Compare commits

...

3 Commits

Author SHA1 Message Date
Aditya Patil
791a74df29 fix: simply clear_cache to invalidate 2026-10-19 18:19:30 +05:30
Aditya Patil
1474193980 perf(native): keep public site images in the media disk cache 2026-10-19 16:08:25 +05:30
Aditya Patil
7b651cf380 fix: drop the workspace logo from notifications and cache workspace list 2026-10-19 15:18:34 +05:30
16 changed files with 227 additions and 99 deletions

View File

@ -11,18 +11,21 @@ import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.service.notification.StatusBarNotification;
import android.text.TextUtils;
import androidx.core.app.NotificationCompat;
import androidx.core.app.Person;
import androidx.core.graphics.drawable.IconCompat;
import com.getcapacitor.JSObject;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
/**
* A message notification: chat-style, with the sender's face per message and a conversation's
* messages stacked, or, for a workspace with a logo, the standard layout with the logo on the right.
* Posted by the notification service, and by the page for a push from another saved site.
* messages stacked. Posted by the notification service, and by the page for a push from another saved site.
*/
final class ConversationNotification {
private ConversationNotification() {}
@ -32,53 +35,42 @@ final class ConversationNotification {
String tag = options.getString("tag");
int id = (int) (System.currentTimeMillis() % Integer.MAX_VALUE);
NotificationManager manager = context.getSystemService(NotificationManager.class);
// A workspace logo needs the standard layout: the conversation one has no picture on the right.
String logoUrl = options.getString("logo");
boolean branded = logoUrl != null && !logoUrl.isEmpty();
String url = branded ? logoUrl : options.getString("image");
// Only the conversation layout stacks earlier messages; the standard one replaces them.
List<NotificationCompat.MessagingStyle.Message> history = branded ? Collections.emptyList() : history(manager, tag);
String url = options.getString("image");
List<NotificationCompat.MessagingStyle.Message> history = history(manager, tag);
Bitmap picture = AvatarCache.cached(context, url);
show(context, manager, options, tag, id, history, picture, branded, false);
String place = place(context, options);
show(context, manager, options, place, tag, id, history, picture, false);
// A picture that has to be fetched arrives after the notification, and updates it in place.
if (picture != null || url == null || url.isEmpty()) return;
Bitmap fetched = AvatarCache.fetch(context, url);
if (fetched != null) show(context, manager, options, tag, id, history, fetched, branded, true);
if (fetched != null) show(context, manager, options, place, tag, id, history, fetched, true);
}
private static void show(
Context context,
NotificationManager manager,
JSObject options,
String place,
String tag,
int id,
List<NotificationCompat.MessagingStyle.Message> history,
Bitmap picture,
boolean branded,
boolean update
) {
String title = options.getString("title", "");
String body = options.getString("body", "");
NotificationCompat.Builder builder = new NotificationCompat.Builder(context, RavenApplication.MESSAGES_CHANNEL)
.setSmallIcon(R.drawable.ic_launcher_foreground);
if (branded) {
builder.setContentTitle(title)
.setContentText(body)
.setSubText(options.getString("site"))
.setStyle(new NotificationCompat.BigTextStyle().bigText(body));
if (picture != null) builder.setLargeIcon(picture);
} else {
// MessagingStyle needs a named device user; only the senders' messages are shown.
NotificationCompat.MessagingStyle style = new NotificationCompat.MessagingStyle(new Person.Builder().setName("You").build())
.setConversationTitle(options.getString("site"))
.setGroupConversation(true);
for (NotificationCompat.MessagingStyle.Message message : history) style.addMessage(message);
Person.Builder sender = new Person.Builder().setName(title);
Bitmap round = circle(picture);
if (round != null) sender.setIcon(IconCompat.createWithBitmap(round));
style.addMessage(body, System.currentTimeMillis(), sender.build());
builder.setStyle(style);
}
// MessagingStyle needs a named device user; only the senders' messages are shown.
NotificationCompat.MessagingStyle style = new NotificationCompat.MessagingStyle(new Person.Builder().setName("You").build())
.setConversationTitle(place)
.setGroupConversation(true);
for (NotificationCompat.MessagingStyle.Message message : history) style.addMessage(message);
Person.Builder sender = new Person.Builder().setName(title);
Bitmap round = circle(picture);
if (round != null) sender.setIcon(IconCompat.createWithBitmap(round));
style.addMessage(body, System.currentTimeMillis(), sender.build());
builder.setStyle(style);
builder.setPriority(NotificationCompat.PRIORITY_HIGH)
.setAutoCancel(true)
// The face arriving must not sound a second time for the same message.
@ -90,6 +82,29 @@ final class ConversationNotification {
manager.notify(tag, tag != null ? 0 : id, notification);
}
/** The header's context: the workspace and the site, each only when there are several to tell apart. */
private static String place(Context context, JSObject options) {
JSObject data = options.getJSObject("data");
List<String> parts = new ArrayList<>();
// The site sends a channel's workspace only when it has several.
String workspace = data == null ? null : data.getString("workspace");
if (workspace != null && !workspace.isEmpty()) parts.add(workspace);
String site = options.getString("site");
if (site != null && !site.isEmpty() && manySites(context)) parts.add(site);
return parts.isEmpty() ? null : TextUtils.join(" · ", parts);
}
/** The saved sites, as the page keeps them in Preferences (apps/web/src/native/sites.ts). */
private static boolean manySites(Context context) {
String sites = context.getSharedPreferences("CapacitorStorage", Context.MODE_PRIVATE).getString("sites", null);
if (sites == null) return false;
try {
return new JSONArray(sites).length() > 1;
} catch (JSONException e) {
return false;
}
}
// Same extras as an FCM tap, so the messaging plugin reports notificationActionPerformed.
private static PendingIntent tapIntent(Context context, int id, JSObject data) {
Intent tap = new Intent(context, MainActivity.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);

View File

@ -38,7 +38,11 @@ final class RavenMediaHandler {
File target = new File(new File(new File(context.getCacheDir(), "media"), folder), file);
if (!isInsideMedia(context, target)) return reject(400, "bad media path");
String range = request.getRequestHeaders().get("Range");
return target.isFile() ? fromDisk(target, range) : fromSite(src, target, range);
if (!target.isFile()) return fromSite(src, target, range);
// Trim goes by the folder's date: a file read often is kept, not just one fetched lately.
//noinspection ResultOfMethodCallIgnored
target.getParentFile().setLastModified(System.currentTimeMillis());
return fromDisk(target, range);
}
// A complete cached file answers Range itself: video seeking never touches the network.
@ -156,32 +160,72 @@ final class RavenMediaHandler {
@Override public void close() throws IOException { in.close(); }
}
/** Copies what the WebView reads into a part file; only a stream read to its end becomes the file. */
/**
* Copies what the WebView reads into a part file; only a stream read to its end becomes the file.
* Caching is best effort: a part file that can't be made or written stops the copy, never the read.
*/
private static final class TeeStream extends InputStream {
private final InputStream in;
private final File target, part;
private final OutputStream out;
private final byte[] one = new byte[1];
private OutputStream out;
private boolean complete;
TeeStream(InputStream in, File target) throws IOException {
TeeStream(InputStream in, File target) {
this.in = in;
this.target = target;
// Own part file per stream: two requests for one file never write into each other.
this.part = new File(target.getPath() + "." + System.nanoTime() + ".part");
//noinspection ResultOfMethodCallIgnored
target.getParentFile().mkdirs();
this.out = new FileOutputStream(part);
try {
this.out = new FileOutputStream(part);
} catch (IOException e) {
// Not cached this time; the read goes on.
}
}
@Override public int read() throws IOException {
return read(one, 0, 1) < 0 ? -1 : one[0] & 0xff;
}
@Override public int read() throws IOException { int b = in.read(); if (b >= 0) out.write(b); else complete = true; return b; }
@Override public int read(byte[] buffer, int off, int len) throws IOException {
int read = in.read(buffer, off, len);
if (read > 0) out.write(buffer, off, read); else complete = true;
// Only -1 ends the stream; 0 is an empty read, and taking it for the end would keep a cut-off file.
if (read > 0) copy(buffer, off, read); else if (read < 0) complete = true;
return read;
}
@Override public void close() throws IOException {
in.close();
out.close();
try {
in.close();
} finally {
keepIfComplete();
}
}
private void keepIfComplete() {
if (out == null) return;
try {
out.close();
} catch (IOException e) {
complete = false;
}
//noinspection ResultOfMethodCallIgnored
if (!complete || !part.renameTo(target)) part.delete();
}
private void copy(byte[] buffer, int off, int len) {
if (out == null) return;
try {
out.write(buffer, off, len);
} catch (IOException e) {
drop();
}
}
private void drop() {
try {
out.close();
} catch (IOException ignored) {
// The part file goes either way.
}
out = null;
//noinspection ResultOfMethodCallIgnored
part.delete();
}
}
}

View File

@ -23,8 +23,6 @@ public class RavenNotificationService extends MessagingService {
options.put("body", data.get("push_body"));
options.put("site", data.get("sitename"));
options.put("image", data.get("image"));
// With a workspace logo the notification leads with it; without one, with the sender's face.
options.put("logo", data.get("workspace_image"));
options.put("tag", data.get("tag"));
JSObject payload = new JSObject();
for (Map.Entry<String, String> entry : data.entrySet()) payload.put(entry.getKey(), entry.getValue());

View File

@ -39,14 +39,14 @@ public class RavenShellPlugin extends Plugin {
}).start();
}
// Until the page says it is listening, a push is drawn here: the seconds before it loads
// would otherwise pass with nothing shown.
// Android draws the site as the conversation's header, so the count decides nothing here.
// A notification reads the saved sites from Preferences itself, so the count decides nothing here.
@PluginMethod
public void setSiteCount(PluginCall call) {
call.resolve();
}
// Until the page says it is listening, a push is drawn here: the seconds before it loads
// would otherwise pass with nothing shown.
@PluginMethod
public void watchNotifications(PluginCall call) {
RavenApplication.setPageWatching(Boolean.TRUE.equals(call.getBoolean("watching", false)));

View File

@ -52,6 +52,8 @@ final class RavenMediaHandler: NSObject, WKURLSchemeHandler {
// Least recently used first.
var used: [Int] = []
var waiting: [Int: [(Data?) -> Void]] = [:]
// A body without a size to check can't be told apart from one cut off: it's served, never kept.
var unsized = false
init(src: URL, target: URL) { self.src = src; self.target = target }
}
// Net queue only, oldest first.
@ -67,7 +69,12 @@ final class RavenMediaHandler: NSObject, WKURLSchemeHandler {
if schemeTask.request.mainDocumentURL == url { return fail(schemeTask, status: 403) }
let target = folder.appendingPathComponent(host).appendingPathComponent(url.lastPathComponent)
let range = schemeTask.request.value(forHTTPHeaderField: "Range")
if FileManager.default.fileExists(atPath: target.path) { return fromDisk(schemeTask, file: target, range: range) }
if FileManager.default.fileExists(atPath: target.path) {
// Trim goes by the folder's date: a file read often is kept, not just one fetched lately.
let folder = target.deletingLastPathComponent().path
disk.async { try? FileManager.default.setAttributes([.modificationDate: Date()], ofItemAtPath: folder) }
return fromDisk(schemeTask, file: target, range: range)
}
let delivery = Delivery(scheme: schemeTask)
live[ObjectIdentifier(schemeTask)] = delivery
let bearer = token
@ -142,11 +149,16 @@ final class RavenMediaHandler: NSObject, WKURLSchemeHandler {
request.setValue("Bearer \(bearer)", forHTTPHeaderField: "Authorization")
let from = index * Self.block
request.setValue("bytes=\(from)-\(from + Self.block - 1)", forHTTPHeaderField: "Range")
session.dataTask(with: request) { data, response, _ in
session.dataTask(with: request) { data, response, error in
let waiters = file.waiting.removeValue(forKey: index) ?? []
guard let http = response as? HTTPURLResponse, let data = data, http.statusCode == 200 || http.statusCode == 206 else {
guard error == nil, let http = response as? HTTPURLResponse, let data = data, http.statusCode == 200 || http.statusCode == 206 else {
return waiters.forEach { $0(nil) }
}
// A compressed body's declared size is the compressed one, so only a plain body is checked.
let size = http.value(forHTTPHeaderField: "Content-Encoding") == nil ? http.expectedContentLength : -1
// A body short of the size the site declared was cut off.
if size >= 0 && Int64(data.count) != size { return waiters.forEach { $0(nil) } }
if size < 0 { file.unsized = true }
if let type = http.value(forHTTPHeaderField: "Content-Type") { file.type = self.inert(type) }
if http.statusCode == 200 {
// A site that ignores ranges sends the whole file: it is every block at once.
@ -192,7 +204,7 @@ final class RavenMediaHandler: NSObject, WKURLSchemeHandler {
/// A file read end to end goes to disk, where replays and seeks are answered at once.
private func keepIfWhole(_ file: File) {
guard let total = file.total else { return }
guard let total = file.total, !file.unsized else { return }
let count = (total + Self.block - 1) / Self.block
guard file.blocks.count == count else { return }
// The blocks themselves, in order: joining them first would hold the file in memory twice.

View File

@ -17,7 +17,7 @@ enum AvatarStore {
}
/// Keeps a downloaded avatar as an icon-sized jpeg and returns where it landed.
/// iOS attaches a jpeg, png or gif only, and a profile picture is often neither.
/// A profile picture straight off a phone is megabytes; the icon needs a few kilobytes of it.
static func keep(_ downloaded: URL, for url: URL) -> URL? {
guard let file = path(for: url), let icon = icon(from: downloaded) else { return nil }
try? FileManager.default.removeItem(at: file)

View File

@ -15,7 +15,9 @@ final class NotificationService: UNNotificationServiceExtension {
private static let onQueue = DispatchSpecificKey<Bool>()
// Who sent the message, which names the person the notification is shown as coming from.
private var sender: String?
// The site, named beside the sender when this device has more than one to tell apart.
// The channel's workspace, sent only when the site has several.
private var workspace: String?
// The site, named under the sender when this device has more than one to tell apart.
private var site: String?
private var manySites: Bool {
(UserDefaults(suiteName: "group.raven.thecommit.company")?.integer(forKey: "siteCount") ?? 0) > 1
@ -49,13 +51,11 @@ final class NotificationService: UNNotificationServiceExtension {
if content.threadIdentifier.isEmpty, let tag = info["tag"] as? String { content.threadIdentifier = tag }
sender = info["from_user"] as? String
// Both pictures at once: the sender's face on the left, a channel's workspace logo on the right.
workspace = info["workspace"] as? String
var face: URL?
var logo: URL?
let both = DispatchGroup()
obtain(url(from: info), into: both) { face = $0 }
obtain(logoURL(from: info), into: both) { logo = $0 }
both.notify(queue: queue) { self.finish(face: face, logo: logo) }
let fetched = DispatchGroup()
obtain(url(from: info), into: fetched) { face = $0 }
fetched.notify(queue: queue) { self.finish(face: face) }
}
/// A picture from the store, or fetched into it; nil when there is none or it fails.
@ -90,24 +90,24 @@ final class NotificationService: UNNotificationServiceExtension {
/// sender to name, the notification is shown as it stands.
private func asMessage(_ content: UNMutableNotificationContent, face: URL?) -> UNNotificationContent {
guard !content.title.isEmpty else { return content }
// A message notification has room for the sender alone: the site comes along only when
// this device is signed in to more than one and the name would be ambiguous.
let name = manySites ? [content.title, site].compactMap { $0 }.joined(separator: " · ") : content.title
let image = face.flatMap { try? Data(contentsOf: $0) }.map { INImage(imageData: $0) }
let handle = INPersonHandle(value: sender ?? content.title, type: .unknown)
let person = INPerson(
personHandle: handle,
nameComponents: nil,
displayName: name,
displayName: content.title,
image: image,
contactIdentifier: nil,
customIdentifier: handle.value
)
// The line under the sender: the workspace and site, each only when there are several.
let place = [workspace, manySites ? site : nil].compactMap { $0 }.filter { !$0.isEmpty }.joined(separator: " · ")
let intent = INSendMessageIntent(
recipients: nil,
// iOS shows the group's name only for a group, which needs a recipient besides this user.
recipients: place.isEmpty ? nil : [Self.groupMember],
outgoingMessageType: .outgoingMessageText,
content: content.body,
speakableGroupName: nil,
speakableGroupName: place.isEmpty ? nil : INSpeakableString(spokenPhrase: place),
conversationIdentifier: content.threadIdentifier.isEmpty ? nil : content.threadIdentifier,
serviceName: nil,
sender: person,
@ -121,26 +121,25 @@ final class NotificationService: UNNotificationServiceExtension {
return (try? content.updating(from: intent)) ?? content
}
private func finish(face: URL? = nil, logo: URL? = nil) {
private static let groupMember = INPerson(
personHandle: INPersonHandle(value: "raven-member", type: .unknown),
nameComponents: nil,
displayName: nil,
image: nil,
contactIdentifier: nil,
customIdentifier: "raven-member"
)
private func finish(face: URL? = nil) {
let body: () -> Void = {
guard let deliver = self.deliver, let content = self.content else { return }
self.deliver = nil
deliver(self.withLogo(self.asMessage(content, face: face), logo: logo))
deliver(self.asMessage(content, face: face))
}
// The pictures arriving call this on the queue already; the timeout calls it from elsewhere.
// The face arriving calls this on the queue already; the timeout calls it from elsewhere.
if DispatchQueue.getSpecific(key: Self.onQueue) == true { body() } else { queue.sync(execute: body) }
}
/// The workspace logo as the picture on the right, a copy since iOS moves an attachment away.
private func withLogo(_ content: UNNotificationContent, logo: URL?) -> UNNotificationContent {
guard let logo = logo, let dressed = content.mutableCopy() as? UNMutableNotificationContent else { return content }
let copy = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString + ".jpg")
guard (try? FileManager.default.copyItem(at: logo, to: copy)) != nil,
let attachment = try? UNNotificationAttachment(identifier: "workspace", url: copy) else { return content }
dressed.attachments = [attachment]
return dressed
}
/// The site's hostname, which is the name it puts on a title it words itself.
private func host(from info: [AnyHashable: Any]) -> String? {
if let base = info["base_url"] as? String, let host = URL(string: base)?.host { return host }
@ -148,12 +147,6 @@ final class NotificationService: UNNotificationServiceExtension {
return sitename?.isEmpty == false ? sitename : nil
}
/// A channel's workspace logo; a direct message has none.
private func logoURL(from info: [AnyHashable: Any]) -> URL? {
guard let logo = info["workspace_image"] as? String, !logo.isEmpty else { return nil }
return URL(string: logo)
}
/// The sender's face: the site puts it in the data, and the relay in its own options.
private func url(from info: [AnyHashable: Any]) -> URL? {
if let image = info["image"] as? String, !image.isEmpty { return URL(string: image) }

View File

@ -9,10 +9,16 @@ describe("fileSrc", () => {
it("returns the path unchanged in the browser", () => {
expect(fileSrc("/private/files/a.png")).toBe("/private/files/a.png")
})
it("prefixes public paths in native", () => {
it("routes public site files in native through the media proxy, which keeps them on disk", () => {
vi.stubEnv("VITE_NATIVE", "1")
setActiveSite("https://a.com", () => "AT")
expect(fileSrc("/files/a.png")).toBe("https://a.com/files/a.png")
expect(fileSrc("/files/a.png")).toMatch(/^raven-media:\/\/[0-9a-z]+\/a\.png\?src=https%3A%2F%2Fa\.com%2Ffiles%2Fa\.png$/)
})
it("prefixes other site paths in native, and leaves other sites alone", () => {
vi.stubEnv("VITE_NATIVE", "1")
setActiveSite("https://a.com", () => "AT")
expect(fileSrc("/assets/raven/a.svg")).toBe("https://a.com/assets/raven/a.svg")
expect(fileSrc("https://b.com/files/a.png")).toBe("https://b.com/files/a.png")
})
it("routes private paths in native through the media proxy", () => {
vi.stubEnv("VITE_NATIVE", "1")

View File

@ -9,13 +9,16 @@ export const sitePath = (src: string): string => {
return url.startsWith(`${origin}/`) ? url.slice(origin.length) : url
}
const isSiteFile = (path: string) => path.startsWith("/files/") || isPrivateFile(path)
/** Site file path, or a saved address of one, → something an <img>, <video>, or <audio> can load. */
export const fileSrc = (url: string): string => {
const path = sitePath(url)
// In the browser the site is the page's own origin, and an <img> carries the session itself.
if (!import.meta.env.VITE_NATIVE) return path
// A public file loads straight from the site; only private ones need the bearer the proxy adds.
return isPrivateFile(path) ? mediaSrc(path) : siteUrl(path)
// Site files go through the media proxy: it adds the bearer private ones need and keeps each on disk.
// Loaded directly, the WebView's cache follows the site's headers, and bench sends none for /files/.
return isSiteFile(path) ? mediaSrc(path) : siteUrl(path)
}
export const useFileSrc = (url?: string): string | undefined => (url ? fileSrc(url) : undefined)

View File

@ -58,7 +58,8 @@ const boot = async () => {
setSessionLostHandler(() => { reloginAt(session.site.url) })
// Storage keys and URLs are scoped from here on; boot needs the token.
setActiveSite(session.site.url, session.getToken)
void import("./media").then((m) => m.setMediaSession(session.getToken()))
// Site files load through the media proxy, which turns everything away until it has the session.
const mediaSession = import("./media").then((m) => m.setMediaSession(session.getToken())).catch(() => { })
// With a cached boot the app opens at once, and the site's answer lands behind it.
const cached = bootFromCache()
const fresh = loadBoot()
@ -72,6 +73,7 @@ const boot = async () => {
const socket = new NativeSocket({ url: socketUrl(session.site.url), namespace: session.site.sitename, origin: session.site.url }, session.getToken)
setTokenRefreshedHandler((token) => { socket.setToken(token); void import("./media").then((m) => m.setMediaSession(token)) })
socket.start().catch(() => { })
await mediaSession
render(<App native={{ url: session.site.url, siteName: session.site.sitename, getToken: session.getToken, onRequestError, socket: socket as unknown as FrappeConfig["socket"] }} />)
initNativePush()
// An app opened from the cache still answers to a revoked session.

View File

@ -2,6 +2,7 @@ import frappe
from frappe import _
from frappe.query_builder import JoinType, Order
from frappe.query_builder.functions import Coalesce
from frappe.utils.caching import redis_cache
from raven.utils import delete_channel_members_cache, delete_workspace_members_cache
@ -55,6 +56,12 @@ def get_list():
return all_workspaces.run(as_dict=True)
@redis_cache()
def get_workspace_names() -> dict[str, str]:
"""Every workspace's name by its ID. Cached since this won't change frequently."""
return dict(frappe.get_all("Raven Workspace", fields=["name", "workspace_name"], as_list=True))
@frappe.whitelist()
def join_workspace(workspace: str):
"""

View File

@ -7,6 +7,7 @@ from frappe.frappeclient import FrappeClient
from frappe.utils import get_datetime, get_system_timezone
from pytz import timezone, utc
from raven.api.workspaces import get_workspace_names
from raven.raven_cloud_notifications import get_site_name
from raven.utils import get_channel_members, make_api_call
@ -18,6 +19,13 @@ def with_site(title: str) -> str:
return f"{title} · {get_site_name()}"
def shown_workspace(workspace: str) -> str:
"""A push names the channel's workspace only when the site has several to tell apart."""
workspaces = get_workspace_names()
# A workspace deleted under the channel leaves the notification without one, not unsent.
return workspaces.get(workspace, "") if len(workspaces) > 1 else ""
def site_tag(key: str) -> str:
"""Per site: a shared tag lets one site replace or clear another site's notification."""
return f"{get_site_name()}:{key}"
@ -154,15 +162,6 @@ def send_push_notification_via_raven_cloud(message, raven_settings):
image = get_image_absolute_url(message_owner_image)
# A channel is shown as its workspace: two workspaces can name a channel the same.
workspace_name, workspace_image = "", ""
if not channel_doc.is_direct_message and channel_doc.workspace:
# A workspace deleted under the channel leaves the notification without one, not unsent.
workspace_name, logo = frappe.get_cached_value(
"Raven Workspace", channel_doc.workspace, ["workspace_name", "logo"]
) or ("", "")
workspace_image = get_image_absolute_url(logo) if logo else ""
data = {
"base_url": frappe.utils.get_url(allow_header_override=False),
"message_url": url,
@ -177,8 +176,12 @@ def send_push_notification_via_raven_cloud(message, raven_settings):
"is_thread": "1" if channel_doc.is_thread else "0",
"creation": get_milliseconds_since_epoch(message.creation),
"image": image if image else "",
"workspace": workspace_name or "",
"workspace_image": workspace_image or "",
# A channel is shown with its workspace: two workspaces can name a channel the same.
"workspace": (
shown_workspace(channel_doc.workspace)
if channel_doc.workspace and not channel_doc.is_direct_message
else ""
),
}
if replied_users:

View File

@ -23,9 +23,22 @@ class RavenWorkspace(Document):
# end: auto-generated types
def after_insert(self):
# A save can't change the name; only insert, rename and delete touch the cached list.
self.invalidate_workspace_list_cache()
if not frappe.flags.in_patch:
self.create_member_for_owner()
def after_rename(self, old, new, merge=False):
self.invalidate_workspace_list_cache()
def after_delete(self):
self.invalidate_workspace_list_cache()
def invalidate_workspace_list_cache(self):
from raven.api.workspaces import get_workspace_names
get_workspace_names.clear_cache()
def on_trash(self):
# Delete all members when the workspace is deleted
frappe.db.delete("Raven Workspace Member", {"workspace": self.name})

View File

@ -4,6 +4,8 @@
import frappe
from frappe.tests import IntegrationTestCase, UnitTestCase
from raven.api.workspaces import get_workspace_names
# On IntegrationTestCase, the doctype test records and all
# link-field test record depdendencies are recursively loaded
# Use these module variables to add/remove to/from that list
@ -83,3 +85,20 @@ class TestRavenWorkspace(IntegrationTestCase):
self.assertRaises(
frappe.DoesNotExistError, frappe.get_doc, "Raven Workspace Member", member.name
)
def test_workspace_cache_follows_insert_rename_and_delete(self):
self.addCleanup(frappe.db.rollback)
# Filled before the changes, so each step has to clear it.
get_workspace_names()
workspace = frappe.get_doc(
{"doctype": "Raven Workspace", "workspace_name": "Cache North", "type": "Public"}
).insert()
self.assertEqual(get_workspace_names().get(workspace.name), "Cache North")
frappe.rename_doc("Raven Workspace", workspace.name, "Cache South")
self.assertNotIn(workspace.name, get_workspace_names())
self.assertIn("Cache South", get_workspace_names())
frappe.delete_doc("Raven Workspace", "Cache South")
self.assertNotIn("Cache South", get_workspace_names())

View File

@ -5,6 +5,7 @@ import frappe
from frappe import _
from frappe.model.document import Document
from raven.api.workspaces import get_workspace_names
from raven.utils import (
create_members_added_system_message,
delete_channel_members_cache,
@ -302,9 +303,9 @@ class RavenChannel(Document):
self.dm_user_1 = self.dm_user_2 = None
if not self.is_direct_message and not self.workspace and not self.is_dm_thread:
workspaces = frappe.get_all("Raven Workspace")
workspaces = get_workspace_names()
if len(workspaces) == 1:
self.workspace = workspaces[0].name
self.workspace = next(iter(workspaces))
self.set_pinned_messages_string()

View File

@ -1,7 +1,9 @@
from unittest.mock import patch
import frappe
from frappe.tests import IntegrationTestCase
from raven.notification import site_tag, split_for_app, with_site
from raven.notification import shown_workspace, site_tag, split_for_app, with_site
from raven.raven_cloud_notifications import get_site_name
@ -19,6 +21,16 @@ class TestNotificationLabels(IntegrationTestCase):
self.assertTrue(tag.startswith(f"{host}:"))
self.assertEqual(tag[len(host) + 1 :], "abc123")
def test_workspace_is_named_only_when_the_site_has_several(self):
with patch("raven.notification.get_workspace_names", return_value={"north": "North"}):
self.assertEqual(shown_workspace("north"), "")
with patch(
"raven.notification.get_workspace_names",
return_value={"north": "North", "south": "South"},
):
self.assertEqual(shown_workspace("north"), "North")
self.assertEqual(shown_workspace("deleted-workspace"), "")
class TestAppPushSplit(IntegrationTestCase):
"""Web keeps the plain title, the iOS app gets the site in it, the Android app draws its own."""