顯示具有 script 標籤的文章。 顯示所有文章
顯示具有 script 標籤的文章。 顯示所有文章

2021年6月12日 星期六

Node.js 筆記 - 使用 Puppeteer 監控瀏覽網頁的 Requests 跟 HTML Code @ macOS 11.4, node v14.14.0, npm 6.14.5

緣起於在追蹤網站架構時,每次都靠 chrome browser 開發人員工具去追蹤特定的 request 還好,若需要大量瀏覽找尋一些蛛絲馬跡時,就會很煩!以前很閒時,就會跳下去寫 chrome extension 或是熱衷於 C++ 時,就會寫一點點  Chromium Embedded Framework 來寫個小型瀏覽器,最後想起來試試看 Puppeteer 吧!

使用 Puppeteer 很輕鬆,除了是很常見的 Javascript 語言外,Puppeteer 套件提供了網頁端常見的事件偵測、所發的 Request 清單。就這樣拼拼湊湊即可完工:

(async () => {
const browser = await puppeteer.launch({headless: false});
//const page = await browser.newPage();
const context = await browser.createIncognitoBrowserContext();
const page = await context.newPage();
await page.emulate(device);
await page.setRequestInterception(true);

// https://pptr.dev/#?product=Puppeteer&version=v10.0.0&show=api-event-domcontentloaded
// https://developer.mozilla.org/en-US/docs/Web/API/Window/DOMContentLoaded_event
//
// The DOMContentLoaded event fires when the initial HTML document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading.
//
page.on('domcontentloaded', () => {
console.log('on.domcontentloaded');
});

// https://pptr.dev/#?product=Puppeteer&version=v10.0.0&show=api-event-domcontentloaded
// https://developer.mozilla.org/en-US/docs/Web/API/Window/load_event
//
// The load event is fired when the whole page has loaded, including all dependent resources such as stylesheets and images. This is in contrast to DOMContentLoaded, which is fired as soon as the page DOM has been loaded, without waiting for resources to finish loading.
//
page.on('load', async () => {
console.log('on.load');
watchTags(page, watch_tags);
});

// https://pptr.dev/#?product=Puppeteer&version=v10.0.0&show=api-event-framenavigated
// https://pptr.dev/#?product=Puppeteer&version=v10.0.0&show=api-class-frame
page.on('framenavigated', frame => {
console.log('on.framenavigated: '+frame.url());
});

// https://pptr.dev/#?product=Puppeteer&version=v10.0.0&show=api-event-request
// https://pptr.dev/#?product=Puppeteer&version=v10.0.0&show=api-class-httprequest
page.on('request', request => {
watchRequest(page.url(), request.url());
if (skip_resource_type[ request.resourceType() ])
request.abort();
else
request.continue();
});

// https://pptr.dev/#?product=Puppeteer&version=v10.0.0&show=api-event-response
// https://pptr.dev/#?product=Puppeteer&version=v10.0.0&show=api-class-httpresponse
page.on('response', response => {
//console.log('on.response: '+response.url());
});

while (true) {
if (url_init.length > 0) {
const target_url = url_init.shift();
await page.goto(target_url, {
waitUntil: 'networkidle0',
});
console.log('networkidle0');
}
if (url_init.length > 0)
await sleep(5000);
else
await sleep(50);
}
await browser.close();
})();

如此,搭配 command line 使用,就可很快的監控想要的 request 規則,或是 HTML DOM Tree 的變化,例如監控 <script> 的讀取位置在哪:

% node index.js -url "https://tw.yahoo.com" -tag "script.src"
...
on.load
[WATCH][TAG] script: src
Web URL: [https://tw.yahoo.com/]
[
  { src: 'https://s.yimg.com/wi/ytc.js' },
  {
    src: 'https://tw.mobi.yahoo.com/polyfill.min.js?features=array.isarray%2Carray.prototype.every%2Carray.prototype.foreach%2Carray.prototype.indexof%2Carray.prototype.map%2Cdate.now%2Cfunction.prototype.bind%2Cobject.keys%2Cstring.prototype.trim%2Cobject.defineproperty%2Cobject.defineproperties%2Cobject.create%2Cobject.freeze%2Carray.prototype.filter%2Carray.prototype.reduce%2Cobject.assign%2Cpromise%2Crequestanimationframe%2Carray.prototype.some%2Cobject.getownpropertynames%2Clocale-data-en-us%2Cintl%2Clocale-data-zh-hant-tw&version=2.1.23'
  },
  { src: 'https://s.yimg.com/aaq/yc/2.9.0/zh.js' },
  {
    src: 'https://s.yimg.com/ud/fp/js/vendor.174522d6d76b51858b93.min.js'
  },
  { src: 'https://s.yimg.com/ud/fp/js/common.js' },
  { src: 'https://s.yimg.com/oa/consent.js' },
  { src: 'https://consent.cmp.oath.com/cmpStub.min.js' },
  { src: 'https://consent.cmp.oath.com/cmp.js' },
  { src: 'https://s.yimg.com/ss/rapid3.js' },
  { src: 'https://s.yimg.com/rq/darla/boot.js' },
  {
    src: 'https://s.yimg.com/ud/fp/js/main.6622c6aeda051386afaa.min.js'
  },
  { src: 'https://mbp.yimg.com/sy/os/yaft/yaft-0.3.22.min.js' },
  {
    src: 'https://mbp.yimg.com/sy/os/yaft/yaft-plugin-aftnoad-0.1.3.min.js'
  },
  { src: 'https://s.yimg.com/aaq/vzm/perf-vitals_1.0.0.js' },
  {
    src: 'https://fc.yahoo.com/sdarla/php/client.php?dm=1&lang=zh-Hant-TW'
  },
  {
    src: 'https://s.yimg.com/aaq/c/e7fecc0.caas-abu_highlander.min.js'
  }
]
...

2016年9月8日 星期四

Ansible 筆記 - 設定 Nginx 啟用 ngx_http_geoip_module.so 片段程式 @ Ubuntu 14.0

其實該寫成 Ansible Role 的,但一時之間有點懶,先把練習的片段紀錄一下。

安裝 nginx-module-geoip:

$ cat geoip-nginx.yml
---
    - name: install geoip packages
      apt: name={{ item }} update_cache=yes state=latest
      with_items:
        - nginx-module-geoip
      when: install_package is defined and install_package

    - name: check maxmind db - http://geolite.maxmind.com/download/geoip/database/GeoLiteCountry/GeoIP.dat.gz
      command: bash -c 'test -e /data/GeoIP.dat || curl http://geolite.maxmind.com/download/geoip/database/GeoLiteCountry/GeoIP.dat.gz | gunzip - > /data/GeoIP.dat'

    - name: check maxmind db - http://geolite.maxmind.com/download/geoip/database/GeoLiteCity.dat.gz
      command: bash -c 'test -e /data/GeoLiteCity.dat || curl http://geolite.maxmind.com/download/geoip/database/GeoLiteCity.dat.gz | gunzip - > /data/GeoLiteCity.dat'


設定 nginx.conf:

$ cat server-deploy.yml
...
  tasks:
    ...
    - include: geoip-nginx.yml
    - name: setup nginx config file - add modules/ngx_http_geoip_module.so
      lineinfile:
        dest: /etc/nginx/nginx.conf
        insertbefore: '^user '
        line: 'load_module "modules/ngx_http_geoip_module.so";'

    - name: setup nginx config file - setup geoip resource path
      lineinfile:
        dest: /etc/nginx/nginx.conf
        insertafter: '^http {'
        line: '    geoip_country /data/GeoIP.dat; geoip_proxy 192.168.0.0/16; geoip_proxy 10.0.0.0/24; geoip_proxy_recursive on;'
        #line: '    geoip_city    /data/GeoLiteCity.dat;'

    - name: setup nginx file to enable geoip - update log format
      lineinfile:
        dest: /etc/nginx/nginx.conf
        regexp: ".*?http_user_agent.*?http_x_forwarded_for"
        line: "                      '\"$http_user_agent\" \"$http_x_forwarded_for\"' $geoip_country_code \"$geoip_country_name\" ;"

    - name: setup nginx file to enable geoip - add GEOIP_COUNTRY_CODE for FastCGI
      lineinfile:
        dest: /etc/nginx/fastcgi_params
        insertbefore: "^fastcgi_param QUERY_STRING"
        line: "fastcgi_param     GEOIP_COUNTRY_CODE $geoip_country_code;"


如此一來,產生的 nginx.conf 如下:

$ cat /etc/nginx/nginx.conf && sudo nginx -t

load_module "modules/ngx_http_geoip_module.so";
user www-data;
worker_processes  1;

error_log  /var/log/nginx/error.log warn;
pid        /var/run/nginx.pid;


events {
    worker_connections  1024;
}


http {
    geoip_country /data/GeoIP.dat; geoip_proxy 192.168.0.0/16; geoip_proxy 10.0.0.0/24; geoip_proxy_recursive on;
    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;

    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"' $geoip_country_code "$geoip_country_name" ;

    access_log  /var/log/nginx/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    keepalive_timeout  65;

    #gzip  on;

    include /etc/nginx/conf.d/*.conf;
}
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful


查看 /var/log/nginx/access.log 就可以看到類似的範例:

.... CN,CHN,"China"
.... US,USA,"United States"


更多變數定義,請參考:http://nginx.org/en/docs/http/ngx_http_geoip_module.html

2015年11月10日 星期二

[Linux] 架設 Jenkins 筆記,以 Git plugin 與 PHP CodeIgniter - command-line interface (CLI) 定期任務為例 @ Ubuntu 14.04

架設還滿簡單的,幾行指令搞定:

$ wget -q -O - http://pkg.jenkins-ci.org/debian/jenkins-ci.org.key | sudo apt-key add -
$ sudo sh -c 'echo deb http://pkg.jenkins-ci.org/debian binary/ > /etc/apt/sources.list.d/jenkins.list'
$ sudo apt-get update
$ sudo apt-get install jenkins
$ sudo service jenkins start


如此一來,預設在 http://localhost:8080 就可以瀏覽到。

接著安裝一些工具,之後會用到:

$ sudo apt-get install git

接著紀錄一下自己的操作設定:
  • 管理 Jenkins -> 設定全域安全性
    • 勾選 Disable remember me
    • 安全性領域
      • 使用 Jenkins 內建使用者資料庫
    • 授權
      • 矩陣型安全性
        • 關閉 匿名使用者 所有權限
  • 管理 Jenkins -> 管理外掛程式
    • 更新
      • 把所有項目更新
    • 可用的
      • 搜尋 GIT plugin 跟 GIT client plugin 並安裝(若系統沒有 git,安裝完可以在 Jenkins 組態裡看到一些錯誤訊息)
其中授權那塊,必須先建立使用者,可以先從"登入成功的使用者可以做任何事"開始設定,過程會導入到建立使用者的流程。若有設定錯誤的地方導致無法管理時,可以修改 /var/lib/jenkins/config.xml 將 <useSecurity>true</useSecurity> 改成 <useSecurity>false</useSecurity> 後,再重新啟動 jenkins (sudo service jenkins restart)即可解決。

如此一來,就建立好 Jenkins 環境,而新工作也能夠用 git 了!擬個範例試試:假設專案在 bitbucket 管理,並使用 PHP CodeIgniter 架構,定期透過此專案來執行分析任務

作法:
  • Jenkins -> 新增作業 -> 填寫作業名稱(StudyJenkinsRoutine) -> 建置 Free-Style 軟體專案
    • 原始碼管理
      • Git
        • Repository URL: git@bitbucket.org:group/project.git
        • Credentials -> Add -> SSH Username with private key -> Enter directly (搭配 Bitbucket SSH 存取即可)
        • Additional Behaviours -> Advanced sub-modules behaviors -> 勾選 Recursively update submodules
    • 建置觸發程序
      • 定期建置(每十五分鐘跑一次,語法跟 crontab 一樣,但會建議用 H/15 來使用)
        • */15 * * * *  
    • 建置
      • 執行 Shell
        • php $WORKSPACE/index.php controller/function
如此一來,透過 Jenkins 的 Web 介面就可以設定與執行一些功能了,唯一留意的是執行工作上是否擁有相關的環境資源,例如範例是執行 PHP Framework 做事,那就得確保 php5-cli 裝了沒,若做的事跟資料庫相關,又得確定 php5-mysql 裝了沒等等。此外,上頭執行的 Shell 有用到 Jenkins 環境變數,要留意有些資料是跟 Jenkins 建立的工作名稱是相關的,例如工作名稱若有空白、等號以及相關的特殊符號時,極有可能會影響 shell script 的執行的。

關於 Jenkins 相關的路徑安排都跟 jenkins 帳號相關,例如 Jenkins 家目錄在 /var/lib/jenkins ,而添加一個任務名為 StudyJenkinsRoutine 時,其 $WORKSPACE 會是 /var/lib/jenkins/jobs/StudyJenkinsRoutine/workspace 的,這個位置也是 git clone 的資料所在。

最後,如果 Jenkins 是架設在 AWS EC2 上,若可以搭配 ELB 跟 SSL 憑證時,可以偷懶使用 ELB 將 https 流量導向到 Jenkins 8080 ,可以無痛提供 https 服務囉。

2015年4月27日 星期一

透過 Script 合併 MPEG2-TS (Transport Stream / TS) 與 ffmpeg 轉檔

因緣際會,處理一些用 M3U 串起來的一堆瑣碎的 .ts 檔案,這些檔案透過 M3U 的格式,可清楚描述第幾秒要播放哪個片段。然而,在一些測試上會略顯麻煩 Orz 所以撰寫一些 script 跟 ffmpeg 來把這些東西在整合成單一檔案 :P

眾多 ts 檔案該怎樣合併成一則?其實單純用 file append 即可:

$ cat 1.ts 2.ts 3.ts > output.ts

所以,假設有一個 M3U 時,可以透過以下指令抓出:

$ grep -v "#" list.m3u | xargs
1.ts 2.ts 3.ts ...


可惜啊,資料比數太 command line 可能會出爆,建議改用 script 來處理,例如 PHP:

<?php
foreach(explode("\n", file_get_contents($m3u_input)) as $line) {
if (empty($line) || $line[0] == '#')
continue;
$raw = file_get_contents($file);
if (!empty($raw))
file_put_contents("$output.raw", $raw, FILE_APPEND);
}


如此一來,就可以把一票 .ts 檔重新建立成單一檔案 .raw 。接著,再用 ffmpeg 轉成想要測試的格式吧!關於 ts 轉 mp4 ,可以透過 ffmepg 處理,其中 ffmpeg 會自己判斷輸出的格式(此例是 mp4),所以有需要也可以用 output.avi:

$ ffmpeg -i input.ts -vcodec copy -acodec copy output.mp4
$ ffmpeg -i input.ts -vcodec copy -acodec copy -bsf:a aac_adtstoasc output.mp4


如果有一票目錄 + M3U 的話,就掃一下目錄建立一票相關的,接著可以用 find 再把這一票轉一轉:

$ find . -name "*.raw" -exec  ffmpeg -i {} -vcodec copy -acodec copy -bsf:a aac_adtstoasc {}.mp4 \;