Compare commits
3 Commits
develop
...
workspace-
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
791a74df29 | ||
|
|
1474193980 | ||
|
|
7b651cf380 |
@ -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);
|
||||
|
||||
@ -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();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ -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());
|
||||
|
||||
@ -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)));
|
||||
|
||||
@ -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.
|
||||
|
||||
@ -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)
|
||||
|
||||
@ -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) }
|
||||
|
||||
@ -13,9 +13,9 @@ import { siteUrl } from "@lib/site"
|
||||
import ravenLogo from "@raven/public/raven_logo.svg"
|
||||
|
||||
const LINKS = [
|
||||
{ label: _("Documentation"), href: "https://docs.frappe.io/raven" },
|
||||
{ label: _("GitHub"), href: "https://github.com/frappe/raven" },
|
||||
{ label: _("Website"), href: "https://ravenchat.ai" },
|
||||
// { label: _("Documentation"), href: "https://docs.ravenapp.cloud" },
|
||||
]
|
||||
|
||||
/** Version of every installed app, plus links. Same footer as the mobile profile page. */
|
||||
|
||||
@ -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")
|
||||
|
||||
@ -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)
|
||||
|
||||
@ -91,13 +91,10 @@
|
||||
}
|
||||
|
||||
/* Setup page motion. Off under reduced motion: the page switches instantly. */
|
||||
/* Animations that end on the resting look fill backwards, not both. Safari keeps an element
|
||||
composited for as long as an animation holds its last frame, and leaves blurred-in text
|
||||
soft until something repaints (WebKit bug 257023). Only the ones that end hidden hold. */
|
||||
/* Steps blur out, leave a short gap, then blur back in sharp. */
|
||||
@utility animate-setup-step-in {
|
||||
@media (prefers-reduced-motion: no-preference) {
|
||||
animation: setup-blur-in 250ms ease-out 100ms backwards;
|
||||
animation: setup-blur-in 250ms ease-out 100ms both;
|
||||
}
|
||||
}
|
||||
|
||||
@ -109,26 +106,26 @@
|
||||
|
||||
@utility animate-setup-blur-in {
|
||||
@media (prefers-reduced-motion: no-preference) {
|
||||
animation: setup-blur-in 300ms ease-out backwards;
|
||||
animation: setup-blur-in 300ms ease-out both;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@utility animate-setup-open {
|
||||
@media (prefers-reduced-motion: no-preference) {
|
||||
animation: setup-open 400ms cubic-bezier(0.16, 1, 0.3, 1) backwards;
|
||||
animation: setup-open 400ms cubic-bezier(0.16, 1, 0.3, 1) both;
|
||||
}
|
||||
}
|
||||
|
||||
@utility animate-setup-open-late {
|
||||
@media (prefers-reduced-motion: no-preference) {
|
||||
animation: setup-open 400ms cubic-bezier(0.16, 1, 0.3, 1) 80ms backwards;
|
||||
animation: setup-open 400ms cubic-bezier(0.16, 1, 0.3, 1) 80ms both;
|
||||
}
|
||||
}
|
||||
|
||||
@utility animate-setup-item-in {
|
||||
@media (prefers-reduced-motion: no-preference) {
|
||||
animation: setup-item-in 250ms ease-out backwards;
|
||||
animation: setup-item-in 250ms ease-out both;
|
||||
}
|
||||
}
|
||||
|
||||
@ -142,7 +139,7 @@
|
||||
@utility animate-setup-check {
|
||||
@media (prefers-reduced-motion: no-preference) {
|
||||
stroke-dasharray: 32;
|
||||
animation: setup-check 400ms cubic-bezier(0.33, 1, 0.68, 1) 150ms backwards;
|
||||
animation: setup-check 400ms cubic-bezier(0.33, 1, 0.68, 1) 150ms both;
|
||||
}
|
||||
}
|
||||
|
||||
@ -158,30 +155,29 @@
|
||||
/* HR step: two app logos come together from either side once the step has faded in, the × growing between them. */
|
||||
@utility animate-setup-join-left {
|
||||
@media (prefers-reduced-motion: no-preference) {
|
||||
animation: setup-join-left 900ms cubic-bezier(0.33, 1, 0.68, 1) 350ms backwards;
|
||||
animation: setup-join-left 900ms cubic-bezier(0.33, 1, 0.68, 1) 350ms both;
|
||||
}
|
||||
}
|
||||
|
||||
@utility animate-setup-join-right {
|
||||
@media (prefers-reduced-motion: no-preference) {
|
||||
animation: setup-join-right 900ms cubic-bezier(0.33, 1, 0.68, 1) 350ms backwards;
|
||||
animation: setup-join-right 900ms cubic-bezier(0.33, 1, 0.68, 1) 350ms both;
|
||||
}
|
||||
}
|
||||
|
||||
@utility animate-setup-join-mark {
|
||||
@media (prefers-reduced-motion: no-preference) {
|
||||
animation: setup-join-mark 900ms cubic-bezier(0.33, 1, 0.68, 1) 350ms backwards;
|
||||
animation: setup-join-mark 900ms cubic-bezier(0.33, 1, 0.68, 1) 350ms both;
|
||||
}
|
||||
}
|
||||
|
||||
/* The sharp end is `none`, not `blur(0)`, so no filter is left on the element afterwards. */
|
||||
@keyframes setup-blur-in {
|
||||
from { opacity: 0; filter: blur(6px); }
|
||||
to { opacity: 1; filter: none; }
|
||||
to { opacity: 1; filter: blur(0); }
|
||||
}
|
||||
|
||||
@keyframes setup-blur-out {
|
||||
from { opacity: 1; filter: none; }
|
||||
from { opacity: 1; filter: blur(0); }
|
||||
to { opacity: 0; filter: blur(6px); }
|
||||
}
|
||||
|
||||
|
||||
@ -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.
|
||||
|
||||
@ -1,82 +0,0 @@
|
||||
# TODO: product issues found while writing the user docs
|
||||
|
||||
Found in October 2026 while checking docs.frappe.io/raven against the code and the demo site. The docs describe only what works today. When an item is fixed, update the docs page named in brackets.
|
||||
|
||||
## Notifications
|
||||
|
||||
- [ ] Per-channel notification options do nothing. The Push notifications and In-app notifications rows in the channel drawer keep local state only (`ChannelSettingsDrawer/ChannelSettingsTab.tsx`), and the channel header menu's All Notifications / Mentions Only / Mute Channel items have empty click handlers (`ChannelHeader/ChannelMenu.tsx`). Only the bell in Settings > Channels works, and the backend has no "mentions only" level. [Mute a channel]
|
||||
- [ ] Quiet hours default: the Raven User field defaults to "No Nudge", while `boot.py` and code comments still treat "Nudge" as the default. Pick one. [Quiet hours]
|
||||
- [ ] The quiet hours banner always shows the Mac shortcut ⌘⇧↵, also on Windows and Linux. [Quiet hours]
|
||||
|
||||
## Channels
|
||||
|
||||
- [ ] "Create a new channel" shows even when the workspace has "Only admins can create channels" on. Other members get an error. [Create a channel]
|
||||
- [ ] A Raven Admin who is a channel member but not a channel admin sees "Remove from channel" enabled (`canManageChannel`), but the server only lets channel admins remove members (`raven/permissions.py`, `channel_member_has_permission`). [Add and remove members]
|
||||
- [ ] Any channel member may add people on the server, but the Add button only shows for channel admins and Raven Admins. Decide which is right. [Add and remove members]
|
||||
- [ ] Rows in the channel drawer's Threads tab look clickable but have no click handler (`ChannelSettingsDrawer/ChannelThreads.tsx`). [Channel files, links, threads and pins]
|
||||
- [ ] The Favorites star tooltip always says "Add to Favorites", even for a favorite. [Organize your sidebar]
|
||||
- [ ] Leave in Settings > Channels leaves at once; Leave in the channel drawer asks first. Make them the same. [Join and leave channels]
|
||||
- [ ] The sidebar filters only apply at 15 or more channels (`packages/lib/utils/buildChannelSidebarData.ts`, `FILTER_MIN_CHANNELS`), and never hide Open, Favorite or grouped channels. The setting's own description says neither. [Preferences]
|
||||
|
||||
## Messages
|
||||
|
||||
- [ ] Settings > Appearance says "4+ images always use the carousel", but `MessageImages.tsx` uses the carousel for 5 or more (`images.length > 4`). [Files and links]
|
||||
- [ ] A pasted link to a document on the same site (/app, /desk) gets no preview card. Only the composer's document button makes a card. [Share documents in a message]
|
||||
- [ ] Custom emoji show as raw shortcodes (":lumen:") in search results on mobile. [Search]
|
||||
- [ ] `hide_link_preview` exists on the message, but nothing in the UI sets it. [Files and links]
|
||||
|
||||
## Threads and search
|
||||
|
||||
- [ ] The Threads page still has an "AI Agents" filter, on desktop and mobile, though AI is deprecated. [Threads]
|
||||
- [ ] The Threads empty state says 'Create Thread'; the menu item is "Create thread".
|
||||
- [ ] "Unread only" on the Threads page's Other tab is always empty, because those threads are never unread.
|
||||
- [ ] Search builds a "Clear all" action for active filters but never shows it. [Search]
|
||||
|
||||
## Workspaces and users
|
||||
|
||||
- [ ] "Can only join via invite?" can only be set in Desk. The web app hides Join for such workspaces, but the server still lets anyone join a public one.
|
||||
- [ ] Add User with one workspace pre-ticks it (disabled, can't untick) even when the System Manager is not that workspace's admin, so `invite_user` fails the write check (`AddUserDialog.tsx` defaultValues, `WorkspaceAccessPicker`). [Add people to Raven]
|
||||
- [ ] Typo in `WorkspaceAccessPicker`: "cannot manage it's members" should be "its".
|
||||
- [ ] The DM header's "View profile" opens the panel on its Files tab. [Direct messages]
|
||||
|
||||
## Settings and permissions
|
||||
|
||||
- [ ] Webhooks and Scheduled Messages tabs show to Raven Admins (`isRavenSettingsAdmin`), but Raven Webhook and Raven Scheduler Event give permission to System Manager only, and Scheduled Messages also needs System Manager to create the Server Script. [Webhooks] [Recurring bot messages]
|
||||
- [ ] Emojis: the delete button shows on every row; people who are not admins can only delete emoji they added and get a permission error on others. [Custom emoji]
|
||||
- [ ] Settings placeholders name specific document types ("Salary Slip Notification", `doc.employee_name`).
|
||||
- [ ] Ctrl/⌘ + / did not open Settings in Playwright's Chrome on a Mac. Check by hand.
|
||||
|
||||
## Webhooks and bots
|
||||
|
||||
- [ ] Channel Member Added and Channel Member Deleted triggers: `RavenWebhook.get_doctype_and_event` uses labels that don't match the Select options, so the webhook gets no doctype. Left out of the docs. [Webhooks]
|
||||
- [ ] Disabling a webhook does nothing: `Raven Webhook.enabled` is never copied to the Frappe Webhook. [Webhooks]
|
||||
- [ ] Conditions the UI offers that the backend rejects or ignores: Channel on Message Reacted On (error), Channel Type on message and member triggers (error), User on Channel Created/Deleted (error), User on User Added/Deleted (ignored, fires for every user). [Webhooks]
|
||||
- [ ] Data and Headers rows can only be added after creation, never removed or updated (`set_webhook_data_and_headers`). [Webhooks]
|
||||
- [ ] Deleting a webhook uses `frappe.db.delete` in `on_trash`, which skips the webhook cache, so it may keep firing until the cache clears. Not tested.
|
||||
- [ ] Message Edited fires on any save of the message record, not only text edits.
|
||||
- [ ] Webhook requests send a JSON body while the record says "Form URL-Encoded", with no Content-Type header. [Webhooks]
|
||||
- [ ] Incoming webhook: opening an existing record in Desk marks it "Not Saved" (the form script calls `set_value` on `webhook_url` in refresh). The Bot field links to Raven User, so it also lists people. Empty content posts an empty message. [Incoming webhooks]
|
||||
- [ ] Agents live under the AI group in Settings, though AI is deprecated. Move Agents out of the AI group. [Agents]
|
||||
- [ ] The agent form in Settings has no image field; an agent's picture can only be set in Desk. [Agents]
|
||||
- [ ] The "Is AI Agent" description still says "Check to enable AI features for this bot". [Agents]
|
||||
|
||||
## Frappe apps and HR
|
||||
|
||||
- [ ] Message actions: the Server Script "View Docs" sample uses `frappe.form_dict.values.field1`, which fails (`values` is a dict method on form_dict). Use `frappe.form_dict.get("values")` and `.get("field")`. In `MessageActionForm.tsx` (EXAMPLES). [Message actions]
|
||||
- [ ] Message actions: Edit Field shows an empty Field box when the field type is not in `VALID_FIELD_TYPES` (`messageActionFieldUtils.ts`), for example Text Editor. [Message actions]
|
||||
- [ ] Frappe HR department channels are only created for departments made after the setting is turned on, are skipped when the company has no workspace mapping (a code comment says a default workspace is used), and employees whose User ID is set later are not added (TODO in `employee.py`). [Frappe HR]
|
||||
- [ ] A broken document notification condition blocks saving the document. [Document notifications]
|
||||
|
||||
## Push and mobile
|
||||
|
||||
- [ ] Frappe Cloud sites are set up for push automatically only when the server config has `raven_push_notification_server_url`. Confirm every Frappe Cloud server has it. [Set up push notifications]
|
||||
- [ ] README says the apps connect to "Raven 3 or later"; the app requires 3.1.0 (`MIN_SITE_VERSION`).
|
||||
- [ ] The Add site screen's placeholder is `raven.frappe.cloud`; the docs use `yourcompany.frappe.cloud`.
|
||||
|
||||
## Demo site
|
||||
|
||||
- [ ] Maya is not a workspace admin of Lumen Cycles or Dealers (only Administrator is), so some docs shots fake the admin view in the browser.
|
||||
- [ ] Maya is a member of every public channel, so there is no "Join" shot.
|
||||
- [ ] Server scripts are off, so the seeded recurring message never runs.
|
||||
- [ ] Suresh Pillai does not show in the @ mention list (probably disabled).
|
||||
- [ ] The demo site shows as 127.0.0.1:8028 in the mobile site picker.
|
||||
@ -6,28 +6,6 @@ from raven.utils import get_channel_members as get_channel_members_util
|
||||
from raven.utils import get_workspace_members
|
||||
|
||||
|
||||
def build_member_entry(user_obj, channel_member) -> dict | None:
|
||||
"""One member's row for the member list, or None when there's no matching
|
||||
Raven User record (e.g. a workspace member whose Raven User record was
|
||||
removed). The caller must skip a None entry instead of indexing into it —
|
||||
a workspace can list a member with no Raven User doc, and that one bad
|
||||
row must never crash the whole list."""
|
||||
if user_obj is None:
|
||||
return None
|
||||
|
||||
return {
|
||||
"name": user_obj.name,
|
||||
"full_name": user_obj.full_name,
|
||||
"user_image": user_obj.user_image,
|
||||
"first_name": user_obj.first_name,
|
||||
"type": user_obj.type,
|
||||
"availability_status": user_obj.availability_status,
|
||||
"is_admin": channel_member.get("is_admin", 0),
|
||||
"allow_notifications": channel_member.get("allow_notifications", 1),
|
||||
"channel_member_name": channel_member.get("name", None),
|
||||
}
|
||||
|
||||
|
||||
@frappe.whitelist(methods=["GET"])
|
||||
def get_channel_members(channel_id: str):
|
||||
# Check if the user has permission to view the channel
|
||||
@ -55,17 +33,34 @@ def get_channel_members(channel_id: str):
|
||||
channel_member = channel_members.get(workspace_member, {})
|
||||
user_obj = next((u for u in all_users if u.name == workspace_member), None)
|
||||
|
||||
entry = build_member_entry(user_obj, channel_member)
|
||||
if entry:
|
||||
member_object[entry["name"]] = entry
|
||||
member_object[user_obj.name] = {
|
||||
"name": user_obj.name,
|
||||
"full_name": user_obj.full_name,
|
||||
"user_image": user_obj.user_image,
|
||||
"first_name": user_obj.first_name,
|
||||
"type": user_obj.type,
|
||||
"availability_status": user_obj.availability_status,
|
||||
"is_admin": channel_member.get("is_admin", 0),
|
||||
"allow_notifications": channel_member.get("allow_notifications", 1),
|
||||
"channel_member_name": channel_member.get("name", None),
|
||||
}
|
||||
|
||||
else:
|
||||
for member in channel_members:
|
||||
channel_member = channel_members[member]
|
||||
user_obj = next((u for u in all_users if u.name == member), None)
|
||||
|
||||
entry = build_member_entry(user_obj, channel_member)
|
||||
if entry:
|
||||
member_object[entry["name"]] = entry
|
||||
if user_obj:
|
||||
member_object[user_obj.name] = {
|
||||
"name": user_obj.name,
|
||||
"full_name": user_obj.full_name,
|
||||
"user_image": user_obj.user_image,
|
||||
"first_name": user_obj.first_name,
|
||||
"type": user_obj.type,
|
||||
"availability_status": user_obj.availability_status,
|
||||
"is_admin": channel_member.is_admin,
|
||||
"allow_notifications": channel_member.allow_notifications,
|
||||
"channel_member_name": channel_member.name,
|
||||
}
|
||||
|
||||
return member_object
|
||||
|
||||
@ -36,10 +36,7 @@ def is_setup_admin() -> bool:
|
||||
|
||||
|
||||
def _raven_users_without_workspace() -> list[dict]:
|
||||
"""
|
||||
Enabled people in Raven who belong to no workspace, except whoever is asking and the
|
||||
Administrator account, which install puts in Raven but is nobody's teammate.
|
||||
"""
|
||||
"""Enabled people in Raven who belong to no workspace, except whoever is asking."""
|
||||
raven_user = frappe.qb.DocType("Raven User")
|
||||
user = frappe.qb.DocType("User")
|
||||
member = frappe.qb.DocType("Raven Workspace Member")
|
||||
@ -56,7 +53,7 @@ def _raven_users_without_workspace() -> list[dict]:
|
||||
)
|
||||
.where(raven_user.type == "User")
|
||||
.where(raven_user.enabled == 1)
|
||||
.where(raven_user.user.notin(["Administrator", frappe.session.user]))
|
||||
.where(raven_user.user != frappe.session.user)
|
||||
.where(raven_user.user.notin(in_a_workspace))
|
||||
).run(as_dict=True)
|
||||
|
||||
|
||||
@ -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):
|
||||
"""
|
||||
|
||||
@ -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:
|
||||
|
||||
@ -343,7 +343,7 @@
|
||||
"index_web_pages_for_search": 1,
|
||||
"issingle": 1,
|
||||
"links": [],
|
||||
"modified": "2026-10-20 14:12:54.000000",
|
||||
"modified": "2026-10-17 12:00:00.000000",
|
||||
"modified_by": "Administrator",
|
||||
"module": "Raven",
|
||||
"name": "Raven Settings",
|
||||
|
||||
@ -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})
|
||||
|
||||
@ -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())
|
||||
|
||||
@ -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()
|
||||
|
||||
|
||||
@ -1,94 +0,0 @@
|
||||
import frappe
|
||||
from frappe.tests import IntegrationTestCase
|
||||
|
||||
from raven.api.chat import build_member_entry, get_channel_members
|
||||
|
||||
EXTRA_TEST_RECORD_DEPENDENCIES = ["User", "Raven User"]
|
||||
|
||||
|
||||
class TestBuildMemberEntry(IntegrationTestCase):
|
||||
"""Pure-function checks for the row builder `get_channel_members` relies on."""
|
||||
|
||||
def test_none_user_obj_returns_none(self):
|
||||
# No matching Raven User record for this member — the caller must be able
|
||||
# to skip it instead of indexing into None.
|
||||
self.assertIsNone(build_member_entry(None, {}))
|
||||
|
||||
def test_matching_user_obj_returns_entry(self):
|
||||
user_obj = frappe._dict(
|
||||
name="test1@example.com",
|
||||
full_name="Test One",
|
||||
user_image=None,
|
||||
first_name="Test",
|
||||
type="User",
|
||||
availability_status="Available",
|
||||
)
|
||||
entry = build_member_entry(user_obj, {"is_admin": 1, "name": "RCM-1"})
|
||||
self.assertEqual(entry["name"], "test1@example.com")
|
||||
self.assertEqual(entry["is_admin"], 1)
|
||||
self.assertEqual(entry["channel_member_name"], "RCM-1")
|
||||
|
||||
def test_missing_channel_member_fields_default(self):
|
||||
# The Open-channel branch passes `{}` when there's no explicit Raven
|
||||
# Channel Member row (every workspace member is implicitly a member).
|
||||
user_obj = frappe._dict(
|
||||
name="test1@example.com",
|
||||
full_name="Test One",
|
||||
user_image=None,
|
||||
first_name="Test",
|
||||
type="User",
|
||||
availability_status="Available",
|
||||
)
|
||||
entry = build_member_entry(user_obj, {})
|
||||
self.assertEqual(entry["is_admin"], 0)
|
||||
self.assertEqual(entry["allow_notifications"], 1)
|
||||
self.assertIsNone(entry["channel_member_name"])
|
||||
|
||||
|
||||
class TestOpenChannelMembers(IntegrationTestCase):
|
||||
"""
|
||||
Regression test: a workspace member whose Raven User record is gone (e.g. a
|
||||
direct cleanup / data fix that skipped RavenUser.on_trash's own cascade) must
|
||||
be skipped from the Open channel's member list, not crash the whole request.
|
||||
"""
|
||||
|
||||
def setUp(self):
|
||||
frappe.set_user("Administrator")
|
||||
frappe.get_doc("User", "test1@example.com").add_roles("Raven User")
|
||||
self.workspace = frappe.get_doc(
|
||||
{
|
||||
"doctype": "Raven Workspace",
|
||||
"workspace_name": "Chat Members Test Workspace",
|
||||
"type": "Private",
|
||||
}
|
||||
).insert()
|
||||
self.channel = frappe.get_doc(
|
||||
{
|
||||
"doctype": "Raven Channel",
|
||||
"channel_name": "chat-members-open-test",
|
||||
"type": "Open",
|
||||
"workspace": self.workspace.name,
|
||||
}
|
||||
).insert()
|
||||
|
||||
def tearDown(self):
|
||||
frappe.set_user("Administrator")
|
||||
frappe.db.delete("Raven Channel Member", {"channel_id": self.channel.name})
|
||||
frappe.db.delete("Raven Workspace Member", {"workspace": self.workspace.name})
|
||||
self.channel.delete()
|
||||
self.workspace.delete()
|
||||
|
||||
def test_open_channel_skips_member_with_no_raven_user_record(self):
|
||||
user = "test1@example.com"
|
||||
frappe.get_doc(
|
||||
{"doctype": "Raven Workspace Member", "workspace": self.workspace.name, "user": user}
|
||||
).insert(ignore_permissions=True)
|
||||
|
||||
# Simulate the broken state directly: a raw delete bypasses RavenUser.on_trash,
|
||||
# so the Workspace Member row survives with no matching Raven User doc.
|
||||
frappe.db.delete("Raven User", {"user": user})
|
||||
frappe.cache().delete_value(f"raven:workspace_members:{self.workspace.name}")
|
||||
|
||||
members = get_channel_members(self.channel.name)
|
||||
|
||||
self.assertNotIn(user, members)
|
||||
@ -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."""
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user