podping-api 0.1.0

A library for the Podping API.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
pub mod api;
pub mod request;

use serde::{Deserialize, Serialize};

const QUERY: &str = "podping";
pub(crate) const HIVE_API: &str = "https://api.hive.blog";

#[derive(Debug)]
pub(crate) struct HiveClient {
    pub client: reqwest::Client,
    block: Option<u64>,
}

impl HiveClient {
    pub(crate) fn new(block: Option<u64>) -> Self {
        let client = reqwest::Client::new();
        Self { client, block }
    }

    pub(crate) async fn init(&mut self) {
        match &self.block {
            Some(_) => {}
            None => {
                let block = self.get_head_block_number();
                self.block = Some(block.await);
            }
        }
    }

    pub(crate) async fn next_block(&mut self) {
        if let Some(block) = self.block_mut() {
            *block += 1
        }
    }

    /// Get the current head block number from hive
    pub(crate) async fn get_head_block_number(&self) -> u64 {
        self.get_dynamic_global_properties()
            .await
            .get_head_block_number()
            .unwrap()
    }

    /// Get the complete dynamic global properties from hive
    pub(crate) async fn get_dynamic_global_properties(&self) -> HiveResponse {
        self.client
            .post(HIVE_API)
            .json(&HiveMessage::get_dynamic_global_properties())
            .send()
            .await
            .unwrap()
            .json::<HiveResponse>()
            .await
            .unwrap()
    }

    pub(crate) fn block(&self) -> Option<u64> {
        self.block
    }

    pub(crate) fn block_mut(&mut self) -> &mut Option<u64> {
        &mut self.block
    }

    pub(crate) fn set_block(&mut self, block: Option<u64>) {
        self.block = block;
    }

    /// Extract Url's from the Operations
    pub(crate) fn get_payloads(&self, operations: Vec<Operations>) -> Vec<String> {
        // Extract the updated uri's
        let mut payloads = vec![];
        for tr in operations {
            let json_payload = serde_json::from_str::<OpPayload>(&tr.json.unwrap()).unwrap();
            payloads = json_payload.iris;
            // println!("block: {:?}, reason: {:?}", self.block, json_payload.reason);
            if json_payload.reason == "live" {
                let item = format!("live: {:?}", self.block);
                std::process::Command::new("notify-send")
                    .arg(item)
                    .output()
                    .expect("failed to execute process");
            }
        }

        if !payloads.is_empty() {
            println!("block: {:?}, payloads: {:?}", self.block, payloads);
        }
        payloads
    }
    /// Get operations for the current block
    /// We filter for notifications with the name `podping`
    pub(crate) async fn get_operations(&self) -> Vec<Operations> {
        let transactions = self.get_transactions().await;

        let mut operations = vec![];
        for transaction in transactions {
            for operation in transaction.operations {
                for op in operation {
                    match op {
                        HiveOperation::Operations(operation) => {
                            if let Some(name) = &operation.id {
                                // We only care about podping messages.
                                if name == QUERY {
                                    operations.push(operation);
                                }
                            }
                        }
                        // We don't care about any of these messages.
                        HiveOperation::String(_)
                        | HiveOperation::Vote(_)
                        | HiveOperation::Transfer(_)
                        | HiveOperation::Transactions(_)
                        | HiveOperation::Comment(_) => {}
                    }
                }
            }
        }
        operations
    }
    pub(crate) async fn get_block(&self) -> HiveResponse {
        let block_response = HiveMessage::get_block(self.block.unwrap());
        let resp = self
            .client
            .post(HIVE_API)
            .json(&block_response)
            .send()
            .await
            .unwrap()
            .text()
            .await
            .unwrap();
        // reqwest can't properly serialize the type into json,
        // but serde_json can.
        serde_json::from_str::<HiveResponse>(&resp).unwrap()
    }

    pub(crate) async fn get_transactions(&self) -> Vec<Transactions> {
        let hive_response = &self.get_block().await;
        if let Some(HiveResponseResult::Block(block)) = &hive_response.result {
            block.transactions.clone()
        } else {
            vec![]
        }
    }
}
#[derive(Debug)]
pub(crate) struct HiveClientBlocking {
    pub client: reqwest::blocking::Client,
    block: Option<u64>,
}

impl HiveClientBlocking {
    pub(crate) fn new(block: Option<u64>) -> Self {
        let client = reqwest::blocking::Client::new();
        Self { client, block }
    }
    pub(crate) fn init(&mut self) {
        match &self.block {
            Some(_) => {}
            None => {
                let block = self.get_head_block_number();
                self.block = Some(block);
            }
        }
    }

    pub(crate) fn get_head_block_number(&self) -> u64 {
        let resp = self
            .client
            .post(HIVE_API)
            .json(&HiveMessage::get_dynamic_global_properties())
            .send()
            .unwrap()
            .json::<HiveResponse>()
            .unwrap();
        resp.get_head_block_number().unwrap()
    }

    /// Get operations for the current block
    /// We filter for notifications with the name `podping`
    pub(crate) fn get_operations(&self) -> Vec<Operations> {
        let transactions = self.get_transactions();

        let mut operations = vec![];
        for transaction in transactions {
            for operation in transaction.operations {
                for op in operation {
                    match op {
                        HiveOperation::Operations(operation) => {
                            if let Some(name) = &operation.id {
                                // We only care about podping messages.
                                if name == QUERY {
                                    operations.push(operation);
                                }
                            }
                        }
                        // We don't care about any of these messages.
                        HiveOperation::String(_)
                        | HiveOperation::Vote(_)
                        | HiveOperation::Transfer(_)
                        | HiveOperation::Transactions(_)
                        | HiveOperation::Comment(_) => {}
                    }
                }
            }
        }
        operations
    }

    pub(crate) fn get_transactions(&self) -> Vec<Transactions> {
        let block_response = HiveMessage::get_block(self.block.unwrap());
        let resp = self
            .client
            .post(HIVE_API)
            .json(&block_response)
            .send()
            .unwrap()
            .text()
            .unwrap();
        // reqwest can't properly serialize the type into json,
        // but serde_json can.
        let hive_response = serde_json::from_str::<HiveResponse>(&resp).unwrap();

        if let Some(HiveResponseResult::Block(block)) = hive_response.result {
            block.transactions
        } else {
            vec![]
        }
    }

    /// Extract Url's from the Operations
    pub(crate) fn get_payloads(&self, operations: Vec<Operations>) -> Vec<String> {
        // Extract the updated uri's
        let mut payloads = vec![];
        for tr in operations {
            let mut json_payload = serde_json::from_str::<OpPayload>(&tr.json.unwrap()).unwrap();
            payloads.append(&mut json_payload.iris);
        }
        payloads
    }

    pub(crate) fn block(&self) -> Option<u64> {
        self.block
    }

    pub(crate) fn block_mut(&mut self) -> &mut Option<u64> {
        &mut self.block
    }

    pub(crate) fn set_block(&mut self, block: Option<u64>) {
        self.block = block;
    }

    pub(crate) fn next_block(&mut self) {
        if let Some(block) = self.block_mut() {
            *block += 1
        }
    }
}

#[derive(Debug, Serialize, Deserialize)]
pub(crate) struct HiveRequest {
    jsonrpc: String,
    method: String,
    id: u8,
}

#[derive(Debug, Serialize, Deserialize)]
pub(crate) struct HiveRequestParams {
    jsonrpc: String,
    method: String,
    params: Vec<ParamMember>,
    id: u8,
}

#[derive(Debug, Serialize, Deserialize)]
#[serde(untagged)]
pub(crate) enum HiveMessage {
    Request(HiveRequest),
    RequestParams(HiveRequestParams),
    Response(HiveResponse),
}

#[derive(Debug, Serialize, Deserialize)]
#[serde(untagged)]
pub(crate) enum ParamMember {
    String(String),
    Int(u16),
    Int128(u128),
    Int64(u64),
    None,
}

impl HiveMessage {
    pub(crate) fn get_followers() -> Self {
        Self::RequestParams(HiveRequestParams {
            jsonrpc: "2.0".into(),
            method: "condenser_api.get_followers".into(),
            params: vec![
                ParamMember::String(QUERY.into()),
                ParamMember::None,
                ParamMember::String("blog".into()),
                ParamMember::Int(100),
            ],
            id: 1,
        })
    }
    pub(crate) fn get_methods() -> Self {
        Self::Request(HiveRequest {
            jsonrpc: "2.0".into(),
            method: "jsonrpc.get_methods".into(),
            id: 1,
        })
    }
    pub(crate) fn get_dynamic_global_properties() -> Self {
        Self::Request(HiveRequest {
            jsonrpc: "2.0".into(),
            method: "database_api.get_dynamic_global_properties".into(),
            id: 1,
        })
    }
    pub(crate) fn get_block(block: u64) -> Self {
        Self::RequestParams(HiveRequestParams {
            jsonrpc: "2.0".into(),
            method: "condenser_api.get_block".into(),
            params: vec![ParamMember::Int64(block)],
            id: 1,
        })
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HiveResponse {
    pub jsonrpc: String,
    pub id: u16,
    // Returns null (None), if the block is too advanced
    pub result: Option<HiveResponseResult>,
}

impl HiveResponse {
    pub(crate) fn get_head_block_number(&self) -> Option<u64> {
        if let Some(response) = &self.result {
            response.get_head_block_number()
        } else {
            None
        }
    }
}

impl HiveResponseResult {
    pub(crate) fn get_head_block_number(&self) -> Option<u64> {
        match self {
            HiveResponseResult::DynamicGlobalProperties(properties) => {
                Some(properties.head_block_number)
            }
            _ => None,
        }
    }
}

#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(untagged)]
pub enum HiveResponseResult {
    DynamicGlobalProperties(HiveDynamicGlobalProperties),
    Block(Block),
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct HiveDynamicGlobalProperties {
    id: u16,
    head_block_number: u64,
    // head_block_id: String,
    // time: String,
    // current_witness: string,
    // total_pow: u128,
    // num_pow_witnesses: u128,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Block {
    // id: u16,
    // previous: String,
    // timestamp: String,
    pub transactions: Vec<Transactions>,
    // pub transactions: HashMap<String, String>,
    // operations:
    // head_block_id: String,
    // time: String,
    // current_witness: string,
    // total_pow: u128,
    // num_pow_witnesses: u128,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
/// All transactions
pub struct Transactions {
    // ref_block_num: u64,
    // ref_block_prefix: u64,
    // pub(crate) expiration: String,
    pub(crate) operations: Vec<Vec<HiveOperation>>,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(untagged)]
pub enum HiveOperation {
    Operations(Operations),
    String(String),
    Vote(Vote),
    Transfer(Transfer),
    Transactions(Transactions),
    Comment(Comment),
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Operations {
    required_auths: Vec<String>,
    required_posting_auths: Vec<String>,
    pub id: Option<String>,
    pub json: Option<String>,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct OpPayload {
    version: String,
    num_urls: Option<u8>,
    pub medium: String,
    pub reason: String,
    // used to be named urls
    pub iris: Vec<String>,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Vote {
    voter: Option<String>,
    author: Option<String>,
    permlink: Option<String>,
    // weight: String,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Transfer {
    from: Option<String>,
    to: Option<String>,
    amount: Option<String>,
    memo: Option<String>,
    // weight: String,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Comment {
    parent_author: Option<String>,
    parent_permlink: Option<String>,
    author: Option<String>,
    title: Option<String>,
    // weight: String,
}