Chatwork から来た社内メンバーへの通知をメンションありで Slack に通知する

※過去ブログの転記


作った経緯

  • 基本社内・社外含めコミュニケーションツールは Slack だけど Chatwork を使っているプロジェクトも存在する
  • Chatwork をブラウザタブで常時開いていないため通知に気づかない

流れ

ネットで調べると出てくる部分は省略しました。

  1. Google アカウントの作成(省略)
  2. Slack bot の作成(省略)
  3. Google App Script の作成方法(省略)
  4. Google App Script へのライブラリ追加方法(省略)
    (2020/12/26 時点で新しいUIでの GAS ではライブラリの追加ができなかったので古いUIに切り替えて追加しました)
  5. Google App Script に処理を書く(ここがメイン)
  6. Chatwork でのサービス連携(省略)

省略した部分に関しては以下の記事がわかりやすいと思います

もっとこうした方がいいなどご意見ございましたらご指摘ください!(特に正規表現は雰囲気で書いている。)

const SLACK_TOKEN = 'xoxb-...'; // Slack bot の token を設定
// https://api.slack.com/methods/chat.postMessage のArguments を指定する
const OPTIONS = {
  username: 'Chatwork',
  link_name: true,
  icon_emoji: ":chatwork:"
};
// Slack に存在する社内ユーザーの ChatworkID と SlackユーザーID の定義
// どれが誰か分からなくなるので日本語でコメント文を書いておく
const MENTIONS = {
  '1234567': 'SLACKUSERID1', // ユーザー1
  '890123': 'SLACKUSERID2', // ユーザー2
}
// Chatwork ルームID => Slack チャンネル名
const CHANNELS = {
  '123456789': 'channel-A',
  '12345678': 'channel-B'
}

/**
 * webhook から呼び出される処理
 * ACCOUNTS に対象ユーザーがないメッセージは送らない
 */
function doPost(e) {
  // リクエストからJSONデータを取得してパース
  const obj = JSON.parse(e.postData.contents);
  // Chatwork から受け取ったメッセージ
  const body = obj.webhook_event.body;
  // body に含まれる対象ユーザーを複数検索(ex. 「[To:1234567]ユーザー1さん [To:890123]ユーザー2 さん」 という文字列)
  const toUsers = body.match(/\[To:([\s\S]*?)\]/g);
  var mention = '';
  if (toUsers != null) {
      toUsers.forEach(function (user) {
          const toUser = user.match(/\[To:([\s\S]*?)\]/);
          if (toUser[1] in MENTIONS) {
              mention += "<@"+ MENTIONS[toUser[1]]  +"> さん ";
          }
      });
  }

  // 返信元に ChatworkID が含まれている場合にもメンションに追加する (ex. [rp aid=1234567 to=123456789-xxxx] という文字列)
  const reply = body.match(/\[rp\ aid\=([\s\S]*?)\ to\=/);
  if (reply && reply[1] in MENTIONS) {
    mention += "<@"+ MENTIONS[reply[1]]  +"> さん ";
  }

  // 全員宛の場合はメンションに @channel をつける
  const isAll = body.match(/toall/);
  if (isAll) {
      mention += " <!channel> ";
  }
  
  // メンションが空であれば return
  if (mention === '') {
    return;
  }
  // メンションの設定
  let message = mention + "宛てにチャットワークより連絡がありました。\n";
  // Chatwork のメッセージに飛ぶためのリンク設定
  message += "https://www.chatwork.com/#!rid" + obj.webhook_event.room_id + "-" + obj.webhook_event.message_id + "\n";
  // 本文の表示
  message += body;

  // SlackApp を使用して Slack に message を投げる
  const slackApp = SlackApp.create(SLACK_TOKEN);
  slackApp.postMessage('#' + CHANNELS[obj.webhook_event.room_id], message, OPTIONS);
}

あとは Chatwork 側のWebhookの設定とSlack側のチャンネルたちにSlask Botのアプリを追加してあげる。

というか Chatwork の Webhook の上限が5件までっぽい。有料プランは上限上げてほしい。

コミュニケーションツールはSlack一択にしたいな〜〜〜〜〜〜〜


参考にしたサイト

www.whizz-tech.co.jp github.com help.receptionist.jp https://help.chatwork.com/hc/ja/articles/360000142962-%E3%82%A2%E3%82%AB%E3%82%A6%E3%83%B3%E3%83%88ID%E3%82%92%E7%A2%BA%E8%AA%8D%E3%81%99%E3%82%8Bhelp.chatwork.com

丸囲み文字コピペ用

数字

① ② ③ ④ ⑤ ⑥ ⑦ ⑧ ⑨ ⑩
⑪ ⑫ ⑬ ⑭ ⑮ ⑯ ⑰ ⑱ ⑲ ⑳

英文字

Ⓐ Ⓑ Ⓒ Ⓓ Ⓔ Ⓕ Ⓖ Ⓗ Ⓘ Ⓙ Ⓚ Ⓛ Ⓜ Ⓝ
Ⓞ Ⓟ Ⓠ Ⓡ Ⓢ Ⓣ Ⓤ Ⓥ Ⓦ Ⓧ Ⓨ Ⓩ

カタカナ

㋐ ㋑ ㋒ ㋓ ㋔ ㋕ ㋖ ㋗ ㋘ ㋙ ㋚ ㋛ ㋜ ㋝ ㋞ ㋟ ㋠ ㋡ ㋢ ㋣ ㋤ ㋥ ㋦ ㋧ ㋨
㋩ ㋪ ㋫ ㋬ ㋭ ㋮ ㋯ ㋰ ㋱ ㋲ ㋳ ㋴ ㋵ ㋶ ㋷ ㋸ ㋹ ㋺ ㋻ ㋼ ㋽ ㋾

Linuxコマンド覚書

find

ファイルもしくはディレクトリの検索 実行すると検索結果が出力される

$ find {検索するパス} {検索条件} {オプション}

拡張子を指定して検索

$ find ../../ -name '*.txt'

特定の文字列を含むファイルを検索

$ find Desktop/ -type f -name "*2019*"

sampleという名前が含まれるファイルを検索

$ find /Desktop -name "*sample*" -type f

sampleという名前が含まれるディレクトリを検索

$ find /Desktop -name "*sample*" -type d

名前にsampleが含まれる、パーミッションが644のものを検索

$ find /Desktop -name "*sample*" -perm 644 

昨日更新されたファイルを検索

$ find Desktop/ -mtime 1

0:今日
1:昨日
-3:三日以内に更新されたファイル
+10:10日よりも前に更新されたファイル

空ファイルもしくはディレクトリを検索する

$ find Desktop/ -empty

ファイル名がsmapleを含むかつ.pngファイルを検索する

$ find Desktop/ -name "*sample*" -and  -name "*.png"

ファイル名がsmapleを含むもしくは.pngファイルを検索する

$ find Desktop/ -name "*sample*" -or  -name "*.png"

grep

ファイルの中の文字列を検索する

$ grep {検索正規表現} {パス/ファイル名}

デスクトップにあるsample.txtの中にaaaという文字列がないかを検索する

$ grep aaa Desktop/sample.txt 

検索結果に行番号を表示する

$ grep aaa Desktop/sample.txt -n

大文字小文字を区別せずに検索する

$ grep aaa Desktop/sample.txt -i

検索結果の前後2行分を表示する

$ grep aaa Desktop/sample.txt -C2

ディレクトリ内も検索対象とする

$ grep aaa Desktop/ -r

open

open -a {アプリを指定} {パスとファイル名} 

finderを開く

$ open .

Chromeでデスクトップのsample.jpegを開く

$ open -a "Google Chrome" Desktop/sample.jpeg 

アプリ名にスペースがある場合はダブルクォートで囲う

一階層上の全ての.pngファイルを開く

$ open ../*.png

screencapture

$ screencapture {保存場所とファイル名}

デスクトップにsample.pngという名前で画面キャプチャ

$ screencapture ../Destop/sample.png

PHPUnitのアサーションについて

書いてないのもあるので修正が必要



論理値の検証

assertFalse

assertFalse(bool $condition[, string $msg = ''])

$conditionがfalseかどうか
assertNotFalse()はこの逆

assertTrue

assertTrue(bool $condition[, string $msg = ''])

$conditionがtrueかどうか
assertNotTrue()はこれの逆

assertIsBool

assertIsBool($actual[, string = ''])

$actualがboolかどうか
assertIsNotBool()はこの逆

空かどうかの検証

assertEmpty

assertEmpty(mixed $actual[, string $msg = '’])

$actualが空かどうか
assertNotEmpty()はこれの逆

assertNull

assertNull(mixed $variable[, string $msg = ''])

$variableNULLかどうか


等しいかどうか

assertEquals

assertEquals(mixed $expect, mixed $actual[, string $msg = ''])

$expect$actualが等しいかどうか
等しくない時に$msgを返す
assetNotEquals()はこの逆

assertEquals(float $expect, float $actual[, string $msg = '', float $delta = 0])

$expect$actualの差分が$delta以下かどうか
以上の時に$msgを返す

assertSame

assertSame(mixed $expect, mixed $actual[, string $msg = ''])

2つの変数$expect$actualが同じ型・同じ値かどうか
assertNotSame()はこれの逆


比較の検証

assertGreaterThan

assertGreaterThan(mixed $expect, mixed $actual[, string $msg = ''])

$actualの値が$expectの値より大きいかどうか
$expect < $actual
大きくない時に$msgを返す

assertGreaterThanOrEqual

assertGreaterThanOrEqual(mixed $expect, mixed $actual[,string $msg =''])

$actualの値が$expectの値を含み大きいかどうか
$expect <= $actual
以下の時に$msgを返す

assertLessThan

assertLessThan(mixed $expect, mixed $actual[, string $msg = ''])

$actualの値が$expectより小さいかどうか
$expect > $actual
小さくない時に$msgを返す

assertLessThanOrEqual

assertLessThanOrEqual(mixed $expect, mixed $actual[, string $msg = ''])

$actualの値が$expectの値を含み小さいかどうか
$expect >= $actual
以上の時に$msgを返す


配列の検証

assertIsArray

assertIsArray($acutual[,string $msg = ''])

$actualが配列かどうか
assertIsNotArray()はこの逆

assertArrayHasKey

assertArrayHasKey(mixed $key, array $array [, string $msg = ‘'])

$array配列に$keyキーが存在するかどうか
存在しないときにエラー$msgを返す
asserArrayNotHasKey()はこれの逆

assertArraySubset

assertArraySubset(array $subset, array $array [, bool $strict = false, string $msg = '']);

$array$subsetを含んでいるかどうか
含まない場合に$msgを返す
$stricttrueにすると型の比較まで行う
エラーログが$subsetをダンプするだけで、どこが違うかを教えてくれないのでわかりづらい

assertContains

assertContains(mixed $needle, iterable $haystack[, string $msg])

$needle$haystackに存在するかどうか
objectも検証可能
存在しない場合に$msgを返す
assertNotContains()はこれの逆

assertContainsOnly

assertContainsOnly(string $type, itrable $haystack[, bool $isNativeType = null, strig $msg = '’])

$haystackの中身の型が$typeだけかどうか
$typeだけじゃない時に$msgを返す
$isNaviteTypeクラスは$typeがネイティブなPHPの型であるかどうかを表す
assertNotContainsOnly()はこれの逆


オブジェクトの検証

assertObjectHasAttribute

assertObjectHasAttribute(string $attrName, object $obj[, string $msg = ''])

$obj->attrNameが存在するかどうか
assertObjectNotHasAttribute()はこれの逆


文字列の検証

assertContains

assertContains(string $needle, string $haystack[, string $msg], bool $ignoreCase = false])

$needle$haystackの文字列に含まれるかどうか
$ignoreCasetrueの時に大文字小文字を区別しない

assertIsString

assertIsString($actual[, $msg = ''])

$actualの型がstringかどうか
assertIsNotString()はこれの逆

assertStringMatchsFormat

assertStringMatchsFormat(string $format, string $string[, string $msg = ''])

$string が書式文字列$formatに一致しているかどうか

assertRegExp

assertRegExp(string $pattern, string $string[, string $msg = ''])

$string$patternに一致しているかどうか
assertNotRegExp()はこれの逆

assertStringEndsWith

assertStringEndsWith(string $suffix, string $string[, string $msg = ''])

$string$suffixで終わっているかどうか
assertStringEndsNotWith()はこれの逆

assertStringStartsWith

assertStringStartsWith(string $prefix, string $string[, string $msg = ''])

$string$prefixで始まっているかどうか
assertStringStartsNotWith()はこれの逆


数の検証

assertCount

assertCount($expect, $haystack[, string $msg = ''])

$haystackの要素数$expectと一致しているかどうか
assertNotCount()はこれの逆


クラスの検証

assertClassHasAttribute

assertClassHasAttribute(string $attrName, string $className, string $msg = ‘')

$classNameにプロパティ変数attrNameが存在するかどうか
存在しない場合に$msgを返す
assertClassNotHasAttribute()はこれの逆

assertClassHasStaticAttribute

assertClassHasStaticAttribute(string $attrName, string $className [, string $msg = ''])

$classNameに静的プロパティ$attrNameが存在するかどうか
存在しない場合に$msgを返す

assertContainsOnlyInstancesOf

assertContainsOnlyInstancesOf(string $className, Traversable|array $haystack[, string $msg = ''])

$haystack$classNameクラスの唯一のインスタンスを含むかどうか
含まない時に$msgを返す


その他の型の検証

assertIsFloat

assertIsFloat($actual[, string $msg =''])

$actualの型がfloatかどうか
assertIsNotFloat()はこれの逆

assertIsInt

assertIsInt($actual[, string $msg = ''])

$actualの型がintかどうか
assertIsNotInt()はこれの逆

assertIsInterable

assertIsInterable($actual[, string $msg])

$actualの型がintertableかどうか
assertIsNotInterable()はこれの逆

assertIsNumeric

assertIsNumeric($actual[, string $msg = ''])

$actualの型がnumericかどうか
assertIsNotNumeric()はこれの逆

assertIsObject

assertIsObject($actual[, string $msg = ''])

$actualの型がobjectかどうか
assetIsNotObject()はこれの逆

assertIsResource

assertIsResource($actual[, string $msg = ''])

$actualの型がresouceかどうか
assertIsNotResouce()はこれの逆

assertIsScalar

assertIsScalar($actual[, string $msg = ''])

$actualの型がscalar値かどうか
assertIsNotScalar()はこれの逆

assertIsCallable

assertIsCallable($actual[, string $msg])

$actualの型がcallableかどうか
assertIsNotCallable()はこの逆


その他の検証

assertInfinite

assertInfinite(mixed $variable[,string $msg])

$variableがINFかどうか
assertFinite()はこの逆

assertNan

assertNan(mixed $valiable[, string $msg= ''])

$valiableがNANかどうか

assertInstanceOf

assertInstanceOf($expect $actual[, string $msg= ''])

$actual$expectインスタンスかどうか
assertNotInstanceOf()はこの逆

assertEqualXMLStructure

assertEqualXMLStructure(DOMElement $expect, DOMElement $actual[, bool $checkAttr = false, $msg = ''])

$actualのDOMElementのXML構造が$expectのDOMElementのXML構造と等しいかどうか


ファイル・ディレクトリの検証

assertIsReadable

assertIsReadable($actual[, string $msg = ''])

$actualに指定したファイルもしくはディレクトリが読み込み可能かどうか
読み込み不可の場合は$msgを返す
assertNotIsReadable()はこれの逆

assertIsWritable

assertIsWritable($actual[, string $msg = ''])

$actualに指定したファイルもしくはディレクトリが書き込み可能かどうか
書き込み不可の場合は$msgを返す
assertNotIsWritable()はこれの逆

assertDirectoryExsits

assertDirectoryExsits(string $dir[, string $msg = ''])

$dirで指定したディレクトリが存在するかどうか
存在しない時に$msgを返す
assertDirectoryNotExists()はこれの逆

assertDirectoryIsReadable

assertDirectoryIsReadable(string $dir[, string $msg = ''])

$dirで指定したディレクトリが読み込み可能かどうか
読み込み不可の時に$msgを返す
assertDirectoryNotIsReadable()はこれの逆

assertDirectoryIsWritable

assertDirectoryIsWritable(string $dir[, string $msg = ''])

$dirで指定したディレクトリが書き込み可能かどうか
書き込み不可の時に$msgを返す
assertDirectoryNotIsWritable()はこれの逆

assertFileEquals

assertFileEquals(string $expect, string $actual[, string $msg = ''])

$expectで指定したファイルと$actualで指定したファイルの内容が等しいかどうか
異なる場合に$msgを返す
assertFileNotEquals()はこの逆

assertFileExists

assertFileExists(string $fileName[, string $msg = ''])

ファイル$fileNameが存在するかどうか
存在しない時は$msgを返す
assertFileNotExists()はこの逆

assertFilesReadable

assertFilesReadable(string $fileName[, string $msg = ''])

$fileNameで指定したファイルが読み込み可能かどうか
読み込み不可の場合は$msgを返す
assertFilesNotReadable()はこの逆

assertFilesWritable

assertFilesWritable(string $fileName[, string $msg = ''])

$fileNameで指定したファイルが書き込み可能かどうか
書き込み不可の時には$msgを返す
assertFilesNotWritable()はこの逆

JSONの検証

assertJsonFileEqualsJsonFile

assertJsonFileEqualsJsonFile(mixed $expectFile, mixed $actualFile[, srtring $msg])

$actualFile$expectFileの内容がJSONとして等しいかどうか

assertJsonStringEqualsJsonFile

assertJsonStringEqualsJsonFile(mixed $expectFile, mixed $actualJson[, string $msg = ''])

$actualJsonの値が$expectFileの値と等しいかどうか

assertJsonStringEqualJsonString

assertJsonStringEqualJsonString(mixed $expectJson, mixed $actualJson[, string $msg =''])

$actualJsonの値が$expectJsonの値と等しいかどうか


参考にしたサイト

phpunit.readthedocs.io

jQueryのDOM操作メソッド 〜要素の取得編〜

続き
途中だけど忘れそうなのでとりあえずアップだけしておく...
後々追加するかも
もしかしたら間違ってる部分あるかも


children - 指定した要素の1階層下の子要素を取得する

$("#children").on("click",function(){
  $(this).children("p").css("background-color","red");
});

find - 指定した要素の子孫要素を取得する

p

pspan

p

$("#find").on("click",function(){
  $("#findTarget").find("span").css("background-color","red");
});

closest - 指定した直近の親要素を取得

  • listParent1
  • listParent2
    • listChild1
    • listChild2
    • listChild3
  • listParent3
  • listParent4
$("#closest").on("click",function(){
  $("#closestTarget ul li:last-of-type").closest("ul").css("background-color","red");
});

contents - 指定した要素の子要素のテキストを含み取得

contentsTarget
$("#contents").on("click",function(){
  console.log($(".contentsTarget").contents());//要素の中のテキストも取得
  console.log($(".contentsTarget").children());//要素を取得
  $(".contentsTarget").contents().wrap('<p style="background-color: red;" />');
});

next - 指定した要素の直後の兄弟要素を返す

$("#next").on("click",function(){
  $(this).next().css("background-color","red");
});

nextAll - 指定した要素以降の兄弟要素を返す

$("#nextAll").on("click",function(){
  $(this).nextAll("[id^='nextAllTarget']").css("background-color","red");
});

nextUntil - 指定した要素以降の兄弟要素で指定したセレクタに一致するまで選択する

$("#nextUntil").on("click",function(){
  $(this).nextUntil("#nextUntilTarget3","button").css("background-color","red");//第二引数でフィルタリングできる
});

prev - 指定した要素の直前の兄弟要素を返す

$("#prev").on("click",function(){
  $(this).prev().css("background-color","red");
});

prevAll - 指定した要素以前の兄弟要素を返す

$("#prevAll").on("click",function(){
  $(this).prevAll("[id^='prevAllTarget']").css("background-color","red");
});

prevUntil - 指定した要素以前の兄弟要素で指定したセレクタに一致するまで選択する

$("#prevUntil").on("click",function(){
  $(this).prevUntil("#prevUntilTarget2","button").css("background-color","red");//第二引数でフィルタリングできる
});

first - 指定した要素の一番最初の要素を取得

  • list
  • list
  • list
  • list
$("#first").on("click",function(){
  $("#firstTarget li").first().css("background-color","red");
});

last - 指定した要素の一番最後の要素を取得

  • list
  • list
  • list
  • list
$("#last").on("click",function(){
  $("#lastTarget li").last().css("background-color","red");
});

not - 指定したセレクタを除く

  • list
  • list
  • list
  • list
  • list
  • list
$("#not").on("click",function(){
  $("#notTarget").children("li").not(":nth-of-type(2)").css("background-color","red");
});

each - 指定した要素をループ処理

  • list
  • list
  • list
  • list
  • list
  • list
$("#each").on("click",function(){
  $("#eachTarget li").each(function(key,value){
    $(this).text($(this).text() + key);
  });
});

is - 指定した要素などのbool値を返す

$("#is").on("click",function(){
  var $true = $(this).is(":visible");
  var $false = $(this).is(":hidden");
  console.log($true);
  console.log($false);
});

has - 指定した要素などを持つ要素を取得する

hasTarget1

hasTarget2
$("#has").on("click",function(){
  $("[id^='hasTarget']").has("p").css("background-color","red");
  $("[id^='hasTarget']:has(span)").css("background-color","blue");
});

siblings - 前後を問わず同じ階層の要素を取得する

siblingsTarget1

siblingsTarget2
var $css = {
  "background-color":"red",
  "color":"white"
};
$("[id^=siblingsTarget]").css($css);
$("#siblings").on("click",function(){
  $(this).siblings("div[id^=siblingsTarget]").css("background-color","blue");
});

slice - 指定した部分を取り出す

  • list
  • list
  • list
  • list
  • list
$("#slice").on("click",function(){
  $("#sliceTarget li").slice(2,4).css("background-color","red");//第二引数がなければ2番目以降〜最後まで
});

filter - 要素の絞り込み

  • list
  • list
  • list
  • list
  • list
$("#filter").on("click",function(){
  $("#filterTarget li").filter(":nth-of-type(3)").css("background-color","red");
  $("#filterTarget li").filter("#last").css("background-color","blue");
});

eq - 0から始まるインデックス番号の要素を取得

  • list0
  • list1
  • list2
  • list3
  • list4
$("#eq").on("click",function(){
  $("#eqTarget li").eq(3).css("background-color","red");
  $("#eqTarget li").eq(-1).css("background-color","blue");//-1で最後の要素を取得する -2の場合はlist3を取得する
});

add - 指定した要素を追加

  • list
  • list
  • list
  • list
$("#add").on("click",function(){
  var $style = $("#addTarget li:nth-of-type(2)").next().add().css("background-color","red");//3番目のliにcssが適用される
  console.log($style);//2番目のli
});

addBack - 選択した要素に指定した要素を追加する

  • list
  • list
  • list
  • list
$("#addBack").on("click",function(){
  var $style2 = $("#addBackTarget li:nth-of-type(2)").next().addBack().css("background-color","red");
  console.log($style2);//2,3番目のli
});

end - 最新のフィルタリング処理を破棄して一つ前の選択状態に戻す

  • list
  • list
  • list
  • list
$("#end").on("click",function(){
  $("#endTarget").find("li:first-of-type").css("background-color","red").end().find("li:nth-of-type(2)").css("background-color","blue");
});

アコーディオンメニューを開いたときにコンテンツの一番初めからスクロールさせる

  • list

余計な余白


<button type="button" id="scroll">scroll()</button>
<ul id="scrollTarget">
    <li style="height: 500px;">list</li>
</ul>
<div style="height: 300px;">
    <p>余計な余白</p>
</div>
<script>
  var $scrollTarget = $("#scrollTarget");
  //開閉メニューのボタン
  var $scroll = $("#scroll");
  //topからの位置を取得
  var $scrollInt = $("#scroll").offset().top;

  //初期設定
  $scrollTarget.hide();

  $scroll.on("click",function(){
    $scrollTarget.slideToggle("normal",function(){
      //表示状態であれば、topからの位置分スクロールトップに移動
      if($scrollTarget.is(":visible")) {
        $("body,html").animate({scrollTop: $scrollInt},"fast");
      }
    });
  });
</script>

パーミッション確認方法など覚書

記号 意味 数字 権限 使用例
r read 4 読み出し 読むだけのHTML,CSS,画像ファイルなど
w write 2 書き込み データの書き込みや書き換えが必要なファイル
x exec 1 実行 サーバー上で実行が必要なファイル touch,rmなどはできない

記述例

数字 記号 意味
644 rw-r--r-- 所有者読み書き可能/所有者以外読み出しのみ (ファイルのデフォルトの権限)
755 rwxr-xr-x 所有者以外書き込み不可 (ディレクトリのデフォルトの権限)
700 rwx------ 所有者のみ読み書き実行可能
666 rw-rw-rw- 読み書きのみ

777 (rwxrwxrwx) はセキュリティ上良くない

$ ls -l は隠しファイルが表示されないので

$ ls -all {パス}

で指定パスのパーミッションを確認する

例:

drwxr-xr-x   18 user  staff     96 12  1 19:48 directory_name
1 2 3 4 5 6 7 8 9 10 11 12
d rwx r-x r-x 18 user staff 96 12 1 19:48 directory_name
  1. ディレクトリかファイルか
    d:ディレクト
    -:ファイル
    |:シンボリックリンク

  2. 所有者の権限

  3. グループの権限

  4. その他のアクセス権限

  5. そのディレクトリにあるディレクトリorファイル数

  6. 所有者名

  7. グループ名

  8. ファイルサイズ

  9. 作成日時もしくは変更日時の月

  10. 作成日時もしくは変更日時の日

  11. 作成日時もしくは変更日時の時間

  12. ファイルもしくはディレクトリ名

変更するときはchmod(change mode)で変更可能

$ chmod {変更したい権限} {パス}

パーミッション確認方法など覚書

※過去ブログの転記

 

 

記号 意味 数字 権限 使用例
r read 4 読み出し 読むだけのHTML,CSS,画像ファイルなど
w write 2 書き込み データの書き込みや書き換えが必要なファイル
x exec 1 実行 サーバー上で実行が必要なファイル touch,rmなどはできない

記述例

数字 記号 意味
644 rw-r--r-- 所有者読み書き可能/所有者以外読み出しのみ (ファイルのデフォルトの権限)
755 rwxr-xr-x 所有者以外書き込み不可 (ディレクトリのデフォルトの権限)
700 rwx------ 所有者のみ読み書き実行可能
666 rw-rw-rw- 読み書きのみ

例:

drwxr-xr-x   18 user  staff     96 12  1 19:48 directory_name
1 2 3 4 5 6 7 8 9 10 11 12
d rwx r-x r-x 18 user staff 96 12 1 19:48 directory_name
  1. ディレクトリかファイルか
    d:ディレクト
    -:ファイル
    |:シンボリックリンク

  2. 所有者の権限

  3. グループの権限

  4. その他のアクセス権限

  5. そのディレクトリにあるディレクトリorファイル数

  6. 所有者名

  7. グループ名

  8. ファイルサイズ

  9. 作成日時もしくは変更日時の月

  10. 作成日時もしくは変更日時の日

  11. 作成日時もしくは変更日時の時間

  12. ファイルもしくはディレクトリ名

変更するときはchmod(change mode)で変更可能

$ chmod {変更したい権限} {パス}

よく使うviコマンド

個人的によく使うやつ
またあれば追加して行く予定

操作 内容
:wq 保存して終了
:q! もしくは :q 保存せずに終了
:w 上書き保存
:w <file name> <file name>で保存
A 行の末尾で挿入モードへ
a カーソル位置の次の文字からinsertモードになる
I カーソル位置の行の先頭へ移動してからinsertモード
o カーソル位置の下に1行追加してinsertモード
cc 1行を削除してinserモード
V カーソルの行を選択してinsertモード
/文字列 文字列を検索
n マッチした検索文字列の次の文字列に
N マッチした検索文字列の前の文字列に
ctrl + v 矩形選択モード
gv 直前の選択範囲を再選択
:%d 全削除
dd カーソル位置の行を削除する
D カーソルから後ろを削除する
yy カーソル行をコピー
3yy カーソル行から3行コピー
p ペースト
u undo
ctrl + r undoをundo
/ をページ内検索
n 検索結果の次へ
N 検索結果の前へ

移動操作

操作 内容
h カーソルを左に
l (エル) カーソルを右に
k カーソルを上に
j カーソルを下に
w 次の単語へ
b 前の単語へ
ctrl + u 半画面上に進む
ctrl + f 1画面上に進む
ctrl + d 半画面上に戻る
ctrl + b 1画面上に戻る
0 行頭へ
$ 行末へ
8G 8行目へ
gg 最初の行へ
G 最終行へ

操作 内容
:vsplit 画面を左右に分割する

SSH接続時にログインメッセージを表示する

/etcディレクトリにmotdファイルの作成

$ sudo touch /etc/motd

書き込む

$ sudo vi /etc/motd

次回ログイン時に表示されるのを確認

f:id:IlIIlIIIlIIlI:20211016162615p:plain:w300

表示されなければパーミッションを644にする

田原年彦は下記サイトで作成しました
他にもメッセージを動的にする方法とかもあるみたいなので時間があれば試したい

tool-taro.com

jQueryのDOM操作メソッド 〜要素の追加・削除編〜

after - 指定した要素の後ろに引数で指定した要素を追加

$("#after").on("click",function(){
  $(this).after($(this).clone());
});

insertAfter - 指定した内容を引数で指定した要素の後ろに追加

$("#insertAfter").on("click",function(){
  $(this).clone().insertAfter($(this));
});

append - 指定した要素の中の後ろに引数で指定した要素を追加

$("#append").on("click",function(){
  $(this).append($(this).clone());
  console.log(this);
});

appendTo - 指定した内容を引数で指定した要素の中の後ろに追加

$("#appendTo").on("click",function(){
  console.log(this);
});

before - 指定した要素の前に引数で指定した要素を追加

$("#before").on("click",function(){
  $(this).before($(this).clone());
});

insertBefore - 指定した内容を引数で指定した要素の前に追加

$("#insertBefore").on("click",function(){
  $(this).clone().insertBefore($(this));
});

prepend - 指定した要素の中の前に引数で指定した要素を追加

$("#prepend").on("click",function(){
  $(this).prepend($(this).clone());
});

prependTo - 指定した内容を引数で指定した要素の中の前に追加

$("#prependTo").on("click",function(){
  $(this).clone().prependTo($(this));
});

clone - 指定した要素の前に追加

記述済みなので省略

detach - 要素の削除

削除後もjQueryから参照可能

var detachTarget = $("#detachTarget");
$("#detach").on("click",function(){
  var isDetachClass = $(this).toggleClass("detach");
  if(isDetachClass.hasClass("detach")) {
    detachTarget.detach();
  }else {
    $(this).after(detachTarget);
  }
});

remove - 要素の削除

$("#remove").on("click",function(){
  $(this).remove();
});

empty - 要素の削除

親を残して削除

$("#empty").on("click",function(){
  $(this).empty();
});

html - 指定したhtmlの取得・セット

$("#html").on("click",function(){
  console.log($(this).html());//指定セレクタを除いたhtmlを返す
  $(this).html($(this).clone());
});

replaceAll - 引数で指定した要素を指定した要素と入れ替える

$("#replaceAll").on("click",function(){
  $("<p>入れ替え</p>").replaceAll($(this));
});

replaceWith - 指定した要素と引数で指定した要素を入れ替える

$("#replaceWith").on("click",function(){
  $(this).replaceWith($("<p>入れ替え</p>"));
});

text - テキストの取得と書き換え

$("#text").on("click",function(){
  alert($(this).text());//テキストの取得
  $(this).text("差し替え");//差し替え
});

wrap - 指定した親要素で囲む

$("#wrap").on("click",function(){
  $(this).wrap("<div style='padding: 10px; background-color: red;' />");
});

unwrap - 親要素を削除

$("#unwrap").on("click",function(){
  $(this).children("p").unwrap();
});

wrapInner - 指定した要素の中に子要素を入れる

$("#wrapInner").on("click",function(){
  $(this).wrapInner("<p style='padding: 10px; background-color: red;' />");
});

wrapAll - 指定した要素全てを親要素で囲む

$("#wrapAll").on("click",function(){
  $("button").wrapAll("<div style='padding: 10px; background-color: red;' />");
});

jQueryのDOM操作メソッド 〜エフェクト編〜

fadeOut - 要素をフェードアウトして非表示

fadeOutTarget
$("#fadeOut").on("click",function(){
  $(this).next(".fadeOutTarget").fadeOut("fast",function(){
    console.log(this);//アニメーション完了後にしたい処理
  });
});

fadeIn - 要素をフェードインして表示

$("#fadeIn").on("click",function(){
  $(this).next(".fadeInTarget").fadeIn("slow",function(){
    console.log(this);//アニメーション完了後にしたい処理
  });
});

fadeToggle - fadeInとfadeOutの切り替え

fadeToggleTarget
$("#fadeToggle").on("click",function(){
  $(this).next(".fadeToggleTarget").fadeToggle("normal",function(){
    console.log(this);//アニメーション完了後にしたい処理
  });
});

fadeTo - 指定したアニメーションでフェード処理

fadeToTarget
$("#fadeTo").on("click",function(){
  $(this).next(".fadeToTarget").fadeTo(1000,0.3,function(){
    console.log(this);//アニメーション完了後にしたい処理
  });
});

toggle - showとhideの切り替え

toggleTarget
$("#toggle").on("click",function(){
  $(this).next(".toggleTarget").toggle(1000,function(){
    console.log(this);//アニメーション完了後にしたい処理
  });
});

slideDown - スライドで要素を表示

$("#slideDown").on("click",function(){
  $(this).next(".slideDownTarget").slideDown(1000,function(){
    console.log(this);//アニメーション完了後にしたい処理
  });
});

slideUp - スライドで要素を非表示

slideUpTarget
$("#slideUp").on("click",function(){
  $(this).next(".slideUpTarget").slideUp(1000,function(){
      console.log(this);//アニメーション完了後にしたい処理
  });
});

slideToggle - slideDownとslideUpの切り替え

slideToggleTarget
$("#slideToggle").on("click",function(){
  $(this).next(".slideToggleTarget").slideToggle(1000,function(){
      console.log(this);//アニメーション完了後にしたい処理
  });
});

animate - 指定したcssのアニメーションの指定

animateTarget
$("#animate").on("click",function(){
  var animeteData = ({
    "background-color":"red",
    "color":"black",
    "height":"100px"
  });
  $(this).next(".animateTarget").animate(animeteData,"normal","linear",function(){
    console.log(this);//アニメーション完了後にしたい処理
  });
});

jQueryのDOM操作メソッド 〜属性編〜

jQueryのDOM操作系のメソッドについてまとめておく

追加していく予定

.addClass - クラスを追加する

$("#addClass").on("click",function(){
  $(this).addClass("add");
  $(this).addClass("add2 add3");//複数指定
});

.attr - 属性の取得

$("#attr").on("click",function(){
  alert($(this).attr("id"));
  $(this).attr("id","attr2");//第二引数に変更したい値を指定できる
});

.hasClass - そのクラス名があるかどうか

$("#hasClass").on("click",function(){
  console.log($(this).hasClass("btn"));//true
  console.log($(this).hasClass("btn2"));//false
});

.prop - プロパティのチェック

$("#prop").on("click",function(){
  console.log($("input[name='checked']").prop("checked"));//true
  console.log($("input[name='unchecked']").prop("checked"));//false
  $("input[name='unchecked']").prop("checked",true);//trueに変更
});

.removeAttr - 指定した属性の削除

$("#removeAttr").on("click",function(){
  $(this).removeAttr("id");
});

.removeClass - 指定したクラス名の削除

$("#removeClass").on("click",function(){
  $(this).removeClass("btn");//複数指定で全部消したい場合はからで良い
});

.removeProp

プロパティの削除

$("#removeProp").on("click",function(){
  $("input[name='removePropTarget']").removeProp("disabled");
});

.toggleClass - 指定したクラスのon/offを切り替える

$("#toggleClass").on("click",function(){
  $(this).toggleClass("btn");//複数指定で全部消したい場合はからで良い
  $(this).toggleClass("btn",false);//第二引数にboolでtrueの場合は追加してfalseの場合は削除する
  $(this).toggleClass(false);//第一引数にboolを指定すると追加もしくは削除する
});

toggleClassが一番使えそう
おわり

Bootstrap3のブレイクポイント

v.3の話
4のことはまだ導入してないから知らん

クラス名 breakpoint 対象
col-xs-x ~767px スマホ
col-sm-x 768~991px タブレット
col-md-x 992~1199px デスクトップ
col-lg-x 1200px~ デスクトップ

visible-sm / hidden-sm で対象の時に表示・非表示を切り替えてくれる

MySQLのORDER BY でNULLを最後にする

※過去ブログの転記

 

NULLを含むカラムでORDER BYする

SELECT num
FROM tbl
ORDER BY num ASC

num
NULL
NULL
NULL
1
2
4
6
9

普通に昇順指定するとNULLが最初に来てしまうのて下記のように修正

SELECT num
FROM tbl
ORDER BY num IS NULL ASC , num ASC

num
1
2
4
6
9
NULL
NULL
NULL