websocket, refresh token, etc.

This commit is contained in:
Hanashi committed 2026-08-22 22:30:56 -04:00
1 parent 8bb657f5af
commit b585dcb833
14 files changed
+1112 -4

No files matched your search

Generated
+28
View File
@@ -1020,6 +1020,33 @@ dependencies = [
"windows-link 0.2.1",
]
[[package]]
name = "ciborium"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "42e69ffd6f0917f5c029256a24d0161db17cea3997d185db0d35926308770f0e"
dependencies = [
"ciborium-io",
"ciborium-ll",
"serde",
]
[[package]]
name = "ciborium-io"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "05afea1e0a06c9be33d539b876f1ce3692f4afea2cb41f740e7743225ed1c757"
[[package]]
name = "ciborium-ll"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "57663b653d948a338bfb3eeba9bb2fd5fcfaecb9e199e87e1eda4d9e8b240fd9"
dependencies = [
"ciborium-io",
"half",
]
[[package]]
name = "clang-sys"
version = "1.8.1"
@@ -3795,6 +3822,7 @@ name = "midjourney_client"
version = "0.0.1"
dependencies = [
"anyhow",
"ciborium",
"cloudflare_errors",
"cookie_store_wrapper",
"dom_query 0.20.2",
@@ -34,6 +34,9 @@ wreq.workspace = true
# NB: We need to parse HTML to get out the websocket token
dom_query = "0.20.2"
# NB: Midjourney's websocket sends server->client frames as CBOR.
ciborium = "0.2"
[dev-dependencies]
filesys.workspace = true
test_data.workspace = true
@@ -1,2 +1,2 @@
pub mod midjourney_hostname;
pub mod midjourney_websocket_client;
pub mod websocket;
@@ -0,0 +1,127 @@
/// A single in-progress preview image carried on the websocket during a job.
///
/// Midjourney streams four images (indices 0-3) that refine over successive
/// diffusion steps. Each websocket progress frame may carry one preview per
/// image for the current step; the previews grow sharper as the step count
/// climbs. The final, full-resolution image is NOT delivered here — it is
/// fetched over HTTP once the job reaches `completed` (see the `imagine`
/// endpoint).
#[derive(Clone)]
pub struct JobStepImage {
/// Which of the four grid images this is, in `[0, 4)`.
pub image_index: u8,
/// The diffusion step this preview was rendered at (larger = more refined).
pub step: u32,
/// The image encoding. Observed to be JPEG in practice.
pub format: MidjourneyImageFormat,
/// The raw encoded image bytes.
pub bytes: Vec<u8>,
}
/// The encoding of a websocket preview image, taken from the file extension in
/// the frame and cross-checked against the leading magic bytes.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum MidjourneyImageFormat {
Jpeg,
Webp,
Png,
Other(String),
}
impl JobStepImage {
/// Parse one `files` entry, whose key looks like `"0_step_5.jpeg"`.
/// Returns `None` if the key does not match the expected shape.
pub fn from_file_entry(key: &str, bytes: Vec<u8>) -> Option<Self> {
// "0_step_5.jpeg" -> index "0", rest "step_5.jpeg"
let (index_str, rest) = key.split_once('_')?;
let image_index = index_str.parse::<u8>().ok()?;
// "step_5.jpeg" -> "5.jpeg"
let rest = rest.strip_prefix("step_")?;
// "5.jpeg" -> step "5", extension "jpeg"
let (step_str, extension) = rest.split_once('.')?;
let step = step_str.parse::<u32>().ok()?;
let format = MidjourneyImageFormat::infer(extension, &bytes);
Some(Self {
image_index,
step,
format,
bytes,
})
}
}
impl MidjourneyImageFormat {
/// Prefer the magic bytes (authoritative), falling back to the extension.
fn infer(extension: &str, bytes: &[u8]) -> Self {
if bytes.len() >= 4 && bytes[0..3] == [0xFF, 0xD8, 0xFF] {
return Self::Jpeg;
}
if bytes.len() >= 12 && &bytes[0..4] == b"RIFF" && &bytes[8..12] == b"WEBP" {
return Self::Webp;
}
if bytes.len() >= 8 && bytes[0..8] == [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A] {
return Self::Png;
}
match extension.to_ascii_lowercase().as_str() {
"jpeg" | "jpg" => Self::Jpeg,
"webp" => Self::Webp,
"png" => Self::Png,
other => Self::Other(other.to_string()),
}
}
pub fn extension(&self) -> &str {
match self {
Self::Jpeg => "jpeg",
Self::Webp => "webp",
Self::Png => "png",
Self::Other(ext) => ext,
}
}
}
impl std::fmt::Debug for JobStepImage {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("JobStepImage")
.field("image_index", &self.image_index)
.field("step", &self.step)
.field("format", &self.format)
.field("bytes", &format!("<{} bytes>", self.bytes.len()))
.finish()
}
}
#[cfg(test)]
mod tests {
use super::*;
const JPEG_MAGIC: &[u8] = &[0xFF, 0xD8, 0xFF, 0xE0, 0x00, 0x10];
#[test]
fn parses_step_file_key() {
let image = JobStepImage::from_file_entry("2_step_14.jpeg", JPEG_MAGIC.to_vec()).unwrap();
assert_eq!(image.image_index, 2);
assert_eq!(image.step, 14);
assert_eq!(image.format, MidjourneyImageFormat::Jpeg);
}
#[test]
fn magic_bytes_override_extension() {
let image = JobStepImage::from_file_entry("0_step_0.png", JPEG_MAGIC.to_vec()).unwrap();
assert_eq!(image.format, MidjourneyImageFormat::Jpeg);
}
#[test]
fn rejects_malformed_keys() {
assert!(JobStepImage::from_file_entry("garbage", vec![]).is_none());
assert!(JobStepImage::from_file_entry("x_step_1.jpeg", vec![]).is_none());
assert!(JobStepImage::from_file_entry("0_notstep_1.jpeg", vec![]).is_none());
}
}
@@ -0,0 +1,214 @@
use crate::client::websocket::midjourney_ws_event::MidjourneyWsEvent;
use crate::credentials::midjourney_user_id::MidjourneyUserId;
use crate::error::midjourney_client_error::MidjourneyClientError;
use log::{debug, warn};
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use tokio::sync::{broadcast, mpsc};
use wreq::ws::WebSocket;
use wreq::ws::message::Message;
/// How many events the broadcast channel buffers. A single job emits ~30
/// frames; this holds many concurrent jobs before a slow consumer lags.
const EVENT_CHANNEL_CAPACITY: usize = 2048;
/// A live, thread-safe handle to an open Midjourney websocket.
///
/// The connection is driven by a background task that owns the raw socket;
/// this handle only talks to it over channels, so it is cheap to `clone` and
/// share across threads. Cloned handles observe the same connection.
///
/// Reading images:
///
/// ```ignore
/// let ws = open_midjourney_websocket(/* ... */).await?;
/// // Submit the job over HTTP, then stream its previews:
/// ws.stream_job(&job_id, |event| {
/// if let MidjourneyWsEvent::Progress(progress) = event {
/// for image in &progress.images {
/// // image.bytes is a JPEG preview for image.image_index at image.step
/// }
/// }
/// }).await?;
/// ```
///
/// For finer control, call [`Self::events`] to get a raw receiver and
/// [`Self::subscribe_to_job`] / [`Self::send_json`] to drive the protocol
/// yourself.
///
/// Dropping the last handle ends the background task and closes the socket.
#[derive(Clone)]
pub struct MidjourneyWebSocket {
inner: Arc<WebSocketInner>,
}
struct WebSocketInner {
user_id: MidjourneyUserId,
outbound: mpsc::UnboundedSender<Message>,
events: broadcast::Sender<Arc<MidjourneyWsEvent>>,
connected: Arc<AtomicBool>,
}
impl MidjourneyWebSocket {
/// Take ownership of a freshly upgraded socket, spawn its driver task, and
/// return a handle. The caller is responsible for the `subscribe_to_user`
/// handshake (see `open_midjourney_websocket`).
pub (crate) fn spawn(user_id: MidjourneyUserId, websocket: WebSocket) -> Self {
let (outbound_tx, outbound_rx) = mpsc::unbounded_channel::<Message>();
let (events_tx, _events_rx) = broadcast::channel::<Arc<MidjourneyWsEvent>>(EVENT_CHANNEL_CAPACITY);
let connected = Arc::new(AtomicBool::new(true));
tokio::spawn(run_websocket_loop(
websocket,
outbound_rx,
events_tx.clone(),
connected.clone(),
));
Self {
inner: Arc::new(WebSocketInner {
user_id,
outbound: outbound_tx,
events: events_tx,
connected,
}),
}
}
/// The user this connection is bound to.
pub fn user_id(&self) -> &MidjourneyUserId {
&self.inner.user_id
}
/// Whether the background task is still running.
pub fn is_connected(&self) -> bool {
self.inner.connected.load(Ordering::SeqCst)
}
/// A new receiver over the decoded event stream. Each call yields an
/// independent receiver that sees events sent *after* it was created, so
/// subscribe before sending the request whose events you want.
pub fn events(&self) -> broadcast::Receiver<Arc<MidjourneyWsEvent>> {
self.inner.events.subscribe()
}
/// Bind this connection to the user (the opening handshake). Normally done
/// for you by `open_midjourney_websocket`.
pub fn subscribe_to_user(&self) -> Result<(), MidjourneyClientError> {
self.send_json(&serde_json::json!({ "type": "subscribe_to_user" }))
}
/// Ask the server to stream progress for a job (after it was submitted over
/// HTTP). Progress frames, including preview images, follow.
pub fn subscribe_to_job(&self, job_id: &str) -> Result<(), MidjourneyClientError> {
self.send_json(&serde_json::json!({ "type": "subscribe_to_job", "job_id": job_id }))
}
/// Send an arbitrary JSON command frame. The escape hatch for protocol
/// messages this handle does not model directly (e.g. `room_new_job`).
pub fn send_json(&self, value: &serde_json::Value) -> Result<(), MidjourneyClientError> {
let text = serde_json::to_string(value)?;
self.send_message(Message::text(text))
}
/// Subscribe to a job and invoke `on_event` for every event belonging to it,
/// returning once the job completes (or erroring if the socket closes first).
///
/// This is the ergonomic path for reading images: each `Progress` event
/// carries the preview `images` for the current step, and the call returns
/// when the `Completed` event arrives.
pub async fn stream_job<F>(
&self,
job_id: &str,
mut on_event: F,
) -> Result<(), MidjourneyClientError>
where
F: FnMut(&MidjourneyWsEvent),
{
let mut receiver = self.events();
self.subscribe_to_job(job_id)?;
loop {
match receiver.recv().await {
Ok(event) => {
if event.job_id() != Some(job_id) {
continue;
}
on_event(&event);
if event.is_terminal() {
return Ok(());
}
}
Err(broadcast::error::RecvError::Lagged(skipped)) => {
warn!("Midjourney websocket consumer lagged, skipped {} events", skipped);
}
Err(broadcast::error::RecvError::Closed) => {
return Err(MidjourneyClientError::WebSocketClosed);
}
}
}
}
/// Politely close the connection. The background task forwards the close
/// frame and then stops. Dropping the last handle does the same implicitly.
pub fn close(&self) {
let _ = self.send_message(Message::Close(None));
}
fn send_message(&self, message: Message) -> Result<(), MidjourneyClientError> {
self.inner
.outbound
.send(message)
.map_err(|_| MidjourneyClientError::WebSocketClosed)
}
}
/// Owns the raw socket: forwards outbound command frames and decodes inbound
/// CBOR frames into events. Ends when the socket closes or all handles drop.
async fn run_websocket_loop(
mut websocket: WebSocket,
mut outbound_rx: mpsc::UnboundedReceiver<Message>,
events_tx: broadcast::Sender<Arc<MidjourneyWsEvent>>,
connected: Arc<AtomicBool>,
) {
loop {
tokio::select! {
maybe_outbound = outbound_rx.recv() => {
match maybe_outbound {
Some(message) => {
if let Err(err) = websocket.send(message).await {
warn!("Midjourney websocket send failed: {}", err);
break;
}
}
// All handles dropped; nothing more will be sent.
None => break,
}
}
maybe_incoming = websocket.recv() => {
match maybe_incoming {
Some(Ok(Message::Binary(bytes))) => {
match MidjourneyWsEvent::from_cbor_frame(&bytes) {
// A send error just means there are no live receivers; that's fine.
Ok(event) => { let _ = events_tx.send(Arc::new(event)); }
Err(err) => warn!("Midjourney websocket frame decode failed: {}", err),
}
}
Some(Ok(Message::Text(text))) => {
debug!("Unexpected text frame from Midjourney websocket: {}", text.as_str());
}
// Ping/Pong are handled by wreq; ignore anything else non-terminal.
Some(Ok(Message::Close(_))) | None => break,
Some(Ok(_)) => {}
Some(Err(err)) => {
warn!("Midjourney websocket receive error: {}", err);
break;
}
}
}
}
}
connected.store(false, Ordering::SeqCst);
debug!("Midjourney websocket loop ended.");
}
@@ -0,0 +1,284 @@
use crate::client::websocket::job_progress::JobStepImage;
use ciborium::value::Value as CborValue;
/// A decoded server-to-client websocket event.
///
/// Midjourney sends these as CBOR binary frames. The variants cover the
/// handshake reply, job lifecycle notifications, and the streaming progress
/// frames that carry preview images.
#[derive(Clone, Debug)]
pub enum MidjourneyWsEvent {
/// Reply to `subscribe_to_user`; the connection is now bound to this user.
UserSuccess {
user_id: String,
},
/// A job was announced in the user's room (echo of `room_new_job`).
RoomNewJob {
job_id: Option<String>,
},
/// Reply to `subscribe_to_job`; progress frames for it will now arrive.
JobSuccess {
job_id: String,
},
/// A progress update. Carries preview images when the frame includes them.
Progress(JobProgress),
/// The job finished. The full-resolution result is fetched over HTTP.
Completed {
job_id: String,
percentage_complete: f64,
},
/// A frame we recognized as CBOR but do not model. `maybe_kind` is its
/// `type` field when present.
Unknown {
maybe_kind: Option<String>,
},
}
/// A single progress frame for a running job.
#[derive(Clone, Debug)]
pub struct JobProgress {
pub job_id: String,
pub maybe_user_id: Option<String>,
/// e.g. `unqueue`, `start_stage`, `running`.
pub current_status: String,
pub percentage_complete: f64,
/// Preview images included in this frame (may be empty).
pub images: Vec<JobStepImage>,
}
impl MidjourneyWsEvent {
/// The job this event concerns, if any. `UserSuccess` and unmodeled frames
/// return `None`.
pub fn job_id(&self) -> Option<&str> {
match self {
Self::UserSuccess { .. } | Self::Unknown { .. } => None,
Self::RoomNewJob { job_id } => job_id.as_deref(),
Self::JobSuccess { job_id } => Some(job_id),
Self::Progress(progress) => Some(&progress.job_id),
Self::Completed { job_id, .. } => Some(job_id),
}
}
/// Whether this event marks the end of a job's progress stream.
pub fn is_terminal(&self) -> bool {
matches!(self, Self::Completed { .. })
}
/// Decode one binary websocket frame (CBOR) into an event.
pub fn from_cbor_frame(bytes: &[u8]) -> Result<Self, MidjourneyWsDecodeError> {
let value: CborValue = ciborium::from_reader(bytes)
.map_err(|err| MidjourneyWsDecodeError(err.to_string()))?;
let entries = match &value {
CborValue::Map(entries) => entries,
_ => return Err(MidjourneyWsDecodeError("frame was not a CBOR map".to_string())),
};
let maybe_kind = get_str(entries, "type");
if let Some(kind) = maybe_kind.as_deref() {
match kind {
"user_success" => {
return Ok(Self::UserSuccess {
user_id: get_str(entries, "user_id").unwrap_or_default(),
});
}
"room_new_job" => {
return Ok(Self::RoomNewJob {
job_id: get_str(entries, "job_id"),
});
}
"job_success" => {
return Ok(Self::JobSuccess {
job_id: get_str(entries, "job_id").unwrap_or_default(),
});
}
_ => {}
}
}
// Progress frames have no `type`, but do carry `current_status`.
if let Some(current_status) = get_str(entries, "current_status") {
let job_id = get_str(entries, "job_id").unwrap_or_default();
let percentage_complete = get_f64(entries, "percentage_complete").unwrap_or(0.0);
if current_status == "completed" {
return Ok(Self::Completed { job_id, percentage_complete });
}
return Ok(Self::Progress(JobProgress {
job_id,
maybe_user_id: get_str(entries, "user_id"),
current_status,
percentage_complete,
images: extract_images(entries),
}));
}
Ok(Self::Unknown { maybe_kind })
}
}
/// The error returned when a websocket frame cannot be decoded as CBOR.
#[derive(Debug)]
pub struct MidjourneyWsDecodeError(pub String);
impl std::fmt::Display for MidjourneyWsDecodeError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "Failed to decode Midjourney websocket frame: {}", self.0)
}
}
impl std::error::Error for MidjourneyWsDecodeError {}
fn extract_images(entries: &[(CborValue, CborValue)]) -> Vec<JobStepImage> {
let files = match map_get(entries, "files") {
Some(CborValue::Map(files)) => files,
_ => return Vec::new(),
};
let mut images = Vec::new();
for (key, value) in files {
let (CborValue::Text(name), CborValue::Bytes(bytes)) = (key, value) else {
continue;
};
if let Some(image) = JobStepImage::from_file_entry(name, bytes.clone()) {
images.push(image);
}
}
images.sort_by_key(|image| (image.step, image.image_index));
images
}
fn map_get<'a>(entries: &'a [(CborValue, CborValue)], key: &str) -> Option<&'a CborValue> {
entries
.iter()
.find(|(k, _)| matches!(k, CborValue::Text(text) if text == key))
.map(|(_, value)| value)
}
/// Read a string field, accepting both a plain text value and a CBOR
/// tag-37 (RFC 8949 UUID) 16-byte value, which Midjourney uses for some
/// `job_id` / `user_id` fields.
fn get_str(entries: &[(CborValue, CborValue)], key: &str) -> Option<String> {
match map_get(entries, key)? {
CborValue::Text(text) => Some(text.clone()),
CborValue::Tag(37, inner) => match inner.as_ref() {
CborValue::Bytes(bytes) if bytes.len() == 16 => Some(format_uuid(bytes)),
CborValue::Text(text) => Some(text.clone()),
_ => None,
},
_ => None,
}
}
fn get_f64(entries: &[(CborValue, CborValue)], key: &str) -> Option<f64> {
match map_get(entries, key)? {
CborValue::Float(float) => Some(*float),
CborValue::Integer(integer) => {
let as_i128: i128 = (*integer).into();
Some(as_i128 as f64)
}
_ => None,
}
}
fn format_uuid(bytes: &[u8]) -> String {
let hex: String = bytes.iter().map(|byte| format!("{:02x}", byte)).collect();
format!(
"{}-{}-{}-{}-{}",
&hex[0..8],
&hex[8..12],
&hex[12..16],
&hex[16..20],
&hex[20..32],
)
}
#[cfg(test)]
mod tests {
use super::*;
fn encode(value: &CborValue) -> Vec<u8> {
let mut buffer = Vec::new();
ciborium::into_writer(value, &mut buffer).unwrap();
buffer
}
fn text(value: &str) -> CborValue {
CborValue::Text(value.to_string())
}
#[test]
fn decodes_user_success() {
let frame = encode(&CborValue::Map(vec![
(text("type"), text("user_success")),
(text("user_id"), text("26c9d38d-1f71-49c7-a356-b29dac58b54c")),
]));
let event = MidjourneyWsEvent::from_cbor_frame(&frame).unwrap();
let MidjourneyWsEvent::UserSuccess { user_id } = event else {
panic!("expected UserSuccess, got {event:?}");
};
assert_eq!(user_id, "26c9d38d-1f71-49c7-a356-b29dac58b54c");
}
#[test]
fn decodes_tag37_uuid_job_id() {
let uuid_bytes = vec![
0x7d, 0xa8, 0xda, 0x16, 0x69, 0x64, 0x46, 0x5b,
0x92, 0x98, 0xa8, 0x45, 0xa7, 0xfe, 0xc1, 0xbb,
];
let frame = encode(&CborValue::Map(vec![
(text("job_id"), CborValue::Tag(37, Box::new(CborValue::Bytes(uuid_bytes)))),
(text("current_status"), text("completed")),
(text("percentage_complete"), CborValue::Integer(100.into())),
]));
let event = MidjourneyWsEvent::from_cbor_frame(&frame).unwrap();
let MidjourneyWsEvent::Completed { job_id, percentage_complete } = event else {
panic!("expected Completed, got {event:?}");
};
assert_eq!(job_id, "7da8da16-6964-465b-9298-a845a7fec1bb");
assert_eq!(percentage_complete, 100.0);
}
#[test]
fn decodes_progress_with_images() {
let jpeg = vec![0xFF, 0xD8, 0xFF, 0xE0, 0x00, 0x10];
let frame = encode(&CborValue::Map(vec![
(text("current_status"), text("running")),
(text("percentage_complete"), CborValue::Float(5.0)),
(text("job_id"), text("job-1")),
(text("user_id"), text("user-1")),
(text("files"), CborValue::Map(vec![
(text("0_step_1.jpeg"), CborValue::Bytes(jpeg.clone())),
(text("1_step_1.jpeg"), CborValue::Bytes(jpeg.clone())),
])),
]));
let event = MidjourneyWsEvent::from_cbor_frame(&frame).unwrap();
let MidjourneyWsEvent::Progress(progress) = event else {
panic!("expected Progress, got {event:?}");
};
assert_eq!(progress.current_status, "running");
assert_eq!(progress.percentage_complete, 5.0);
assert_eq!(progress.images.len(), 2);
assert_eq!(progress.images[0].image_index, 0);
assert_eq!(progress.images[1].image_index, 1);
}
#[test]
fn non_map_frame_errors() {
let frame = encode(&text("nope"));
assert!(MidjourneyWsEvent::from_cbor_frame(&frame).is_err());
}
}
@@ -0,0 +1,15 @@
//! Midjourney websocket client.
//!
//! Midjourney streams job progress (and in-progress preview images) over a
//! websocket at `wss://ws.midjourney.com/ws`. Client-to-server frames are JSON
//! text; server-to-client frames are CBOR binary.
//!
//! Usage: open the socket with [`open_midjourney_websocket`], submit a job over
//! HTTP (see the `submit_job` endpoint), then read previews with
//! [`MidjourneyWebSocket::stream_job`] or the raw [`MidjourneyWebSocket::events`]
//! receiver.
pub mod job_progress;
pub mod midjourney_websocket;
pub mod midjourney_ws_event;
pub mod open_midjourney_websocket;
@@ -0,0 +1,161 @@
use crate::client::midjourney_hostname::MidjourneyHostname;
use crate::client::websocket::midjourney_websocket::MidjourneyWebSocket;
use crate::client::websocket::midjourney_ws_event::MidjourneyWsEvent;
use crate::credentials::midjourney_user_id::MidjourneyUserId;
use crate::error::midjourney_client_error::MidjourneyClientError;
use crate::error::midjourney_error::MidjourneyError;
use std::time::Duration;
use tokio::sync::broadcast;
use tokio::time::timeout;
use wreq::Client;
use wreq_util::Emulation;
/// Midjourney's websocket gateway. The host is fixed regardless of which
/// `www`/custom hostname the HTTP API is reached through.
const WEBSOCKET_URL_BASE: &str = "wss://ws.midjourney.com/ws";
/// Protocol version pinned by the web client's `?v=` query parameter.
const WEBSOCKET_PROTOCOL_VERSION: &str = "5";
/// How long to wait for the `user_success` reply before giving up.
const HANDSHAKE_TIMEOUT: Duration = Duration::from_secs(15);
pub struct OpenMidjourneyWebSocketRequest<'a> {
/// The short-lived websocket token from the index page's `initialProps`
/// (see `get_user_info`, which reads `websocketToken`).
pub websocket_token: &'a str,
/// The Midjourney user id this connection is for.
pub user_id: MidjourneyUserId,
/// Used only for the `Origin` header; the socket host is always
/// `ws.midjourney.com`.
pub hostname: MidjourneyHostname,
}
/// Open a Midjourney websocket, complete the `subscribe_to_user` handshake,
/// and return a live [`MidjourneyWebSocket`] handle.
///
/// The returned handle is already bound to the user and ready for
/// [`MidjourneyWebSocket::subscribe_to_job`] / [`MidjourneyWebSocket::stream_job`].
/// No cookies are needed — the websocket authenticates via `websocket_token`.
pub async fn open_midjourney_websocket(
req: OpenMidjourneyWebSocketRequest<'_>,
) -> Result<MidjourneyWebSocket, MidjourneyError> {
let client = Client::builder()
.emulation(Emulation::Firefox139)
.build()
.map_err(MidjourneyClientError::WreqError)?;
let origin = format!("https://{}", req.hostname.as_str());
let url = format!(
"{}?token={}&v={}",
WEBSOCKET_URL_BASE,
req.websocket_token,
WEBSOCKET_PROTOCOL_VERSION,
);
let response = client
.websocket(url)
.header("Origin", origin)
.send()
.await
.map_err(|err| MidjourneyClientError::WebSocketUpgrade(err.to_string()))?;
let websocket = response
.into_websocket()
.await
.map_err(|err| MidjourneyClientError::WebSocketUpgrade(err.to_string()))?;
let handle = MidjourneyWebSocket::spawn(req.user_id, websocket);
// Subscribe to the event stream BEFORE sending, so we cannot miss the reply.
let mut events = handle.events();
handle.subscribe_to_user()?;
match timeout(HANDSHAKE_TIMEOUT, await_user_success(&mut events)).await {
Ok(Ok(())) => Ok(handle),
Ok(Err(err)) => Err(err.into()),
Err(_) => Err(MidjourneyClientError::WebSocketHandshakeTimeout.into()),
}
}
async fn await_user_success(
events: &mut broadcast::Receiver<std::sync::Arc<MidjourneyWsEvent>>,
) -> Result<(), MidjourneyClientError> {
loop {
match events.recv().await {
Ok(event) => {
if matches!(event.as_ref(), MidjourneyWsEvent::UserSuccess { .. }) {
return Ok(());
}
}
Err(broadcast::error::RecvError::Lagged(_)) => continue,
Err(broadcast::error::RecvError::Closed) => {
return Err(MidjourneyClientError::WebSocketClosed);
}
}
}
}
#[cfg(test)]
mod tests {
use crate::client::midjourney_hostname::MidjourneyHostname;
use crate::client::websocket::midjourney_ws_event::MidjourneyWsEvent;
use crate::client::websocket::open_midjourney_websocket::{
open_midjourney_websocket, OpenMidjourneyWebSocketRequest,
};
use crate::endpoints::submit_job::{submit_job, SubmitJobRequest};
use crate::recipes::channel_id::ChannelId;
use crate::recipes::get_user_info::{get_user_info, GetUserInfoRequest};
use errors::AnyhowResult;
use filesys::read_to_trimmed_string::read_to_trimmed_string;
// Live end-to-end test. Requires a valid cookie header on disk. Run with:
// cargo test -p midjourney_client --features (none) -- --ignored --exact \
// client::websocket::open_midjourney_websocket::tests::live_stream_job
#[ignore]
#[tokio::test]
async fn live_stream_job() -> AnyhowResult<()> {
let cookie_header = read_to_trimmed_string("/Users/bt/secrets/midjourney/cookie.txt")?;
// 1. Read user id + websocket token from the index page.
let user_info = get_user_info(GetUserInfoRequest {
hostname: MidjourneyHostname::Standard,
cookie_header: cookie_header.clone(),
}).await?;
let user_id = user_info.user_id.expect("user id");
let websocket_token = user_info.websocket_token.expect("websocket token");
// 2. Open the websocket (does the subscribe_to_user handshake).
let ws = open_midjourney_websocket(OpenMidjourneyWebSocketRequest {
websocket_token: &websocket_token,
user_id: user_id.clone(),
hostname: MidjourneyHostname::Standard,
}).await?;
// 3. Submit a job over HTTP.
let channel_id = ChannelId::UserId(user_id.clone()).to_string();
let submit = submit_job(SubmitJobRequest {
prompt: "pirate ship in the city --v 8.2",
channel_id: &channel_id,
hostname: MidjourneyHostname::Standard,
cookie_header,
}).await?;
let job_id = submit.maybe_job_id.expect("job id");
// 4. Stream previews until completion.
let mut preview_frames = 0;
ws.stream_job(&job_id, |event| {
if let MidjourneyWsEvent::Progress(progress) = event {
if !progress.images.is_empty() {
preview_frames += 1;
}
}
}).await?;
assert!(preview_frames > 0, "expected at least one preview frame");
Ok(())
}
}
@@ -1,5 +1,7 @@
pub mod get_index_page_html;
pub mod imagine;
pub mod prompt_session_log;
pub mod refresh_token;
pub mod storage_list;
pub mod submit_job;
pub mod user_connections;
pub mod user_connections;
@@ -0,0 +1,145 @@
use crate::client::midjourney_hostname::MidjourneyHostname;
use crate::error::midjourney_api_error::MidjourneyApiError;
use crate::error::midjourney_client_error::MidjourneyClientError;
use crate::error::midjourney_error::MidjourneyError;
use cloudflare_errors::filter_cloudflare_errors::filter_cloudflare_errors;
use log::error;
use serde::{Deserialize, Serialize};
use wreq::Client;
use wreq_util::Emulation;
/// Logs a prompt to `/api/prompt-session-log`.
///
/// The web client fires this alongside each imagine submission (see the
/// `08`/`11` captures). It is telemetry, not the job-enqueue call — that is
/// `submit_job`. We mirror it so our traffic matches the browser's.
pub struct PromptSessionLogRequest<'a> {
pub hostname: MidjourneyHostname,
pub cookie_header: String,
/// A client-generated session id (UUID) grouping prompts in one sitting.
pub session_id: &'a str,
/// Monotonic index of this prompt within the session, starting at 0.
pub sequence_index: u32,
/// Epoch milliseconds when the prompt was captured.
pub captured_at_ms: u64,
/// The prompt text WITHOUT the trailing `--` parameters.
pub raw_text: &'a str,
/// The model version string, e.g. `"8.2"`.
pub version: &'a str,
}
#[derive(Debug, Clone)]
pub struct PromptSessionLogResponse {
/// The `status` field from the response body (e.g. `"success"`).
pub status: Option<String>,
}
pub async fn prompt_session_log(
req: PromptSessionLogRequest<'_>,
) -> Result<PromptSessionLogResponse, MidjourneyError> {
let cookie_header = req.cookie_header.trim();
if cookie_header.len() < 20 {
error!("Cookie header is too short (len: {}): {}", cookie_header.len(), cookie_header);
return Err(MidjourneyClientError::CookieTooShort.into());
}
let client = Client::builder()
.emulation(Emulation::Firefox139)
.build()
.map_err(MidjourneyClientError::WreqError)?;
let referer = format!("https://{}/imagine", req.hostname.as_str());
let url = format!("https://{}/api/prompt-session-log", req.hostname.as_str());
#[derive(Serialize)]
struct RawRequest<'a> {
session_id: &'a str,
sequence_index: u32,
captured_at_ms: u64,
source: &'a str,
raw_text: &'a str,
route: &'a str,
in_conversation_mode: bool,
version: &'a str,
video_mode: bool,
image_prompt_count: u32,
style_ref_count: u32,
character_ref_count: u32,
depth_ref_count: u32,
starting_frame_count: u32,
ending_frame_count: u32,
openai_item_id: Option<String>,
}
let body = RawRequest {
session_id: req.session_id,
sequence_index: req.sequence_index,
captured_at_ms: req.captured_at_ms,
source: "imagine_text",
raw_text: req.raw_text,
route: "/imagine",
in_conversation_mode: false,
version: req.version,
video_mode: false,
image_prompt_count: 0,
style_ref_count: 0,
character_ref_count: 0,
depth_ref_count: 0,
starting_frame_count: 0,
ending_frame_count: 0,
openai_item_id: None,
};
let http_request = client.post(url)
.header("cookie", cookie_header)
.header("Referer", &referer)
.header("Referrer-Policy", "origin-when-cross-origin")
.header("accept", "*/*")
.header("accept-language", "en-US,en;q=0.8")
.header("content-type", "application/json")
.header("priority", "u=1, i")
.header("sec-ch-ua-mobile", "?0")
.header("sec-fetch-dest", "empty")
.header("sec-fetch-mode", "cors")
.header("sec-fetch-site", "same-origin")
.header("x-csrf-protection", "1")
.json(&body)
.build()
.map_err(MidjourneyClientError::WreqError)?;
let response = client.execute(http_request)
.await
.map_err(|e| MidjourneyApiError::NetworkError(e.to_string()))?;
let status = response.status();
let response_body = response.text().await
.map_err(|e| MidjourneyApiError::NetworkError(e.to_string()))?;
if !status.is_success() {
if let Err(err) = filter_cloudflare_errors(status.as_u16(), &response_body) {
return Err(MidjourneyApiError::CloudflareError(err).into());
}
return Err(MidjourneyApiError::UnknownHttpFailure {
status_code: status.as_u16(),
body: response_body,
}.into());
}
// {"status":"success"}
#[derive(Deserialize)]
struct RawResponse {
status: Option<String>,
}
let response = serde_json::from_str::<RawResponse>(&response_body)
.map_err(MidjourneyApiError::DeserializationError)?;
Ok(PromptSessionLogResponse {
status: response.status,
})
}
@@ -0,0 +1,113 @@
use crate::error::midjourney_api_error::MidjourneyApiError;
use crate::error::midjourney_client_error::MidjourneyClientError;
use crate::error::midjourney_error::MidjourneyError;
use serde::Deserialize;
use wreq::Client;
use wreq_util::Emulation;
/// Google Identity Toolkit endpoint that Midjourney's Firebase auth uses to
/// exchange a refresh token for a fresh ID token.
const SECURE_TOKEN_URL: &str = "https://securetoken.googleapis.com/v1/token";
/// The public Firebase Web API key embedded in the Midjourney web app. This is
/// not a secret (it ships in the client bundle); it identifies the Firebase
/// project, and access is still gated by the refresh token.
pub const DEFAULT_FIREBASE_API_KEY: &str = "AIzaSyAjizp68NsH3JGUS0EyLXsChW4fN0A92tM";
/// Exchanges a refresh token for a new ID/access token.
///
/// The refresh token is the value of the `__Host-Midjourney.AuthUserTokenV3_r`
/// cookie. The returned `id_token` is the new value for the
/// `__Host-Midjourney.AuthUserTokenV3_i` cookie.
pub struct RefreshTokenRequest<'a> {
pub refresh_token: &'a str,
/// Firebase Web API key. Pass `DEFAULT_FIREBASE_API_KEY` unless overriding.
pub api_key: &'a str,
}
#[derive(Debug, Clone)]
pub struct RefreshTokenResponse {
/// The new access token (same value as `id_token`).
pub access_token: String,
/// The new Firebase ID token — the fresh `AuthUserTokenV3_i` cookie value.
pub id_token: String,
/// The refresh token to use next time (may be rotated).
pub refresh_token: String,
/// Seconds until `access_token` expires (as returned, a stringified number).
pub expires_in: Option<String>,
pub token_type: Option<String>,
pub user_id: Option<String>,
pub project_id: Option<String>,
}
pub async fn refresh_token(
req: RefreshTokenRequest<'_>,
) -> Result<RefreshTokenResponse, MidjourneyError> {
let client = Client::builder()
.emulation(Emulation::Firefox139)
.build()
.map_err(MidjourneyClientError::WreqError)?;
let url = format!("{}?key={}", SECURE_TOKEN_URL, req.api_key);
let form = [
("grant_type", "refresh_token"),
("refresh_token", req.refresh_token),
];
let http_request = client.post(url)
.header("Origin", "https://www.midjourney.com")
.header("Referer", "https://www.midjourney.com/")
.header("accept", "*/*")
.header("accept-language", "en-US,en;q=0.8")
.header("content-type", "application/x-www-form-urlencoded")
.form(&form)
.build()
.map_err(MidjourneyClientError::WreqError)?;
let response = client.execute(http_request)
.await
.map_err(|e| MidjourneyApiError::NetworkError(e.to_string()))?;
let status = response.status();
let response_body = response.text().await
.map_err(|e| MidjourneyApiError::NetworkError(e.to_string()))?;
if !status.is_success() {
return Err(match status.as_u16() {
400 => MidjourneyApiError::InvalidRequest(response_body),
401 => MidjourneyApiError::Unauthorized(response_body),
403 => MidjourneyApiError::Forbidden(response_body),
code => MidjourneyApiError::UnknownHttpFailure { status_code: code, body: response_body },
}.into());
}
#[derive(Deserialize)]
struct RawResponse {
access_token: String,
id_token: String,
refresh_token: String,
expires_in: Option<String>,
token_type: Option<String>,
user_id: Option<String>,
project_id: Option<String>,
}
let response = serde_json::from_str::<RawResponse>(&response_body)
.map_err(MidjourneyApiError::DeserializationError)?;
Ok(RefreshTokenResponse {
access_token: response.access_token,
id_token: response.id_token,
refresh_token: response.refresh_token,
expires_in: response.expires_in,
token_type: response.token_type,
user_id: response.user_id,
project_id: response.project_id,
})
}
@@ -72,11 +72,13 @@ pub async fn submit_job(req: SubmitJobRequest<'_>) -> Result<SubmitJobResponse,
#[derive(Serialize)]
#[allow(non_snake_case)]
struct Metadata {
// NB: Field order and null-vs-empty match the browser request exactly.
isMobile: Option<bool>,
imagePrompts: u8,
imageReferences: u8,
characterReferences: u8,
depthReferences: u8,
lightboxOpen: String,
lightboxOpen: Option<bool>,
}
#[derive(Serialize)]
@@ -96,11 +98,12 @@ pub async fn submit_job(req: SubmitJobRequest<'_>) -> Result<SubmitJobResponse,
},
channelId: req.channel_id.to_string(),
metadata: Metadata {
isMobile: None,
imagePrompts: 0,
imageReferences: 0,
characterReferences: 0,
depthReferences: 0,
lightboxOpen: "".to_string(),
lightboxOpen: None,
},
t: "imagine".to_string(),
prompt: req.prompt.to_string(),
@@ -27,6 +27,16 @@ pub enum MidjourneyClientError {
/// A serialization error with the request.
SerializationError(serde_json::Error),
/// The websocket upgrade handshake failed.
WebSocketUpgrade(String),
/// Tried to send on a websocket whose background task has stopped.
WebSocketClosed,
/// The websocket opened but the `subscribe_to_user` handshake did not
/// complete within the allotted time.
WebSocketHandshakeTimeout,
}
impl Error for MidjourneyClientError {}
@@ -42,6 +52,9 @@ impl Display for MidjourneyClientError {
//Self::ReqwestError(err) => write!(f, "Reqwest client error: {}", err),
Self::WreqError(err) => write!(f, "Wreq client error: {}", err),
Self::SerializationError(err) => write!(f, "Request serialization error: {}", err),
Self::WebSocketUpgrade(msg) => write!(f, "WebSocket upgrade failed: {}", msg),
Self::WebSocketClosed => write!(f, "The websocket connection is closed."),
Self::WebSocketHandshakeTimeout => write!(f, "Timed out waiting for the websocket user handshake."),
}
}
}