fastdotcom 0.0.4__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
fastdotcom/__init__.py ADDED
@@ -0,0 +1,742 @@
1
+ import os
2
+ import json
3
+ import urllib.request
4
+ import urllib.parse
5
+ import urllib.error
6
+ import time
7
+ from threading import Thread, Event
8
+ import socket
9
+ from urllib.parse import urlparse
10
+
11
+ import asyncio
12
+ from icmplib import async_ping, SocketPermissionError
13
+ import requests
14
+
15
+ # Global event to mark when the download has started (i.e. first payload received)
16
+ download_started = Event()
17
+
18
+
19
+ # ------------------------------
20
+ # Helper Classes and Functions
21
+ # ------------------------------
22
+
23
+ class ProgressReader:
24
+ """
25
+ A file-like object that wraps a bytes payload and tracks its read progress.
26
+ """
27
+ def __init__(self, data, chunk_size=64 * 1024):
28
+ self.data = data
29
+ self.chunk_size = chunk_size
30
+ self.offset = 0
31
+ self.total = len(data)
32
+ self.read_bytes = 0
33
+
34
+ def read(self, amt=None):
35
+ if amt is None:
36
+ amt = self.chunk_size
37
+ if self.offset >= self.total:
38
+ return b""
39
+ chunk = self.data[self.offset : self.offset + amt]
40
+ self.offset += amt
41
+ self.read_bytes += len(chunk)
42
+ return chunk
43
+
44
+
45
+ def get_html_result(url, result, index):
46
+ """
47
+ Download helper: Reads data from the URL in fixed-size chunks and updates result[index].
48
+ """
49
+ try:
50
+ req = urllib.request.urlopen(url)
51
+ except urllib.error.URLError:
52
+ result[index] = 0
53
+ return
54
+
55
+ chunk_size = 100 * 1024
56
+ i = 1
57
+ while True:
58
+ chunk = req.read(chunk_size)
59
+ if not chunk:
60
+ break
61
+ result[index] = i * chunk_size
62
+ i += 1
63
+
64
+
65
+ def application_bytes_to_network_bits(num_bytes):
66
+ return num_bytes * 8 * 1.0415
67
+
68
+
69
+ def find_ipv4(fqdn):
70
+ ipv4 = socket.getaddrinfo(fqdn, 80, socket.AF_INET)[0][4][0]
71
+ return ipv4
72
+
73
+
74
+ def find_ipv6(fqdn):
75
+ ipv6 = socket.getaddrinfo(fqdn, 80, socket.AF_INET6)[0][4][0]
76
+ return ipv6
77
+
78
+
79
+ def get_fast_token(verbose=False):
80
+ """
81
+ Fetch the fast.com homepage, parse the JavaScript URL, and extract the token.
82
+ Returns the token string or None if there was an error.
83
+ """
84
+ url = "https://fast.com/"
85
+ try:
86
+ url_result = urllib.request.urlopen(url)
87
+ except Exception as e:
88
+ if verbose:
89
+ print("Error connecting to fast.com:", e)
90
+ return None
91
+
92
+ response = url_result.read().decode().strip()
93
+ js_name = None
94
+ for line in response.split("\n"):
95
+ if "script src" in line:
96
+ js_name = line.split('"')[1]
97
+ break
98
+ if not js_name:
99
+ if verbose:
100
+ print("Could not find the JavaScript filename.")
101
+ return None
102
+
103
+ token_url = "https://fast.com" + js_name
104
+ if verbose:
105
+ print("JavaScript URL is", token_url)
106
+ try:
107
+ url_result = urllib.request.urlopen(token_url)
108
+ except Exception as e:
109
+ if verbose:
110
+ print("Error fetching JavaScript file:", e)
111
+ return None
112
+
113
+ js_content = url_result.read().decode().strip()
114
+ token = None
115
+ for part in js_content.split(","):
116
+ if "token:" in part:
117
+ if verbose:
118
+ print("Found JS part:", part)
119
+ token = part.split('"')[1]
120
+ if verbose:
121
+ print("Token is", token)
122
+ break
123
+ if not token and verbose:
124
+ print("Token not found in JavaScript file.")
125
+ return token
126
+
127
+
128
+ # -----------------------------
129
+ # Download Test Functions
130
+ # -----------------------------
131
+
132
+ def download_test(
133
+ token,
134
+ verbose=False,
135
+ min_time=5,
136
+ max_time=15,
137
+ force_ipv4=False,
138
+ force_ipv6=False,
139
+ window_size=3,
140
+ connections_min=1,
141
+ connections_max=8,
142
+ ):
143
+ """
144
+ Multi-threaded download test that dynamically manages parallel connections.
145
+
146
+ Returns:
147
+ int: Highest moving-average download speed in Mbps (rounded to 0 decimals).
148
+ """
149
+ if not token:
150
+ if verbose:
151
+ print("No token provided. Aborting download.")
152
+ return 0
153
+
154
+ base_url = "https://api.fast.com/"
155
+ if force_ipv4:
156
+ ipv4 = find_ipv4("api.fast.com")
157
+ base_url = "http://" + ipv4 + "/"
158
+ elif force_ipv6:
159
+ ipv6 = find_ipv6("api.fast.com")
160
+ base_url = "http://[" + ipv6 + "]/"
161
+ api_url = base_url + "netflix/speedtest?https=true&token=" + token + "&urlCount=3"
162
+ if verbose:
163
+ print("API URL is", api_url)
164
+ try:
165
+ url_result = urllib.request.urlopen(api_url, None, 2)
166
+ except Exception as e:
167
+ if verbose:
168
+ print("Error connecting to API:", e)
169
+ return 0
170
+
171
+ json_result = url_result.read().decode().strip()
172
+ parsed_json = json.loads(json_result)
173
+ urls = [item["url"] for item in parsed_json]
174
+ if verbose:
175
+ print("Retrieved URLs:")
176
+ for url in urls:
177
+ print(url)
178
+
179
+ results = []
180
+ active_threads = []
181
+ next_url_index = 0
182
+
183
+ def spawn_thread():
184
+ nonlocal next_url_index
185
+ idx = len(results)
186
+ results.append(0)
187
+ url = urls[next_url_index]
188
+ next_url_index = (next_url_index + 1) % len(urls)
189
+ t = Thread(target=get_html_result, args=(url, results, idx))
190
+ t.daemon = True
191
+ t.start()
192
+ active_threads.append((t, idx))
193
+ if verbose:
194
+ print(f"Spawned thread {idx} using URL: {url}")
195
+
196
+ for _ in range(connections_min):
197
+ spawn_thread()
198
+
199
+ snapshots = []
200
+ last_total = 0
201
+ last_snapshot_time = time.perf_counter()
202
+ highest_speed_bps = 0
203
+
204
+ start_time = time.perf_counter()
205
+ end_time = start_time + max_time
206
+ current_time = start_time
207
+
208
+ while current_time < end_time or (current_time - start_time) < min_time:
209
+ time.sleep(0.5)
210
+ current_time = time.perf_counter()
211
+ active_threads = [(t, idx) for t, idx in active_threads if t.is_alive()]
212
+ while len(active_threads) < connections_min and current_time < end_time:
213
+ spawn_thread()
214
+ active_threads = [(t, idx) for t, idx in active_threads if t.is_alive()]
215
+ if current_time - last_snapshot_time >= 1:
216
+ elapsed_ms = (current_time - last_snapshot_time) * 1000
217
+ total = sum(results)
218
+ delta = total - last_total
219
+ if delta < 0:
220
+ delta = 0
221
+ if delta > 0 and not download_started.is_set():
222
+ download_started.set()
223
+ if elapsed_ms > 0:
224
+ snapshots.append({"bytes": delta, "time": elapsed_ms})
225
+ if len(snapshots) > window_size:
226
+ snapshots = snapshots[-window_size:]
227
+ total_bytes = sum(s["bytes"] for s in snapshots)
228
+ total_time = sum(s["time"] for s in snapshots)
229
+ avg_speed = (1000 * total_bytes * 8 / total_time) if total_time > 0 else 0
230
+ if avg_speed > highest_speed_bps:
231
+ highest_speed_bps = avg_speed
232
+ if verbose:
233
+ print(
234
+ f"Snapshot: {delta} bytes in {elapsed_ms:.0f} ms, "
235
+ f"avg speed: {avg_speed:.1f} bps"
236
+ )
237
+ last_total = total
238
+ last_snapshot_time = current_time
239
+
240
+ desired = connections_min
241
+ if avg_speed > 50e6:
242
+ desired = connections_max
243
+ elif avg_speed > 10e6:
244
+ desired = max(connections_min, min(5, connections_max))
245
+ elif avg_speed > 1e6:
246
+ desired = max(connections_min, 3)
247
+ if len(active_threads) < desired and current_time < end_time:
248
+ threads_to_spawn = desired - len(active_threads)
249
+ for _ in range(threads_to_spawn):
250
+ if len(active_threads) < connections_max:
251
+ spawn_thread()
252
+ active_threads = [
253
+ (t, idx) for t, idx in active_threads if t.is_alive()
254
+ ]
255
+ if current_time >= end_time and (current_time - start_time) >= min_time:
256
+ break
257
+ time.sleep(0.2)
258
+ mbps = highest_speed_bps / 1e6
259
+ if verbose:
260
+ print(f"Highest moving average download speed: {round(mbps)} Mbps")
261
+ return mbps
262
+
263
+
264
+ # -----------------------------
265
+ # Upload Test Functions
266
+ # -----------------------------
267
+
268
+ def upload_with_progress(url, progress_obj, start_time_container, result_container):
269
+ req = urllib.request.Request(url, data=progress_obj, method="POST")
270
+ req.add_header("Content-Length", str(progress_obj.total))
271
+ req.add_header("Content-Type", "application/octet-stream")
272
+ start = time.perf_counter()
273
+ start_time_container[0] = start
274
+ try:
275
+ urllib.request.urlopen(req)
276
+ except Exception as e:
277
+ result_container[0] = (0, time.perf_counter() - start)
278
+ return
279
+ end = time.perf_counter()
280
+ result_container[0] = (progress_obj.read_bytes, end - start)
281
+
282
+
283
+ def upload_test(
284
+ token,
285
+ verbose=False,
286
+ min_time=5,
287
+ max_time=15,
288
+ force_ipv4=False,
289
+ force_ipv6=False,
290
+ window_size=3,
291
+ connections_min=1,
292
+ connections_max=8,
293
+ payload_size=10 * 1024 * 1024,
294
+ max_payload_size=50 * 1024 * 1024,
295
+ adjust_threshold=1.0,
296
+ ):
297
+ """
298
+ Run an upload test that dynamically manages parallel connections and adjusts the payload size.
299
+
300
+ Returns:
301
+ int: Highest moving-average upload speed in Mbps (rounded to 0 decimals).
302
+ """
303
+ if not token:
304
+ if verbose:
305
+ print("No token provided. Aborting upload test.")
306
+ return 0
307
+
308
+ base_url = "https://api.fast.com/"
309
+ if force_ipv4:
310
+ ipv4 = find_ipv4("api.fast.com")
311
+ base_url = "http://" + ipv4 + "/"
312
+ elif force_ipv6:
313
+ ipv6 = find_ipv6("api.fast.com")
314
+ base_url = "http://[" + ipv6 + "]/"
315
+ api_url = base_url + "netflix/speedtest?https=true&token=" + token + "&urlCount=3"
316
+ if verbose:
317
+ print("API URL is", api_url)
318
+ try:
319
+ url_result = urllib.request.urlopen(api_url, None, 2)
320
+ except Exception as e:
321
+ if verbose:
322
+ print("Error connecting to API:", e)
323
+ return 0
324
+
325
+ json_result = url_result.read().decode().strip()
326
+ parsed_json = json.loads(json_result)
327
+ urls = [item["url"] for item in parsed_json]
328
+ if verbose:
329
+ print("Retrieved upload test URLs:")
330
+ for url in urls:
331
+ print(url)
332
+
333
+ readers = {}
334
+ start_times = {}
335
+ result_containers = {}
336
+ active_threads = {}
337
+ next_thread_index = 0
338
+ next_url_index = 0
339
+ request_size = payload_size
340
+
341
+ def spawn_upload_thread():
342
+ nonlocal next_thread_index, next_url_index, request_size
343
+ idx = next_thread_index
344
+ next_thread_index += 1
345
+ payload = os.urandom(request_size)
346
+ pr = ProgressReader(payload)
347
+ readers[idx] = pr
348
+ start_times[idx] = [None]
349
+ result_containers[idx] = [None]
350
+ url_to_use = urls[next_url_index]
351
+ next_url_index = (next_url_index + 1) % len(urls)
352
+ t = Thread(
353
+ target=upload_with_progress,
354
+ args=(url_to_use, pr, start_times[idx], result_containers[idx]),
355
+ )
356
+ t.daemon = True
357
+ t.start()
358
+ active_threads[idx] = t
359
+ if verbose:
360
+ print(
361
+ f"Spawned upload thread {idx} using URL: {url_to_use} "
362
+ f"with payload size: {request_size} bytes"
363
+ )
364
+
365
+ for _ in range(connections_min):
366
+ spawn_upload_thread()
367
+
368
+ snapshots = []
369
+ last_total = 0
370
+ last_snapshot_time = time.perf_counter()
371
+ highest_speed_bps = 0
372
+
373
+ overall_start_time = time.perf_counter()
374
+ end_time = overall_start_time + max_time
375
+ current_time = overall_start_time
376
+
377
+ while current_time < end_time or (current_time - overall_start_time) < min_time:
378
+ time.sleep(1)
379
+ current_time = time.perf_counter()
380
+ total = 0
381
+ finished_times = []
382
+ for idx in list(active_threads.keys()):
383
+ t = active_threads[idx]
384
+ if t.is_alive():
385
+ total += readers[idx].read_bytes
386
+ else:
387
+ if result_containers[idx][0] is not None:
388
+ bytes_uploaded, elapsed = result_containers[idx][0]
389
+ total += bytes_uploaded
390
+ finished_times.append(elapsed)
391
+ active_threads.pop(idx)
392
+ elapsed_ms = (current_time - last_snapshot_time) * 1000
393
+ delta = total - last_total
394
+ if delta < 0:
395
+ delta = 0
396
+ if elapsed_ms > 0:
397
+ snapshots.append({"bytes": delta, "time": elapsed_ms})
398
+ if len(snapshots) > window_size:
399
+ snapshots = snapshots[-window_size:]
400
+ total_bytes = sum(s["bytes"] for s in snapshots)
401
+ total_time = sum(s["time"] for s in snapshots)
402
+ avg_speed = (1000 * total_bytes * 8 / total_time) if total_time > 0 else 0
403
+ if avg_speed > highest_speed_bps:
404
+ highest_speed_bps = avg_speed
405
+ if verbose:
406
+ print(
407
+ f"Snapshot: {delta} bytes in {elapsed_ms:.0f} ms, "
408
+ f"avg speed: {avg_speed:.1f} bps"
409
+ )
410
+ if finished_times:
411
+ min_elapsed = min(finished_times)
412
+ if min_elapsed < adjust_threshold:
413
+ new_size = int(request_size * (adjust_threshold / min_elapsed))
414
+ if new_size > request_size:
415
+ old_size = request_size
416
+ request_size = min(new_size, max_payload_size)
417
+ if verbose and request_size != old_size:
418
+ print(f"Adjusted payload size to: {request_size} bytes")
419
+ last_total = total
420
+ last_snapshot_time = current_time
421
+
422
+ if avg_speed > 50e6:
423
+ desired = connections_max
424
+ elif avg_speed > 10e6:
425
+ desired = max(connections_min, 5)
426
+ elif avg_speed > 1e6:
427
+ desired = max(connections_min, 3)
428
+ else:
429
+ desired = connections_min
430
+ if len(active_threads) < desired and current_time < end_time:
431
+ threads_to_spawn = desired - len(active_threads)
432
+ for _ in range(threads_to_spawn):
433
+ if len(active_threads) < connections_max:
434
+ spawn_upload_thread()
435
+ if current_time >= end_time and (current_time - overall_start_time) >= min_time:
436
+ break
437
+ time.sleep(0.2)
438
+ mbps = highest_speed_bps / 1e6
439
+ if verbose:
440
+ print(f"Highest moving average upload speed: {round(mbps)} Mbps")
441
+ return mbps
442
+
443
+
444
+ def upload_js_comparable_test(token, verbose=False, max_time=15, payload_chunk_size=64 * 1024):
445
+ """
446
+ An upload test that mimics JavaScript's behavior by using a persistent HTTP connection.
447
+ It streams random data (via a generator) for 'max_time' seconds using chunked transfer encoding.
448
+
449
+ Returns:
450
+ int: The upload speed in Mbps (rounded to 0 decimals).
451
+ """
452
+ if not token:
453
+ if verbose:
454
+ print("No token provided. Aborting JS-comparable upload test.")
455
+ return 0
456
+
457
+ base_url = "https://api.fast.com/"
458
+ api_url = base_url + "netflix/speedtest?https=true&token=" + token + "&urlCount=3"
459
+ try:
460
+ url_result = urllib.request.urlopen(api_url, None, 2)
461
+ except Exception as e:
462
+ if verbose:
463
+ print("Error connecting to API for upload:", e)
464
+ return 0
465
+
466
+ json_result = url_result.read().decode().strip()
467
+ parsed_json = json.loads(json_result)
468
+ urls = [item["url"] for item in parsed_json]
469
+ url_to_use = urls[0]
470
+ if verbose:
471
+ print("Using upload URL (JS-comparable):", url_to_use)
472
+
473
+ start = time.perf_counter()
474
+ total_bytes = 0
475
+
476
+ def data_generator():
477
+ nonlocal total_bytes
478
+ while time.perf_counter() - start < max_time:
479
+ chunk = os.urandom(payload_chunk_size)
480
+ total_bytes += len(chunk)
481
+ yield chunk
482
+
483
+ session = requests.Session()
484
+ headers = {
485
+ "Transfer-Encoding": "chunked",
486
+ "Content-Type": "application/octet-stream",
487
+ }
488
+ try:
489
+ session.post(url_to_use, data=data_generator(), headers=headers, timeout=max_time + 5)
490
+ except Exception as e:
491
+ if verbose:
492
+ print("JS-comparable upload error:", e)
493
+ return 0
494
+ elapsed = time.perf_counter() - start
495
+ speed_bps = (total_bytes * 8) / elapsed
496
+ mbps = speed_bps / 1e6
497
+ if verbose:
498
+ print(f"Uploaded {total_bytes} bytes in {round(elapsed)} s, speed: {round(mbps)} Mbps")
499
+ return mbps
500
+
501
+
502
+ def upload_js_comparable_dynamic_test(token, verbose=False, max_time=15, candidate_sizes=None):
503
+ """
504
+ Runs a JS-comparable upload test that cycles through different payload chunk sizes
505
+ repeatedly until the overall max_time is reached, then returns the highest measured upload speed.
506
+
507
+ Parameters:
508
+ candidate_sizes: list of payload chunk sizes in bytes.
509
+ Defaults to [64KB, 128KB, 256KB, 512KB].
510
+
511
+ Returns:
512
+ int: Highest upload speed in Mbps (rounded to 0 decimals).
513
+ """
514
+ if candidate_sizes is None:
515
+ candidate_sizes = [64 * 10240, 128 * 1024, 256 * 1024, 512 * 1024]
516
+
517
+ best_speed = 0
518
+ start_time = time.perf_counter()
519
+ # Cycle through candidate sizes until max_time is reached.
520
+ while time.perf_counter() - start_time < max_time:
521
+ for size in candidate_sizes:
522
+ remaining = max_time - (time.perf_counter() - start_time)
523
+ if remaining <= 0:
524
+ break
525
+ speed = upload_js_comparable_test(token, verbose=verbose, max_time=remaining, payload_chunk_size=size)
526
+ if verbose:
527
+ print(f"Payload size: {size} bytes -> Upload speed: {speed} Mbps")
528
+ if speed > best_speed:
529
+ best_speed = speed
530
+ if verbose:
531
+ print(f"Best upload speed measured: {best_speed} Mbps")
532
+ return best_speed
533
+
534
+
535
+ # -----------------------------
536
+ # Ping Test Functions Using icmplib
537
+ # -----------------------------
538
+
539
+ def ping_test(host, count=5, timeout=2, verbose=False):
540
+ """
541
+ Uses icmplib's async_ping to send ICMP echo requests to 'host' count times.
542
+ Returns the average latency (in ms) and a list of individual measurements.
543
+ (Values are already in ms.)
544
+ If an error occurs, returns 0 and an empty list.
545
+ """
546
+ try:
547
+ response = asyncio.run(async_ping(host, count=count, timeout=timeout, privileged=True))
548
+ except SocketPermissionError:
549
+ if verbose:
550
+ print("Insufficient privileges, falling back to unprivileged mode for ping")
551
+ try:
552
+ response = asyncio.run(
553
+ async_ping(host, count=count, timeout=timeout, privileged=False)
554
+ )
555
+ except Exception as e:
556
+ if verbose:
557
+ print("Ping error (unprivileged):", e)
558
+ return 0, []
559
+ except Exception as e:
560
+ if verbose:
561
+ print("Ping error:", e)
562
+ return 0, []
563
+ avg_ms = response.avg_rtt
564
+ times_ms = response.rtts
565
+ if verbose:
566
+ print(f"ICMP ping to {host}: avg {round(avg_ms)} ms, individual: {[round(r) for r in times_ms]}")
567
+ return avg_ms, times_ms
568
+
569
+
570
+ def fast_com_ping_unloaded(token=None, verbose=False, count=5):
571
+ """
572
+ Measures unloaded ping using icmplib by extracting the hostname from a test URL.
573
+
574
+ Returns:
575
+ (average latency in ms, list of measurements)
576
+ If token retrieval fails, returns 0 for the average ping.
577
+ """
578
+ if token is None:
579
+ token = get_fast_token(verbose=verbose)
580
+ if not token:
581
+ return 0, []
582
+ base_url = "https://api.fast.com/"
583
+ api_url = base_url + "netflix/speedtest?https=true&token=" + token + "&urlCount=3"
584
+ try:
585
+ url_result = urllib.request.urlopen(api_url, None, 2)
586
+ except Exception as e:
587
+ if verbose:
588
+ print("Error connecting to API for unloaded ping:", e)
589
+ return 0, []
590
+ json_result = url_result.read().decode().strip()
591
+ parsed_json = json.loads(json_result)
592
+ urls = [item["url"] for item in parsed_json]
593
+ host = urlparse(urls[0]).hostname
594
+ avg, times = ping_test(host, count=count, timeout=2, verbose=verbose)
595
+ return avg, times
596
+
597
+
598
+ def fast_com_download(token=None, verbose=False, max_time=15, ping_count=5, ping_interval=1):
599
+ """
600
+ Runs the multi-threaded download test and concurrently measures loaded ping using icmplib.
601
+ The ping worker starts after the first payload is received and runs until the download test completes.
602
+
603
+ Returns:
604
+ (download speed in Mbps, average loaded ping in ms, list of ping measurements)
605
+ If token retrieval fails, returns 0 for both download speed and ping.
606
+ """
607
+ if token is None:
608
+ token = get_fast_token(verbose=verbose)
609
+ if not token:
610
+ return 0, 0, []
611
+
612
+ base_url = "https://api.fast.com/"
613
+ api_url = base_url + "netflix/speedtest?https=true&token=" + token + "&urlCount=3"
614
+ try:
615
+ url_result = urllib.request.urlopen(api_url, None, 2)
616
+ except Exception as e:
617
+ if verbose:
618
+ print("Error connecting to API for download:", e)
619
+ return 0, 0, []
620
+ json_result = url_result.read().decode().strip()
621
+ parsed_json = json.loads(json_result)
622
+ urls = [item["url"] for item in parsed_json]
623
+ host = urlparse(urls[0]).hostname
624
+ if verbose:
625
+ print("Using host for loaded ping (ICMP):", host)
626
+
627
+ ping_values = []
628
+ stop_event = Event()
629
+
630
+ def ping_worker():
631
+ download_started.wait()
632
+ while not stop_event.is_set():
633
+ avg, _ = ping_test(host, count=ping_count, timeout=ping_interval, verbose=verbose)
634
+ if avg is not None:
635
+ ping_values.append(avg)
636
+ time.sleep(ping_interval)
637
+
638
+ ping_thread = Thread(target=ping_worker)
639
+ ping_thread.daemon = True
640
+ ping_thread.start()
641
+
642
+ dl_speed = download_test(
643
+ token,
644
+ verbose=verbose,
645
+ min_time=5,
646
+ max_time=max_time,
647
+ force_ipv4=False,
648
+ force_ipv6=False,
649
+ window_size=3,
650
+ connections_min=1,
651
+ connections_max=8,
652
+ )
653
+
654
+ stop_event.set()
655
+ ping_thread.join()
656
+ overall_ping = sum(ping_values) / len(ping_values) if ping_values else 0
657
+ return dl_speed, overall_ping, ping_values
658
+
659
+
660
+ # -----------------------------
661
+ # Convenience Functions
662
+ # -----------------------------
663
+
664
+ def fast_com_test():
665
+ result = {
666
+ "download_speed": 1.23,
667
+ "upload_speed": 4.56,
668
+ "unloaded_ping": 7.89,
669
+ "loaded_ping": 10.11,
670
+ }
671
+ return result
672
+
673
+ def fast_com(
674
+ verbose=False,
675
+ max_time=15,
676
+ ping_count=5,
677
+ force_ipv4=False,
678
+ force_ipv6=False,
679
+ payload_size=10 * 1024 * 1024,
680
+ max_payload_size=50 * 1024 * 1024,
681
+ ):
682
+ token = get_fast_token(verbose=verbose)
683
+ if not token:
684
+ return (
685
+ "Failed to get token. All test values will be 0.\n"
686
+ "Download Speed: 0.00 Mbps\n"
687
+ "Upload Speed: 0.00 Mbps\n"
688
+ "Unloaded Ping: 0 ms\n"
689
+ "Loaded Ping: 0 ms"
690
+ )
691
+
692
+ avg_ping_unloaded, ping_unloaded_vals = fast_com_ping_unloaded(
693
+ token=token, verbose=verbose, count=ping_count
694
+ )
695
+ dl_speed_loaded, avg_ping_loaded, ping_loaded_vals = fast_com_download(
696
+ token=token, verbose=verbose, max_time=max_time, ping_count=ping_count, ping_interval=1
697
+ )
698
+ upload_speed_dynamic = upload_js_comparable_dynamic_test(
699
+ token=token, verbose=verbose, max_time=max_time
700
+ )
701
+
702
+ result = {
703
+ "download_speed": dl_speed_loaded,
704
+ "upload_speed": upload_speed_dynamic,
705
+ "unloaded_ping": avg_ping_unloaded,
706
+ "loaded_ping": avg_ping_loaded,
707
+ }
708
+ return result
709
+
710
+
711
+ def main():
712
+ print("Starting fast.com speed test...")
713
+
714
+ token = get_fast_token(verbose=False)
715
+ if not token:
716
+ print("Failed to get token. All test values will be 0.")
717
+ return
718
+
719
+ print("\nRunning unloaded ping test:")
720
+ avg_ping_unloaded, ping_unloaded_vals = fast_com_ping_unloaded(
721
+ token=token, verbose=False, count=3
722
+ )
723
+ print("Unloaded Ping: {:d} ms".format(int(round(avg_ping_unloaded))))
724
+
725
+ print("\nRunning download test:")
726
+ dl_speed_loaded, avg_ping_loaded, ping_loaded_vals = fast_com_download(
727
+ token=token, verbose=False, max_time=10, ping_count=5, ping_interval=1
728
+ )
729
+ print("Download test results: {:.2f} Mbps".format(dl_speed_loaded))
730
+ print("Loaded Ping: {:d} ms".format(int(round(avg_ping_loaded))))
731
+
732
+ print("\nRunning upload test:")
733
+ upload_speed_dynamic = upload_js_comparable_dynamic_test(
734
+ token=token, verbose=False, max_time=10
735
+ )
736
+ print("Upload test result: {:.2f} Mbps".format(upload_speed_dynamic))
737
+
738
+ print("All tests completed.")
739
+
740
+
741
+ if __name__ == "__main__":
742
+ main()
@@ -0,0 +1,16 @@
1
+ Metadata-Version: 2.4
2
+ Name: fastdotcom
3
+ Version: 0.0.4
4
+ Summary: Python API for testing internet speed on Fast.com
5
+ Home-page: https://github.com/nkgilley/fast.com
6
+ Author: Nolan Gilley
7
+ License: MIT
8
+ License-File: LICENSE
9
+ Requires-Dist: requests>=2.0
10
+ Requires-Dist: icmplib>=3.0.4
11
+ Dynamic: author
12
+ Dynamic: home-page
13
+ Dynamic: license
14
+ Dynamic: license-file
15
+ Dynamic: requires-dist
16
+ Dynamic: summary
@@ -0,0 +1,7 @@
1
+ fastdotcom/__init__.py,sha256=jLBBIH8OuQ8ElxIYbI71h65ao-4a6qlVvpZAS4onJHs,24566
2
+ fastdotcom-0.0.4.dist-info/licenses/LICENSE,sha256=2n6rt7r999OuXp8iOqW9we7ORaxWncIbOwN1ILRGR2g,7651
3
+ fastdotcom-0.0.4.dist-info/METADATA,sha256=8qLdSgTxeU9lym1EORjd8k2BhvMEAjXKOLM52hXkclA,390
4
+ fastdotcom-0.0.4.dist-info/WHEEL,sha256=DnLRTWE75wApRYVsjgc6wsVswC54sMSJhAEd4xhDpBk,91
5
+ fastdotcom-0.0.4.dist-info/top_level.txt,sha256=iAYZwhemDpSRlADEeolvIlE2_7Qn6KTFBO0lGdKCX1k,11
6
+ fastdotcom-0.0.4.dist-info/zip-safe,sha256=AbpHGcgLb-kRsJGnwFEktk7uzpZOCcBY74-YBdrKVGs,1
7
+ fastdotcom-0.0.4.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (80.4.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,165 @@
1
+ GNU LESSER GENERAL PUBLIC LICENSE
2
+ Version 3, 29 June 2007
3
+
4
+ Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
5
+ Everyone is permitted to copy and distribute verbatim copies
6
+ of this license document, but changing it is not allowed.
7
+
8
+
9
+ This version of the GNU Lesser General Public License incorporates
10
+ the terms and conditions of version 3 of the GNU General Public
11
+ License, supplemented by the additional permissions listed below.
12
+
13
+ 0. Additional Definitions.
14
+
15
+ As used herein, "this License" refers to version 3 of the GNU Lesser
16
+ General Public License, and the "GNU GPL" refers to version 3 of the GNU
17
+ General Public License.
18
+
19
+ "The Library" refers to a covered work governed by this License,
20
+ other than an Application or a Combined Work as defined below.
21
+
22
+ An "Application" is any work that makes use of an interface provided
23
+ by the Library, but which is not otherwise based on the Library.
24
+ Defining a subclass of a class defined by the Library is deemed a mode
25
+ of using an interface provided by the Library.
26
+
27
+ A "Combined Work" is a work produced by combining or linking an
28
+ Application with the Library. The particular version of the Library
29
+ with which the Combined Work was made is also called the "Linked
30
+ Version".
31
+
32
+ The "Minimal Corresponding Source" for a Combined Work means the
33
+ Corresponding Source for the Combined Work, excluding any source code
34
+ for portions of the Combined Work that, considered in isolation, are
35
+ based on the Application, and not on the Linked Version.
36
+
37
+ The "Corresponding Application Code" for a Combined Work means the
38
+ object code and/or source code for the Application, including any data
39
+ and utility programs needed for reproducing the Combined Work from the
40
+ Application, but excluding the System Libraries of the Combined Work.
41
+
42
+ 1. Exception to Section 3 of the GNU GPL.
43
+
44
+ You may convey a covered work under sections 3 and 4 of this License
45
+ without being bound by section 3 of the GNU GPL.
46
+
47
+ 2. Conveying Modified Versions.
48
+
49
+ If you modify a copy of the Library, and, in your modifications, a
50
+ facility refers to a function or data to be supplied by an Application
51
+ that uses the facility (other than as an argument passed when the
52
+ facility is invoked), then you may convey a copy of the modified
53
+ version:
54
+
55
+ a) under this License, provided that you make a good faith effort to
56
+ ensure that, in the event an Application does not supply the
57
+ function or data, the facility still operates, and performs
58
+ whatever part of its purpose remains meaningful, or
59
+
60
+ b) under the GNU GPL, with none of the additional permissions of
61
+ this License applicable to that copy.
62
+
63
+ 3. Object Code Incorporating Material from Library Header Files.
64
+
65
+ The object code form of an Application may incorporate material from
66
+ a header file that is part of the Library. You may convey such object
67
+ code under terms of your choice, provided that, if the incorporated
68
+ material is not limited to numerical parameters, data structure
69
+ layouts and accessors, or small macros, inline functions and templates
70
+ (ten or fewer lines in length), you do both of the following:
71
+
72
+ a) Give prominent notice with each copy of the object code that the
73
+ Library is used in it and that the Library and its use are
74
+ covered by this License.
75
+
76
+ b) Accompany the object code with a copy of the GNU GPL and this license
77
+ document.
78
+
79
+ 4. Combined Works.
80
+
81
+ You may convey a Combined Work under terms of your choice that,
82
+ taken together, effectively do not restrict modification of the
83
+ portions of the Library contained in the Combined Work and reverse
84
+ engineering for debugging such modifications, if you also do each of
85
+ the following:
86
+
87
+ a) Give prominent notice with each copy of the Combined Work that
88
+ the Library is used in it and that the Library and its use are
89
+ covered by this License.
90
+
91
+ b) Accompany the Combined Work with a copy of the GNU GPL and this license
92
+ document.
93
+
94
+ c) For a Combined Work that displays copyright notices during
95
+ execution, include the copyright notice for the Library among
96
+ these notices, as well as a reference directing the user to the
97
+ copies of the GNU GPL and this license document.
98
+
99
+ d) Do one of the following:
100
+
101
+ 0) Convey the Minimal Corresponding Source under the terms of this
102
+ License, and the Corresponding Application Code in a form
103
+ suitable for, and under terms that permit, the user to
104
+ recombine or relink the Application with a modified version of
105
+ the Linked Version to produce a modified Combined Work, in the
106
+ manner specified by section 6 of the GNU GPL for conveying
107
+ Corresponding Source.
108
+
109
+ 1) Use a suitable shared library mechanism for linking with the
110
+ Library. A suitable mechanism is one that (a) uses at run time
111
+ a copy of the Library already present on the user's computer
112
+ system, and (b) will operate properly with a modified version
113
+ of the Library that is interface-compatible with the Linked
114
+ Version.
115
+
116
+ e) Provide Installation Information, but only if you would otherwise
117
+ be required to provide such information under section 6 of the
118
+ GNU GPL, and only to the extent that such information is
119
+ necessary to install and execute a modified version of the
120
+ Combined Work produced by recombining or relinking the
121
+ Application with a modified version of the Linked Version. (If
122
+ you use option 4d0, the Installation Information must accompany
123
+ the Minimal Corresponding Source and Corresponding Application
124
+ Code. If you use option 4d1, you must provide the Installation
125
+ Information in the manner specified by section 6 of the GNU GPL
126
+ for conveying Corresponding Source.)
127
+
128
+ 5. Combined Libraries.
129
+
130
+ You may place library facilities that are a work based on the
131
+ Library side by side in a single library together with other library
132
+ facilities that are not Applications and are not covered by this
133
+ License, and convey such a combined library under terms of your
134
+ choice, if you do both of the following:
135
+
136
+ a) Accompany the combined library with a copy of the same work based
137
+ on the Library, uncombined with any other library facilities,
138
+ conveyed under the terms of this License.
139
+
140
+ b) Give prominent notice with the combined library that part of it
141
+ is a work based on the Library, and explaining where to find the
142
+ accompanying uncombined form of the same work.
143
+
144
+ 6. Revised Versions of the GNU Lesser General Public License.
145
+
146
+ The Free Software Foundation may publish revised and/or new versions
147
+ of the GNU Lesser General Public License from time to time. Such new
148
+ versions will be similar in spirit to the present version, but may
149
+ differ in detail to address new problems or concerns.
150
+
151
+ Each version is given a distinguishing version number. If the
152
+ Library as you received it specifies that a certain numbered version
153
+ of the GNU Lesser General Public License "or any later version"
154
+ applies to it, you have the option of following the terms and
155
+ conditions either of that published version or of any later version
156
+ published by the Free Software Foundation. If the Library as you
157
+ received it does not specify a version number of the GNU Lesser
158
+ General Public License, you may choose any version of the GNU Lesser
159
+ General Public License ever published by the Free Software Foundation.
160
+
161
+ If the Library as you received it specifies that a proxy can decide
162
+ whether future versions of the GNU Lesser General Public License shall
163
+ apply, that proxy's public statement of acceptance of any version is
164
+ permanent authorization for you to choose that version for the
165
+ Library.
@@ -0,0 +1 @@
1
+ fastdotcom
@@ -0,0 +1 @@
1
+